restapi.go 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains functions for interacting with the Discord REST/JSON API
  7. // at the lowest level.
  8. package discordgo
  9. import (
  10. "bytes"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "image"
  15. _ "image/jpeg" // For JPEG decoding
  16. _ "image/png" // For PNG decoding
  17. "io"
  18. "io/ioutil"
  19. "log"
  20. "mime/multipart"
  21. "net/http"
  22. "net/textproto"
  23. "net/url"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. // All error constants
  29. var (
  30. ErrJSONUnmarshal = errors.New("json unmarshal")
  31. ErrStatusOffline = errors.New("You can't set your Status to offline")
  32. ErrVerificationLevelBounds = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  33. ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1")
  34. ErrGuildNoIcon = errors.New("guild does not have an icon set")
  35. ErrGuildNoSplash = errors.New("guild does not have a splash set")
  36. )
  37. // Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr
  38. func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
  39. return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0])
  40. }
  41. // RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data.
  42. func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string) (response []byte, err error) {
  43. var body []byte
  44. if data != nil {
  45. body, err = json.Marshal(data)
  46. if err != nil {
  47. return
  48. }
  49. }
  50. return s.request(method, urlStr, "application/json", body, bucketID, 0)
  51. }
  52. // request makes a (GET/POST/...) Requests to Discord REST API.
  53. // Sequence is the sequence number, if it fails with a 502 it will
  54. // retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries
  55. func (s *Session) request(method, urlStr, contentType string, b []byte, bucketID string, sequence int) (response []byte, err error) {
  56. if bucketID == "" {
  57. bucketID = strings.SplitN(urlStr, "?", 2)[0]
  58. }
  59. bucket := s.ratelimiter.LockBucket(bucketID)
  60. if s.Debug {
  61. log.Printf("API REQUEST %8s :: %s\n", method, urlStr)
  62. log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b))
  63. }
  64. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
  65. if err != nil {
  66. bucket.Release(nil)
  67. return
  68. }
  69. // Not used on initial login..
  70. // TODO: Verify if a login, otherwise complain about no-token
  71. if s.Token != "" {
  72. req.Header.Set("authorization", s.Token)
  73. }
  74. req.Header.Set("Content-Type", contentType)
  75. // TODO: Make a configurable static variable.
  76. req.Header.Set("User-Agent", fmt.Sprintf("DiscordBot (https://github.com/bwmarrin/discordgo, v%s)", VERSION))
  77. if s.Debug {
  78. for k, v := range req.Header {
  79. log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
  80. }
  81. }
  82. resp, err := s.Client.Do(req)
  83. if err != nil {
  84. bucket.Release(nil)
  85. return
  86. }
  87. defer func() {
  88. err2 := resp.Body.Close()
  89. if err2 != nil {
  90. log.Println("error closing resp body")
  91. }
  92. }()
  93. err = bucket.Release(resp.Header)
  94. if err != nil {
  95. return
  96. }
  97. response, err = ioutil.ReadAll(resp.Body)
  98. if err != nil {
  99. return
  100. }
  101. if s.Debug {
  102. log.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
  103. for k, v := range resp.Header {
  104. log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
  105. }
  106. log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response)
  107. }
  108. switch resp.StatusCode {
  109. case http.StatusOK:
  110. case http.StatusCreated:
  111. case http.StatusNoContent:
  112. // TODO check for 401 response, invalidate token if we get one.
  113. case http.StatusBadGateway:
  114. // Retry sending request if possible
  115. if sequence < s.MaxRestRetries {
  116. s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status)
  117. response, err = s.request(method, urlStr, contentType, b, bucketID, sequence+1)
  118. } else {
  119. err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response)
  120. }
  121. case 429: // TOO MANY REQUESTS - Rate limiting
  122. rl := TooManyRequests{}
  123. err = json.Unmarshal(response, &rl)
  124. if err != nil {
  125. s.log(LogError, "rate limit unmarshal error, %s", err)
  126. return
  127. }
  128. s.log(LogInformational, "Rate Limiting %s, retry in %d", urlStr, rl.RetryAfter)
  129. s.handleEvent(rateLimitEventType, RateLimit{TooManyRequests: &rl, URL: urlStr})
  130. time.Sleep(rl.RetryAfter * time.Millisecond)
  131. // we can make the above smarter
  132. // this method can cause longer delays than required
  133. response, err = s.request(method, urlStr, contentType, b, bucketID, sequence)
  134. default: // Error condition
  135. err = newRestError(req, resp, response)
  136. }
  137. return
  138. }
  139. func unmarshal(data []byte, v interface{}) error {
  140. err := json.Unmarshal(data, v)
  141. if err != nil {
  142. return ErrJSONUnmarshal
  143. }
  144. return nil
  145. }
  146. // ------------------------------------------------------------------------------------------------
  147. // Functions specific to Discord Sessions
  148. // ------------------------------------------------------------------------------------------------
  149. // Login asks the Discord server for an authentication token.
  150. //
  151. // NOTE: While email/pass authentication is supported by DiscordGo it is
  152. // HIGHLY DISCOURAGED by Discord. Please only use email/pass to obtain a token
  153. // and then use that authentication token for all future connections.
  154. // Also, doing any form of automation with a user (non Bot) account may result
  155. // in that account being permanently banned from Discord.
  156. func (s *Session) Login(email, password string) (err error) {
  157. data := struct {
  158. Email string `json:"email"`
  159. Password string `json:"password"`
  160. }{email, password}
  161. response, err := s.RequestWithBucketID("POST", EndpointLogin, data, EndpointLogin)
  162. if err != nil {
  163. return
  164. }
  165. temp := struct {
  166. Token string `json:"token"`
  167. MFA bool `json:"mfa"`
  168. }{}
  169. err = unmarshal(response, &temp)
  170. if err != nil {
  171. return
  172. }
  173. s.Token = temp.Token
  174. s.MFA = temp.MFA
  175. return
  176. }
  177. // Register sends a Register request to Discord, and returns the authentication token
  178. // Note that this account is temporary and should be verified for future use.
  179. // Another option is to save the authentication token external, but this isn't recommended.
  180. func (s *Session) Register(username string) (token string, err error) {
  181. data := struct {
  182. Username string `json:"username"`
  183. }{username}
  184. response, err := s.RequestWithBucketID("POST", EndpointRegister, data, EndpointRegister)
  185. if err != nil {
  186. return
  187. }
  188. temp := struct {
  189. Token string `json:"token"`
  190. }{}
  191. err = unmarshal(response, &temp)
  192. if err != nil {
  193. return
  194. }
  195. token = temp.Token
  196. return
  197. }
  198. // Logout sends a logout request to Discord.
  199. // This does not seem to actually invalidate the token. So you can still
  200. // make API calls even after a Logout. So, it seems almost pointless to
  201. // even use.
  202. func (s *Session) Logout() (err error) {
  203. // _, err = s.Request("POST", LOGOUT, fmt.Sprintf(`{"token": "%s"}`, s.Token))
  204. if s.Token == "" {
  205. return
  206. }
  207. data := struct {
  208. Token string `json:"token"`
  209. }{s.Token}
  210. _, err = s.RequestWithBucketID("POST", EndpointLogout, data, EndpointLogout)
  211. return
  212. }
  213. // ------------------------------------------------------------------------------------------------
  214. // Functions specific to Discord Users
  215. // ------------------------------------------------------------------------------------------------
  216. // User returns the user details of the given userID
  217. // userID : A user ID or "@me" which is a shortcut of current user ID
  218. func (s *Session) User(userID string) (st *User, err error) {
  219. body, err := s.RequestWithBucketID("GET", EndpointUser(userID), nil, EndpointUsers)
  220. if err != nil {
  221. return
  222. }
  223. err = unmarshal(body, &st)
  224. return
  225. }
  226. // UserAvatar is deprecated. Please use UserAvatarDecode
  227. // userID : A user ID or "@me" which is a shortcut of current user ID
  228. func (s *Session) UserAvatar(userID string) (img image.Image, err error) {
  229. u, err := s.User(userID)
  230. if err != nil {
  231. return
  232. }
  233. img, err = s.UserAvatarDecode(u)
  234. return
  235. }
  236. // UserAvatarDecode returns an image.Image of a user's Avatar
  237. // user : The user which avatar should be retrieved
  238. func (s *Session) UserAvatarDecode(u *User) (img image.Image, err error) {
  239. body, err := s.RequestWithBucketID("GET", EndpointUserAvatar(u.ID, u.Avatar), nil, EndpointUserAvatar("", ""))
  240. if err != nil {
  241. return
  242. }
  243. img, _, err = image.Decode(bytes.NewReader(body))
  244. return
  245. }
  246. // UserUpdate updates a users settings.
  247. func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {
  248. // NOTE: Avatar must be either the hash/id of existing Avatar or
  249. // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
  250. // to set a new avatar.
  251. // If left blank, avatar will be set to null/blank
  252. data := struct {
  253. Email string `json:"email,omitempty"`
  254. Password string `json:"password,omitempty"`
  255. Username string `json:"username,omitempty"`
  256. Avatar string `json:"avatar,omitempty"`
  257. NewPassword string `json:"new_password,omitempty"`
  258. }{email, password, username, avatar, newPassword}
  259. body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers)
  260. if err != nil {
  261. return
  262. }
  263. err = unmarshal(body, &st)
  264. return
  265. }
  266. // UserSettings returns the settings for a given user
  267. func (s *Session) UserSettings() (st *Settings, err error) {
  268. body, err := s.RequestWithBucketID("GET", EndpointUserSettings("@me"), nil, EndpointUserSettings(""))
  269. if err != nil {
  270. return
  271. }
  272. err = unmarshal(body, &st)
  273. return
  274. }
  275. // UserUpdateStatus update the user status
  276. // status : The new status (Actual valid status are 'online','idle','dnd','invisible')
  277. func (s *Session) UserUpdateStatus(status Status) (st *Settings, err error) {
  278. if status == StatusOffline {
  279. err = ErrStatusOffline
  280. return
  281. }
  282. data := struct {
  283. Status Status `json:"status"`
  284. }{status}
  285. body, err := s.RequestWithBucketID("PATCH", EndpointUserSettings("@me"), data, EndpointUserSettings(""))
  286. if err != nil {
  287. return
  288. }
  289. err = unmarshal(body, &st)
  290. return
  291. }
  292. // UserChannels returns an array of Channel structures for all private
  293. // channels.
  294. func (s *Session) UserChannels() (st []*Channel, err error) {
  295. body, err := s.RequestWithBucketID("GET", EndpointUserChannels("@me"), nil, EndpointUserChannels(""))
  296. if err != nil {
  297. return
  298. }
  299. err = unmarshal(body, &st)
  300. return
  301. }
  302. // UserChannelCreate creates a new User (Private) Channel with another User
  303. // recipientID : A user ID for the user to which this channel is opened with.
  304. func (s *Session) UserChannelCreate(recipientID string) (st *Channel, err error) {
  305. data := struct {
  306. RecipientID string `json:"recipient_id"`
  307. }{recipientID}
  308. body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""))
  309. if err != nil {
  310. return
  311. }
  312. err = unmarshal(body, &st)
  313. return
  314. }
  315. // UserGuilds returns an array of UserGuild structures for all guilds.
  316. // limit : The number guilds that can be returned. (max 100)
  317. // beforeID : If provided all guilds returned will be before given ID.
  318. // afterID : If provided all guilds returned will be after given ID.
  319. func (s *Session) UserGuilds(limit int, beforeID, afterID string) (st []*UserGuild, err error) {
  320. v := url.Values{}
  321. if limit > 0 {
  322. v.Set("limit", strconv.Itoa(limit))
  323. }
  324. if afterID != "" {
  325. v.Set("after", afterID)
  326. }
  327. if beforeID != "" {
  328. v.Set("before", beforeID)
  329. }
  330. uri := EndpointUserGuilds("@me")
  331. if len(v) > 0 {
  332. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  333. }
  334. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""))
  335. if err != nil {
  336. return
  337. }
  338. err = unmarshal(body, &st)
  339. return
  340. }
  341. // UserGuildSettingsEdit Edits the users notification settings for a guild
  342. // guildID : The ID of the guild to edit the settings on
  343. // settings : The settings to update
  344. func (s *Session) UserGuildSettingsEdit(guildID string, settings *UserGuildSettingsEdit) (st *UserGuildSettings, err error) {
  345. body, err := s.RequestWithBucketID("PATCH", EndpointUserGuildSettings("@me", guildID), settings, EndpointUserGuildSettings("", guildID))
  346. if err != nil {
  347. return
  348. }
  349. err = unmarshal(body, &st)
  350. return
  351. }
  352. // UserChannelPermissions returns the permission of a user in a channel.
  353. // userID : The ID of the user to calculate permissions for.
  354. // channelID : The ID of the channel to calculate permission for.
  355. //
  356. // NOTE: This function is now deprecated and will be removed in the future.
  357. // Please see the same function inside state.go
  358. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int, err error) {
  359. // Try to just get permissions from state.
  360. apermissions, err = s.State.UserChannelPermissions(userID, channelID)
  361. if err == nil {
  362. return
  363. }
  364. // Otherwise try get as much data from state as possible, falling back to the network.
  365. channel, err := s.State.Channel(channelID)
  366. if err != nil || channel == nil {
  367. channel, err = s.Channel(channelID)
  368. if err != nil {
  369. return
  370. }
  371. }
  372. guild, err := s.State.Guild(channel.GuildID)
  373. if err != nil || guild == nil {
  374. guild, err = s.Guild(channel.GuildID)
  375. if err != nil {
  376. return
  377. }
  378. }
  379. if userID == guild.OwnerID {
  380. apermissions = PermissionAll
  381. return
  382. }
  383. member, err := s.State.Member(guild.ID, userID)
  384. if err != nil || member == nil {
  385. member, err = s.GuildMember(guild.ID, userID)
  386. if err != nil {
  387. return
  388. }
  389. }
  390. return memberPermissions(guild, channel, member), nil
  391. }
  392. // Calculates the permissions for a member.
  393. // https://support.discordapp.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured-
  394. func memberPermissions(guild *Guild, channel *Channel, member *Member) (apermissions int) {
  395. userID := member.User.ID
  396. if userID == guild.OwnerID {
  397. apermissions = PermissionAll
  398. return
  399. }
  400. for _, role := range guild.Roles {
  401. if role.ID == guild.ID {
  402. apermissions |= role.Permissions
  403. break
  404. }
  405. }
  406. for _, role := range guild.Roles {
  407. for _, roleID := range member.Roles {
  408. if role.ID == roleID {
  409. apermissions |= role.Permissions
  410. break
  411. }
  412. }
  413. }
  414. if apermissions&PermissionAdministrator == PermissionAdministrator {
  415. apermissions |= PermissionAll
  416. }
  417. // Apply @everyone overrides from the channel.
  418. for _, overwrite := range channel.PermissionOverwrites {
  419. if guild.ID == overwrite.ID {
  420. apermissions &= ^overwrite.Deny
  421. apermissions |= overwrite.Allow
  422. break
  423. }
  424. }
  425. denies := 0
  426. allows := 0
  427. // Member overwrites can override role overrides, so do two passes
  428. for _, overwrite := range channel.PermissionOverwrites {
  429. for _, roleID := range member.Roles {
  430. if overwrite.Type == "role" && roleID == overwrite.ID {
  431. denies |= overwrite.Deny
  432. allows |= overwrite.Allow
  433. break
  434. }
  435. }
  436. }
  437. apermissions &= ^denies
  438. apermissions |= allows
  439. for _, overwrite := range channel.PermissionOverwrites {
  440. if overwrite.Type == "member" && overwrite.ID == userID {
  441. apermissions &= ^overwrite.Deny
  442. apermissions |= overwrite.Allow
  443. break
  444. }
  445. }
  446. if apermissions&PermissionAdministrator == PermissionAdministrator {
  447. apermissions |= PermissionAllChannel
  448. }
  449. return apermissions
  450. }
  451. // ------------------------------------------------------------------------------------------------
  452. // Functions specific to Discord Guilds
  453. // ------------------------------------------------------------------------------------------------
  454. // Guild returns a Guild structure of a specific Guild.
  455. // guildID : The ID of a Guild
  456. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  457. if s.StateEnabled {
  458. // Attempt to grab the guild from State first.
  459. st, err = s.State.Guild(guildID)
  460. if err == nil {
  461. return
  462. }
  463. }
  464. body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  465. if err != nil {
  466. return
  467. }
  468. err = unmarshal(body, &st)
  469. return
  470. }
  471. // GuildCreate creates a new Guild
  472. // name : A name for the Guild (2-100 characters)
  473. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  474. data := struct {
  475. Name string `json:"name"`
  476. }{name}
  477. body, err := s.RequestWithBucketID("POST", EndpointGuilds, data, EndpointGuilds)
  478. if err != nil {
  479. return
  480. }
  481. err = unmarshal(body, &st)
  482. return
  483. }
  484. // GuildEdit edits a new Guild
  485. // guildID : The ID of a Guild
  486. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  487. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  488. // Bounds checking for VerificationLevel, interval: [0, 3]
  489. if g.VerificationLevel != nil {
  490. val := *g.VerificationLevel
  491. if val < 0 || val > 3 {
  492. err = ErrVerificationLevelBounds
  493. return
  494. }
  495. }
  496. //Bounds checking for regions
  497. if g.Region != "" {
  498. isValid := false
  499. regions, _ := s.VoiceRegions()
  500. for _, r := range regions {
  501. if g.Region == r.ID {
  502. isValid = true
  503. }
  504. }
  505. if !isValid {
  506. var valid []string
  507. for _, r := range regions {
  508. valid = append(valid, r.ID)
  509. }
  510. err = fmt.Errorf("Region not a valid region (%q)", valid)
  511. return
  512. }
  513. }
  514. body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID))
  515. if err != nil {
  516. return
  517. }
  518. err = unmarshal(body, &st)
  519. return
  520. }
  521. // GuildDelete deletes a Guild.
  522. // guildID : The ID of a Guild
  523. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  524. body, err := s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  525. if err != nil {
  526. return
  527. }
  528. err = unmarshal(body, &st)
  529. return
  530. }
  531. // GuildLeave leaves a Guild.
  532. // guildID : The ID of a Guild
  533. func (s *Session) GuildLeave(guildID string) (err error) {
  534. _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID))
  535. return
  536. }
  537. // GuildBans returns an array of User structures for all bans of a
  538. // given guild.
  539. // guildID : The ID of a Guild.
  540. func (s *Session) GuildBans(guildID string) (st []*GuildBan, err error) {
  541. body, err := s.RequestWithBucketID("GET", EndpointGuildBans(guildID), nil, EndpointGuildBans(guildID))
  542. if err != nil {
  543. return
  544. }
  545. err = unmarshal(body, &st)
  546. return
  547. }
  548. // GuildBanCreate bans the given user from the given guild.
  549. // guildID : The ID of a Guild.
  550. // userID : The ID of a User
  551. // days : The number of days of previous comments to delete.
  552. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  553. return s.GuildBanCreateWithReason(guildID, userID, "", days)
  554. }
  555. // GuildBanCreateWithReason bans the given user from the given guild also providing a reaso.
  556. // guildID : The ID of a Guild.
  557. // userID : The ID of a User
  558. // reason : The reason for this ban
  559. // days : The number of days of previous comments to delete.
  560. func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int) (err error) {
  561. uri := EndpointGuildBan(guildID, userID)
  562. queryParams := url.Values{}
  563. if days > 0 {
  564. queryParams.Set("delete-message-days", strconv.Itoa(days))
  565. }
  566. if reason != "" {
  567. queryParams.Set("reason", reason)
  568. }
  569. if len(queryParams) > 0 {
  570. uri += "?" + queryParams.Encode()
  571. }
  572. _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""))
  573. return
  574. }
  575. // GuildBanDelete removes the given user from the guild bans
  576. // guildID : The ID of a Guild.
  577. // userID : The ID of a User
  578. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  579. _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""))
  580. return
  581. }
  582. // GuildMembers returns a list of members for a guild.
  583. // guildID : The ID of a Guild.
  584. // after : The id of the member to return members after
  585. // limit : max number of members to return (max 1000)
  586. func (s *Session) GuildMembers(guildID string, after string, limit int) (st []*Member, err error) {
  587. uri := EndpointGuildMembers(guildID)
  588. v := url.Values{}
  589. if after != "" {
  590. v.Set("after", after)
  591. }
  592. if limit > 0 {
  593. v.Set("limit", strconv.Itoa(limit))
  594. }
  595. if len(v) > 0 {
  596. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  597. }
  598. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID))
  599. if err != nil {
  600. return
  601. }
  602. err = unmarshal(body, &st)
  603. return
  604. }
  605. // GuildMember returns a member of a guild.
  606. // guildID : The ID of a Guild.
  607. // userID : The ID of a User
  608. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  609. body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""))
  610. if err != nil {
  611. return
  612. }
  613. err = unmarshal(body, &st)
  614. return
  615. }
  616. // GuildMemberDelete removes the given user from the given guild.
  617. // guildID : The ID of a Guild.
  618. // userID : The ID of a User
  619. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  620. return s.GuildMemberDeleteWithReason(guildID, userID, "")
  621. }
  622. // GuildMemberDeleteWithReason removes the given user from the given guild.
  623. // guildID : The ID of a Guild.
  624. // userID : The ID of a User
  625. // reason : The reason for the kick
  626. func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string) (err error) {
  627. uri := EndpointGuildMember(guildID, userID)
  628. if reason != "" {
  629. uri += "?reason=" + url.QueryEscape(reason)
  630. }
  631. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""))
  632. return
  633. }
  634. // GuildMemberEdit edits the roles of a member.
  635. // guildID : The ID of a Guild.
  636. // userID : The ID of a User.
  637. // roles : A list of role ID's to set on the member.
  638. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  639. data := struct {
  640. Roles []string `json:"roles"`
  641. }{roles}
  642. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  643. if err != nil {
  644. return
  645. }
  646. return
  647. }
  648. // GuildMemberMove moves a guild member from one voice channel to another/none
  649. // guildID : The ID of a Guild.
  650. // userID : The ID of a User.
  651. // channelID : The ID of a channel to move user to, or null?
  652. // NOTE : I am not entirely set on the name of this function and it may change
  653. // prior to the final 1.0.0 release of Discordgo
  654. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  655. data := struct {
  656. ChannelID string `json:"channel_id"`
  657. }{channelID}
  658. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  659. if err != nil {
  660. return
  661. }
  662. return
  663. }
  664. // GuildMemberNickname updates the nickname of a guild member
  665. // guildID : The ID of a guild
  666. // userID : The ID of a user
  667. // userID : The ID of a user or "@me" which is a shortcut of the current user ID
  668. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  669. data := struct {
  670. Nick string `json:"nick"`
  671. }{nickname}
  672. if userID == "@me" {
  673. userID += "/nick"
  674. }
  675. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  676. return
  677. }
  678. // GuildMemberRoleAdd adds the specified role to a given member
  679. // guildID : The ID of a Guild.
  680. // userID : The ID of a User.
  681. // roleID : The ID of a Role to be assigned to the user.
  682. func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string) (err error) {
  683. _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  684. return
  685. }
  686. // GuildMemberRoleRemove removes the specified role to a given member
  687. // guildID : The ID of a Guild.
  688. // userID : The ID of a User.
  689. // roleID : The ID of a Role to be removed from the user.
  690. func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string) (err error) {
  691. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  692. return
  693. }
  694. // GuildChannels returns an array of Channel structures for all channels of a
  695. // given guild.
  696. // guildID : The ID of a Guild.
  697. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  698. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0)
  699. if err != nil {
  700. return
  701. }
  702. err = unmarshal(body, &st)
  703. return
  704. }
  705. // GuildChannelCreate creates a new channel in the given guild
  706. // guildID : The ID of a Guild.
  707. // name : Name of the channel (2-100 chars length)
  708. // ctype : Tpye of the channel (voice or text)
  709. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st *Channel, err error) {
  710. data := struct {
  711. Name string `json:"name"`
  712. Type string `json:"type"`
  713. }{name, ctype}
  714. body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  715. if err != nil {
  716. return
  717. }
  718. err = unmarshal(body, &st)
  719. return
  720. }
  721. // GuildChannelsReorder updates the order of channels in a guild
  722. // guildID : The ID of a Guild.
  723. // channels : Updated channels.
  724. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  725. _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), channels, EndpointGuildChannels(guildID))
  726. return
  727. }
  728. // GuildInvites returns an array of Invite structures for the given guild
  729. // guildID : The ID of a Guild.
  730. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  731. body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInivtes(guildID))
  732. if err != nil {
  733. return
  734. }
  735. err = unmarshal(body, &st)
  736. return
  737. }
  738. // GuildRoles returns all roles for a given guild.
  739. // guildID : The ID of a Guild.
  740. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  741. body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  742. if err != nil {
  743. return
  744. }
  745. err = unmarshal(body, &st)
  746. return // TODO return pointer
  747. }
  748. // GuildRoleCreate returns a new Guild Role.
  749. // guildID: The ID of a Guild.
  750. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  751. body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  752. if err != nil {
  753. return
  754. }
  755. err = unmarshal(body, &st)
  756. return
  757. }
  758. // GuildRoleEdit updates an existing Guild Role with new values
  759. // guildID : The ID of a Guild.
  760. // roleID : The ID of a Role.
  761. // name : The name of the Role.
  762. // color : The color of the role (decimal, not hex).
  763. // hoist : Whether to display the role's users separately.
  764. // perm : The permissions for the role.
  765. // mention : Whether this role is mentionable
  766. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int, mention bool) (st *Role, err error) {
  767. // Prevent sending a color int that is too big.
  768. if color > 0xFFFFFF {
  769. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  770. }
  771. data := struct {
  772. Name string `json:"name"` // The role's name (overwrites existing)
  773. Color int `json:"color"` // The color the role should have (as a decimal, not hex)
  774. Hoist bool `json:"hoist"` // Whether to display the role's users separately
  775. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  776. Mentionable bool `json:"mentionable"` // Whether this role is mentionable
  777. }{name, color, hoist, perm, mention}
  778. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""))
  779. if err != nil {
  780. return
  781. }
  782. err = unmarshal(body, &st)
  783. return
  784. }
  785. // GuildRoleReorder reoders guild roles
  786. // guildID : The ID of a Guild.
  787. // roles : A list of ordered roles.
  788. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  789. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID))
  790. if err != nil {
  791. return
  792. }
  793. err = unmarshal(body, &st)
  794. return
  795. }
  796. // GuildRoleDelete deletes an existing role.
  797. // guildID : The ID of a Guild.
  798. // roleID : The ID of a Role.
  799. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  800. _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""))
  801. return
  802. }
  803. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  804. // Requires 'KICK_MEMBER' permission.
  805. // guildID : The ID of a Guild.
  806. // days : The number of days to count prune for (1 or more).
  807. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  808. count = 0
  809. if days <= 0 {
  810. err = ErrPruneDaysBounds
  811. return
  812. }
  813. p := struct {
  814. Pruned uint32 `json:"pruned"`
  815. }{}
  816. uri := EndpointGuildPrune(guildID) + fmt.Sprintf("?days=%d", days)
  817. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  818. err = unmarshal(body, &p)
  819. if err != nil {
  820. return
  821. }
  822. count = p.Pruned
  823. return
  824. }
  825. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  826. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  827. // guildID : The ID of a Guild.
  828. // days : The number of days to count prune for (1 or more).
  829. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  830. count = 0
  831. if days <= 0 {
  832. err = ErrPruneDaysBounds
  833. return
  834. }
  835. data := struct {
  836. days uint32
  837. }{days}
  838. p := struct {
  839. Pruned uint32 `json:"pruned"`
  840. }{}
  841. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  842. if err != nil {
  843. return
  844. }
  845. err = unmarshal(body, &p)
  846. if err != nil {
  847. return
  848. }
  849. count = p.Pruned
  850. return
  851. }
  852. // GuildIntegrations returns an array of Integrations for a guild.
  853. // guildID : The ID of a Guild.
  854. func (s *Session) GuildIntegrations(guildID string) (st []*GuildIntegration, err error) {
  855. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  856. if err != nil {
  857. return
  858. }
  859. err = unmarshal(body, &st)
  860. return
  861. }
  862. // GuildIntegrationCreate creates a Guild Integration.
  863. // guildID : The ID of a Guild.
  864. // integrationType : The Integration type.
  865. // integrationID : The ID of an integration.
  866. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  867. data := struct {
  868. Type string `json:"type"`
  869. ID string `json:"id"`
  870. }{integrationType, integrationID}
  871. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  872. return
  873. }
  874. // GuildIntegrationEdit edits a Guild Integration.
  875. // guildID : The ID of a Guild.
  876. // integrationType : The Integration type.
  877. // integrationID : The ID of an integration.
  878. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  879. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  880. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  881. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  882. data := struct {
  883. ExpireBehavior int `json:"expire_behavior"`
  884. ExpireGracePeriod int `json:"expire_grace_period"`
  885. EnableEmoticons bool `json:"enable_emoticons"`
  886. }{expireBehavior, expireGracePeriod, enableEmoticons}
  887. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  888. return
  889. }
  890. // GuildIntegrationDelete removes the given integration from the Guild.
  891. // guildID : The ID of a Guild.
  892. // integrationID : The ID of an integration.
  893. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  894. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  895. return
  896. }
  897. // GuildIntegrationSync syncs an integration.
  898. // guildID : The ID of a Guild.
  899. // integrationID : The ID of an integration.
  900. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  901. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  902. return
  903. }
  904. // GuildIcon returns an image.Image of a guild icon.
  905. // guildID : The ID of a Guild.
  906. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  907. g, err := s.Guild(guildID)
  908. if err != nil {
  909. return
  910. }
  911. if g.Icon == "" {
  912. err = ErrGuildNoIcon
  913. return
  914. }
  915. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  916. if err != nil {
  917. return
  918. }
  919. img, _, err = image.Decode(bytes.NewReader(body))
  920. return
  921. }
  922. // GuildSplash returns an image.Image of a guild splash image.
  923. // guildID : The ID of a Guild.
  924. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  925. g, err := s.Guild(guildID)
  926. if err != nil {
  927. return
  928. }
  929. if g.Splash == "" {
  930. err = ErrGuildNoSplash
  931. return
  932. }
  933. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  934. if err != nil {
  935. return
  936. }
  937. img, _, err = image.Decode(bytes.NewReader(body))
  938. return
  939. }
  940. // GuildEmbed returns the embed for a Guild.
  941. // guildID : The ID of a Guild.
  942. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  943. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  944. if err != nil {
  945. return
  946. }
  947. err = unmarshal(body, &st)
  948. return
  949. }
  950. // GuildEmbedEdit returns the embed for a Guild.
  951. // guildID : The ID of a Guild.
  952. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  953. data := GuildEmbed{enabled, channelID}
  954. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  955. return
  956. }
  957. // ------------------------------------------------------------------------------------------------
  958. // Functions specific to Discord Channels
  959. // ------------------------------------------------------------------------------------------------
  960. // Channel returns a Channel strucutre of a specific Channel.
  961. // channelID : The ID of the Channel you want returned.
  962. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  963. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  964. if err != nil {
  965. return
  966. }
  967. err = unmarshal(body, &st)
  968. return
  969. }
  970. // ChannelEdit edits the given channel
  971. // channelID : The ID of a Channel
  972. // name : The new name to assign the channel.
  973. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  974. data := struct {
  975. Name string `json:"name"`
  976. }{name}
  977. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  978. if err != nil {
  979. return
  980. }
  981. err = unmarshal(body, &st)
  982. return
  983. }
  984. // ChannelDelete deletes the given channel
  985. // channelID : The ID of a Channel
  986. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  987. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  988. if err != nil {
  989. return
  990. }
  991. err = unmarshal(body, &st)
  992. return
  993. }
  994. // ChannelTyping broadcasts to all members that authenticated user is typing in
  995. // the given channel.
  996. // channelID : The ID of a Channel
  997. func (s *Session) ChannelTyping(channelID string) (err error) {
  998. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  999. return
  1000. }
  1001. // ChannelMessages returns an array of Message structures for messages within
  1002. // a given channel.
  1003. // channelID : The ID of a Channel.
  1004. // limit : The number messages that can be returned. (max 100)
  1005. // beforeID : If provided all messages returned will be before given ID.
  1006. // afterID : If provided all messages returned will be after given ID.
  1007. // aroundID : If provided all messages returned will be around given ID.
  1008. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  1009. uri := EndpointChannelMessages(channelID)
  1010. v := url.Values{}
  1011. if limit > 0 {
  1012. v.Set("limit", strconv.Itoa(limit))
  1013. }
  1014. if afterID != "" {
  1015. v.Set("after", afterID)
  1016. }
  1017. if beforeID != "" {
  1018. v.Set("before", beforeID)
  1019. }
  1020. if aroundID != "" {
  1021. v.Set("around", aroundID)
  1022. }
  1023. if len(v) > 0 {
  1024. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1025. }
  1026. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  1027. if err != nil {
  1028. return
  1029. }
  1030. err = unmarshal(body, &st)
  1031. return
  1032. }
  1033. // ChannelMessage gets a single message by ID from a given channel.
  1034. // channeld : The ID of a Channel
  1035. // messageID : the ID of a Message
  1036. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  1037. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1038. if err != nil {
  1039. return
  1040. }
  1041. err = unmarshal(response, &st)
  1042. return
  1043. }
  1044. // ChannelMessageAck acknowledges and marks the given message as read
  1045. // channeld : The ID of a Channel
  1046. // messageID : the ID of a Message
  1047. // lastToken : token returned by last ack
  1048. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  1049. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  1050. if err != nil {
  1051. return
  1052. }
  1053. err = unmarshal(body, &st)
  1054. return
  1055. }
  1056. // ChannelMessageSend sends a message to the given channel.
  1057. // channelID : The ID of a Channel.
  1058. // content : The message to send.
  1059. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1060. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1061. Content: content,
  1062. })
  1063. }
  1064. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  1065. // ChannelMessageSendComplex sends a message to the given channel.
  1066. // channelID : The ID of a Channel.
  1067. // data : The message struct to send.
  1068. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1069. if data.Embed != nil && data.Embed.Type == "" {
  1070. data.Embed.Type = "rich"
  1071. }
  1072. endpoint := EndpointChannelMessages(channelID)
  1073. // TODO: Remove this when compatibility is not required.
  1074. files := data.Files
  1075. if data.File != nil {
  1076. if files == nil {
  1077. files = []*File{data.File}
  1078. } else {
  1079. err = fmt.Errorf("cannot specify both File and Files")
  1080. return
  1081. }
  1082. }
  1083. var response []byte
  1084. if len(files) > 0 {
  1085. body := &bytes.Buffer{}
  1086. bodywriter := multipart.NewWriter(body)
  1087. var payload []byte
  1088. payload, err = json.Marshal(data)
  1089. if err != nil {
  1090. return
  1091. }
  1092. var p io.Writer
  1093. h := make(textproto.MIMEHeader)
  1094. h.Set("Content-Disposition", `form-data; name="payload_json"`)
  1095. h.Set("Content-Type", "application/json")
  1096. p, err = bodywriter.CreatePart(h)
  1097. if err != nil {
  1098. return
  1099. }
  1100. if _, err = p.Write(payload); err != nil {
  1101. return
  1102. }
  1103. for i, file := range files {
  1104. h := make(textproto.MIMEHeader)
  1105. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file%d"; filename="%s"`, i, quoteEscaper.Replace(file.Name)))
  1106. contentType := file.ContentType
  1107. if contentType == "" {
  1108. contentType = "application/octet-stream"
  1109. }
  1110. h.Set("Content-Type", contentType)
  1111. p, err = bodywriter.CreatePart(h)
  1112. if err != nil {
  1113. return
  1114. }
  1115. if _, err = io.Copy(p, file.Reader); err != nil {
  1116. return
  1117. }
  1118. }
  1119. err = bodywriter.Close()
  1120. if err != nil {
  1121. return
  1122. }
  1123. response, err = s.request("POST", endpoint, bodywriter.FormDataContentType(), body.Bytes(), endpoint, 0)
  1124. } else {
  1125. response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1126. }
  1127. if err != nil {
  1128. return
  1129. }
  1130. err = unmarshal(response, &st)
  1131. return
  1132. }
  1133. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1134. // channelID : The ID of a Channel.
  1135. // content : The message to send.
  1136. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1137. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1138. Content: content,
  1139. Tts: true,
  1140. })
  1141. }
  1142. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1143. // channelID : The ID of a Channel.
  1144. // embed : The embed data to send.
  1145. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1146. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1147. Embed: embed,
  1148. })
  1149. }
  1150. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1151. // the given content.
  1152. // channelID : The ID of a Channel
  1153. // messageID : The ID of a Message
  1154. // content : The contents of the message
  1155. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1156. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content))
  1157. }
  1158. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1159. // the given MessageEdit struct
  1160. func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) {
  1161. if m.Embed != nil && m.Embed.Type == "" {
  1162. m.Embed.Type = "rich"
  1163. }
  1164. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, ""))
  1165. if err != nil {
  1166. return
  1167. }
  1168. err = unmarshal(response, &st)
  1169. return
  1170. }
  1171. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1172. // channelID : The ID of a Channel
  1173. // messageID : The ID of a Message
  1174. // embed : The embed data to send
  1175. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1176. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbed(embed))
  1177. }
  1178. // ChannelMessageDelete deletes a message from the Channel.
  1179. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1180. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1181. return
  1182. }
  1183. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1184. // If only one messageID is in the slice call channelMessageDelete funciton.
  1185. // If the slice is empty do nothing.
  1186. // channelID : The ID of the channel for the messages to delete.
  1187. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1188. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1189. if len(messages) == 0 {
  1190. return
  1191. }
  1192. if len(messages) == 1 {
  1193. err = s.ChannelMessageDelete(channelID, messages[0])
  1194. return
  1195. }
  1196. if len(messages) > 100 {
  1197. messages = messages[:100]
  1198. }
  1199. data := struct {
  1200. Messages []string `json:"messages"`
  1201. }{messages}
  1202. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1203. return
  1204. }
  1205. // ChannelMessagePin pins a message within a given channel.
  1206. // channelID: The ID of a channel.
  1207. // messageID: The ID of a message.
  1208. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1209. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1210. return
  1211. }
  1212. // ChannelMessageUnpin unpins a message within a given channel.
  1213. // channelID: The ID of a channel.
  1214. // messageID: The ID of a message.
  1215. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1216. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1217. return
  1218. }
  1219. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1220. // within a given channel
  1221. // channelID : The ID of a Channel.
  1222. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1223. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1224. if err != nil {
  1225. return
  1226. }
  1227. err = unmarshal(body, &st)
  1228. return
  1229. }
  1230. // ChannelFileSend sends a file to the given channel.
  1231. // channelID : The ID of a Channel.
  1232. // name: The name of the file.
  1233. // io.Reader : A reader for the file contents.
  1234. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (*Message, error) {
  1235. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}})
  1236. }
  1237. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1238. // DEPRECATED. Use ChannelMessageSendComplex instead.
  1239. // channelID : The ID of a Channel.
  1240. // content: Optional Message content.
  1241. // name: The name of the file.
  1242. // io.Reader : A reader for the file contents.
  1243. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (*Message, error) {
  1244. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content})
  1245. }
  1246. // ChannelInvites returns an array of Invite structures for the given channel
  1247. // channelID : The ID of a Channel
  1248. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1249. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1250. if err != nil {
  1251. return
  1252. }
  1253. err = unmarshal(body, &st)
  1254. return
  1255. }
  1256. // ChannelInviteCreate creates a new invite for the given channel.
  1257. // channelID : The ID of a Channel
  1258. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  1259. // and XkcdPass defined.
  1260. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1261. data := struct {
  1262. MaxAge int `json:"max_age"`
  1263. MaxUses int `json:"max_uses"`
  1264. Temporary bool `json:"temporary"`
  1265. XKCDPass string `json:"xkcdpass"`
  1266. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  1267. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1268. if err != nil {
  1269. return
  1270. }
  1271. err = unmarshal(body, &st)
  1272. return
  1273. }
  1274. // ChannelPermissionSet creates a Permission Override for the given channel.
  1275. // NOTE: This func name may changed. Using Set instead of Create because
  1276. // you can both create a new override or update an override with this function.
  1277. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1278. data := struct {
  1279. ID string `json:"id"`
  1280. Type string `json:"type"`
  1281. Allow int `json:"allow"`
  1282. Deny int `json:"deny"`
  1283. }{targetID, targetType, allow, deny}
  1284. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1285. return
  1286. }
  1287. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1288. // NOTE: Name of this func may change.
  1289. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1290. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1291. return
  1292. }
  1293. // ------------------------------------------------------------------------------------------------
  1294. // Functions specific to Discord Invites
  1295. // ------------------------------------------------------------------------------------------------
  1296. // Invite returns an Invite structure of the given invite
  1297. // inviteID : The invite code (or maybe xkcdpass?)
  1298. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1299. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1300. if err != nil {
  1301. return
  1302. }
  1303. err = unmarshal(body, &st)
  1304. return
  1305. }
  1306. // InviteDelete deletes an existing invite
  1307. // inviteID : the code (or maybe xkcdpass?) of an invite
  1308. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1309. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1310. if err != nil {
  1311. return
  1312. }
  1313. err = unmarshal(body, &st)
  1314. return
  1315. }
  1316. // InviteAccept accepts an Invite to a Guild or Channel
  1317. // inviteID : The invite code (or maybe xkcdpass?)
  1318. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1319. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1320. if err != nil {
  1321. return
  1322. }
  1323. err = unmarshal(body, &st)
  1324. return
  1325. }
  1326. // ------------------------------------------------------------------------------------------------
  1327. // Functions specific to Discord Voice
  1328. // ------------------------------------------------------------------------------------------------
  1329. // VoiceRegions returns the voice server regions
  1330. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1331. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1332. if err != nil {
  1333. return
  1334. }
  1335. err = unmarshal(body, &st)
  1336. return
  1337. }
  1338. // VoiceICE returns the voice server ICE information
  1339. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1340. body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce)
  1341. if err != nil {
  1342. return
  1343. }
  1344. err = unmarshal(body, &st)
  1345. return
  1346. }
  1347. // ------------------------------------------------------------------------------------------------
  1348. // Functions specific to Discord Websockets
  1349. // ------------------------------------------------------------------------------------------------
  1350. // Gateway returns the websocket Gateway address
  1351. func (s *Session) Gateway() (gateway string, err error) {
  1352. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1353. if err != nil {
  1354. return
  1355. }
  1356. temp := struct {
  1357. URL string `json:"url"`
  1358. }{}
  1359. err = unmarshal(response, &temp)
  1360. if err != nil {
  1361. return
  1362. }
  1363. gateway = temp.URL
  1364. // Ensure the gateway always has a trailing slash.
  1365. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1366. if !strings.HasSuffix(gateway, "/") {
  1367. gateway += "/"
  1368. }
  1369. return
  1370. }
  1371. // GatewayBot returns the websocket Gateway address and the recommended number of shards
  1372. func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) {
  1373. response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot)
  1374. if err != nil {
  1375. return
  1376. }
  1377. err = unmarshal(response, &st)
  1378. if err != nil {
  1379. return
  1380. }
  1381. // Ensure the gateway always has a trailing slash.
  1382. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1383. if !strings.HasSuffix(st.URL, "/") {
  1384. st.URL += "/"
  1385. }
  1386. return
  1387. }
  1388. // Functions specific to Webhooks
  1389. // WebhookCreate returns a new Webhook.
  1390. // channelID: The ID of a Channel.
  1391. // name : The name of the webhook.
  1392. // avatar : The avatar of the webhook.
  1393. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1394. data := struct {
  1395. Name string `json:"name"`
  1396. Avatar string `json:"avatar,omitempty"`
  1397. }{name, avatar}
  1398. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1399. if err != nil {
  1400. return
  1401. }
  1402. err = unmarshal(body, &st)
  1403. return
  1404. }
  1405. // ChannelWebhooks returns all webhooks for a given channel.
  1406. // channelID: The ID of a channel.
  1407. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1408. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1409. if err != nil {
  1410. return
  1411. }
  1412. err = unmarshal(body, &st)
  1413. return
  1414. }
  1415. // GuildWebhooks returns all webhooks for a given guild.
  1416. // guildID: The ID of a Guild.
  1417. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1418. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1419. if err != nil {
  1420. return
  1421. }
  1422. err = unmarshal(body, &st)
  1423. return
  1424. }
  1425. // Webhook returns a webhook for a given ID
  1426. // webhookID: The ID of a webhook.
  1427. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1428. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1429. if err != nil {
  1430. return
  1431. }
  1432. err = unmarshal(body, &st)
  1433. return
  1434. }
  1435. // WebhookWithToken returns a webhook for a given ID
  1436. // webhookID: The ID of a webhook.
  1437. // token : The auth token for the webhook.
  1438. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1439. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1440. if err != nil {
  1441. return
  1442. }
  1443. err = unmarshal(body, &st)
  1444. return
  1445. }
  1446. // WebhookEdit updates an existing Webhook.
  1447. // webhookID: The ID of a webhook.
  1448. // name : The name of the webhook.
  1449. // avatar : The avatar of the webhook.
  1450. func (s *Session) WebhookEdit(webhookID, name, avatar string) (st *Role, err error) {
  1451. data := struct {
  1452. Name string `json:"name,omitempty"`
  1453. Avatar string `json:"avatar,omitempty"`
  1454. }{name, avatar}
  1455. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1456. if err != nil {
  1457. return
  1458. }
  1459. err = unmarshal(body, &st)
  1460. return
  1461. }
  1462. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1463. // webhookID: The ID of a webhook.
  1464. // token : The auth token for the webhook.
  1465. // name : The name of the webhook.
  1466. // avatar : The avatar of the webhook.
  1467. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1468. data := struct {
  1469. Name string `json:"name,omitempty"`
  1470. Avatar string `json:"avatar,omitempty"`
  1471. }{name, avatar}
  1472. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1473. if err != nil {
  1474. return
  1475. }
  1476. err = unmarshal(body, &st)
  1477. return
  1478. }
  1479. // WebhookDelete deletes a webhook for a given ID
  1480. // webhookID: The ID of a webhook.
  1481. func (s *Session) WebhookDelete(webhookID string) (err error) {
  1482. _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1483. return
  1484. }
  1485. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1486. // webhookID: The ID of a webhook.
  1487. // token : The auth token for the webhook.
  1488. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1489. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1490. if err != nil {
  1491. return
  1492. }
  1493. err = unmarshal(body, &st)
  1494. return
  1495. }
  1496. // WebhookExecute executes a webhook.
  1497. // webhookID: The ID of a webhook.
  1498. // token : The auth token for the webhook
  1499. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (err error) {
  1500. uri := EndpointWebhookToken(webhookID, token)
  1501. if wait {
  1502. uri += "?wait=true"
  1503. }
  1504. _, err = s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))
  1505. return
  1506. }
  1507. // MessageReactionAdd creates an emoji reaction to a message.
  1508. // channelID : The channel ID.
  1509. // messageID : The message ID.
  1510. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1511. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1512. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1513. return err
  1514. }
  1515. // MessageReactionRemove deletes an emoji reaction to a message.
  1516. // channelID : The channel ID.
  1517. // messageID : The message ID.
  1518. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1519. // userID : @me or ID of the user to delete the reaction for.
  1520. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1521. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1522. return err
  1523. }
  1524. // MessageReactionsRemoveAll deletes all reactions from a message
  1525. // channelID : The channel ID
  1526. // messageID : The message ID.
  1527. func (s *Session) MessageReactionsRemoveAll(channelID, messageID string) error {
  1528. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID))
  1529. return err
  1530. }
  1531. // MessageReactions gets all the users reactions for a specific emoji.
  1532. // channelID : The channel ID.
  1533. // messageID : The message ID.
  1534. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1535. // limit : max number of users to return (max 100)
  1536. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int) (st []*User, err error) {
  1537. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1538. v := url.Values{}
  1539. if limit > 0 {
  1540. v.Set("limit", strconv.Itoa(limit))
  1541. }
  1542. if len(v) > 0 {
  1543. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1544. }
  1545. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1546. if err != nil {
  1547. return
  1548. }
  1549. err = unmarshal(body, &st)
  1550. return
  1551. }
  1552. // ------------------------------------------------------------------------------------------------
  1553. // Functions specific to user notes
  1554. // ------------------------------------------------------------------------------------------------
  1555. // UserNoteSet sets the note for a specific user.
  1556. func (s *Session) UserNoteSet(userID string, message string) (err error) {
  1557. data := struct {
  1558. Note string `json:"note"`
  1559. }{message}
  1560. _, err = s.RequestWithBucketID("PUT", EndpointUserNotes(userID), data, EndpointUserNotes(""))
  1561. return
  1562. }
  1563. // ------------------------------------------------------------------------------------------------
  1564. // Functions specific to Discord Relationships (Friends list)
  1565. // ------------------------------------------------------------------------------------------------
  1566. // RelationshipsGet returns an array of all the relationships of the user.
  1567. func (s *Session) RelationshipsGet() (r []*Relationship, err error) {
  1568. body, err := s.RequestWithBucketID("GET", EndpointRelationships(), nil, EndpointRelationships())
  1569. if err != nil {
  1570. return
  1571. }
  1572. err = unmarshal(body, &r)
  1573. return
  1574. }
  1575. // relationshipCreate creates a new relationship. (I.e. send or accept a friend request, block a user.)
  1576. // relationshipType : 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  1577. func (s *Session) relationshipCreate(userID string, relationshipType int) (err error) {
  1578. data := struct {
  1579. Type int `json:"type"`
  1580. }{relationshipType}
  1581. _, err = s.RequestWithBucketID("PUT", EndpointRelationship(userID), data, EndpointRelationships())
  1582. return
  1583. }
  1584. // RelationshipFriendRequestSend sends a friend request to a user.
  1585. // userID: ID of the user.
  1586. func (s *Session) RelationshipFriendRequestSend(userID string) (err error) {
  1587. err = s.relationshipCreate(userID, 4)
  1588. return
  1589. }
  1590. // RelationshipFriendRequestAccept accepts a friend request from a user.
  1591. // userID: ID of the user.
  1592. func (s *Session) RelationshipFriendRequestAccept(userID string) (err error) {
  1593. err = s.relationshipCreate(userID, 1)
  1594. return
  1595. }
  1596. // RelationshipUserBlock blocks a user.
  1597. // userID: ID of the user.
  1598. func (s *Session) RelationshipUserBlock(userID string) (err error) {
  1599. err = s.relationshipCreate(userID, 2)
  1600. return
  1601. }
  1602. // RelationshipDelete removes the relationship with a user.
  1603. // userID: ID of the user.
  1604. func (s *Session) RelationshipDelete(userID string) (err error) {
  1605. _, err = s.RequestWithBucketID("DELETE", EndpointRelationship(userID), nil, EndpointRelationships())
  1606. return
  1607. }
  1608. // RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with.
  1609. // userID: ID of the user.
  1610. func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) {
  1611. body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID))
  1612. if err != nil {
  1613. return
  1614. }
  1615. err = unmarshal(body, &mf)
  1616. return
  1617. }