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