restapi.go 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  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. // UserConnections returns the user's connections
  296. func (s *Session) UserConnections() (conn []*UserConnection, err error) {
  297. response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"))
  298. if err != nil {
  299. return nil, err
  300. }
  301. err = unmarshal(response, &conn)
  302. if err != nil {
  303. return
  304. }
  305. return
  306. }
  307. // UserChannels returns an array of Channel structures for all private
  308. // channels.
  309. func (s *Session) UserChannels() (st []*Channel, err error) {
  310. body, err := s.RequestWithBucketID("GET", EndpointUserChannels("@me"), nil, EndpointUserChannels(""))
  311. if err != nil {
  312. return
  313. }
  314. err = unmarshal(body, &st)
  315. return
  316. }
  317. // UserChannelCreate creates a new User (Private) Channel with another User
  318. // recipientID : A user ID for the user to which this channel is opened with.
  319. func (s *Session) UserChannelCreate(recipientID string) (st *Channel, err error) {
  320. data := struct {
  321. RecipientID string `json:"recipient_id"`
  322. }{recipientID}
  323. body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""))
  324. if err != nil {
  325. return
  326. }
  327. err = unmarshal(body, &st)
  328. return
  329. }
  330. // UserGuilds returns an array of UserGuild structures for all guilds.
  331. // limit : The number guilds that can be returned. (max 100)
  332. // beforeID : If provided all guilds returned will be before given ID.
  333. // afterID : If provided all guilds returned will be after given ID.
  334. func (s *Session) UserGuilds(limit int, beforeID, afterID string) (st []*UserGuild, err error) {
  335. v := url.Values{}
  336. if limit > 0 {
  337. v.Set("limit", strconv.Itoa(limit))
  338. }
  339. if afterID != "" {
  340. v.Set("after", afterID)
  341. }
  342. if beforeID != "" {
  343. v.Set("before", beforeID)
  344. }
  345. uri := EndpointUserGuilds("@me")
  346. if len(v) > 0 {
  347. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  348. }
  349. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""))
  350. if err != nil {
  351. return
  352. }
  353. err = unmarshal(body, &st)
  354. return
  355. }
  356. // UserGuildSettingsEdit Edits the users notification settings for a guild
  357. // guildID : The ID of the guild to edit the settings on
  358. // settings : The settings to update
  359. func (s *Session) UserGuildSettingsEdit(guildID string, settings *UserGuildSettingsEdit) (st *UserGuildSettings, err error) {
  360. body, err := s.RequestWithBucketID("PATCH", EndpointUserGuildSettings("@me", guildID), settings, EndpointUserGuildSettings("", guildID))
  361. if err != nil {
  362. return
  363. }
  364. err = unmarshal(body, &st)
  365. return
  366. }
  367. // UserChannelPermissions returns the permission of a user in a channel.
  368. // userID : The ID of the user to calculate permissions for.
  369. // channelID : The ID of the channel to calculate permission for.
  370. //
  371. // NOTE: This function is now deprecated and will be removed in the future.
  372. // Please see the same function inside state.go
  373. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int, err error) {
  374. // Try to just get permissions from state.
  375. apermissions, err = s.State.UserChannelPermissions(userID, channelID)
  376. if err == nil {
  377. return
  378. }
  379. // Otherwise try get as much data from state as possible, falling back to the network.
  380. channel, err := s.State.Channel(channelID)
  381. if err != nil || channel == nil {
  382. channel, err = s.Channel(channelID)
  383. if err != nil {
  384. return
  385. }
  386. }
  387. guild, err := s.State.Guild(channel.GuildID)
  388. if err != nil || guild == nil {
  389. guild, err = s.Guild(channel.GuildID)
  390. if err != nil {
  391. return
  392. }
  393. }
  394. if userID == guild.OwnerID {
  395. apermissions = PermissionAll
  396. return
  397. }
  398. member, err := s.State.Member(guild.ID, userID)
  399. if err != nil || member == nil {
  400. member, err = s.GuildMember(guild.ID, userID)
  401. if err != nil {
  402. return
  403. }
  404. }
  405. return memberPermissions(guild, channel, member), nil
  406. }
  407. // Calculates the permissions for a member.
  408. // https://support.discordapp.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured-
  409. func memberPermissions(guild *Guild, channel *Channel, member *Member) (apermissions int) {
  410. userID := member.User.ID
  411. if userID == guild.OwnerID {
  412. apermissions = PermissionAll
  413. return
  414. }
  415. for _, role := range guild.Roles {
  416. if role.ID == guild.ID {
  417. apermissions |= role.Permissions
  418. break
  419. }
  420. }
  421. for _, role := range guild.Roles {
  422. for _, roleID := range member.Roles {
  423. if role.ID == roleID {
  424. apermissions |= role.Permissions
  425. break
  426. }
  427. }
  428. }
  429. if apermissions&PermissionAdministrator == PermissionAdministrator {
  430. apermissions |= PermissionAll
  431. }
  432. // Apply @everyone overrides from the channel.
  433. for _, overwrite := range channel.PermissionOverwrites {
  434. if guild.ID == overwrite.ID {
  435. apermissions &= ^overwrite.Deny
  436. apermissions |= overwrite.Allow
  437. break
  438. }
  439. }
  440. denies := 0
  441. allows := 0
  442. // Member overwrites can override role overrides, so do two passes
  443. for _, overwrite := range channel.PermissionOverwrites {
  444. for _, roleID := range member.Roles {
  445. if overwrite.Type == "role" && roleID == overwrite.ID {
  446. denies |= overwrite.Deny
  447. allows |= overwrite.Allow
  448. break
  449. }
  450. }
  451. }
  452. apermissions &= ^denies
  453. apermissions |= allows
  454. for _, overwrite := range channel.PermissionOverwrites {
  455. if overwrite.Type == "member" && overwrite.ID == userID {
  456. apermissions &= ^overwrite.Deny
  457. apermissions |= overwrite.Allow
  458. break
  459. }
  460. }
  461. if apermissions&PermissionAdministrator == PermissionAdministrator {
  462. apermissions |= PermissionAllChannel
  463. }
  464. return apermissions
  465. }
  466. // ------------------------------------------------------------------------------------------------
  467. // Functions specific to Discord Guilds
  468. // ------------------------------------------------------------------------------------------------
  469. // Guild returns a Guild structure of a specific Guild.
  470. // guildID : The ID of a Guild
  471. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  472. body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  473. if err != nil {
  474. return
  475. }
  476. err = unmarshal(body, &st)
  477. return
  478. }
  479. // GuildCreate creates a new Guild
  480. // name : A name for the Guild (2-100 characters)
  481. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  482. data := struct {
  483. Name string `json:"name"`
  484. }{name}
  485. body, err := s.RequestWithBucketID("POST", EndpointGuildCreate, data, EndpointGuildCreate)
  486. if err != nil {
  487. return
  488. }
  489. err = unmarshal(body, &st)
  490. return
  491. }
  492. // GuildEdit edits a new Guild
  493. // guildID : The ID of a Guild
  494. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  495. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  496. // Bounds checking for VerificationLevel, interval: [0, 3]
  497. if g.VerificationLevel != nil {
  498. val := *g.VerificationLevel
  499. if val < 0 || val > 3 {
  500. err = ErrVerificationLevelBounds
  501. return
  502. }
  503. }
  504. //Bounds checking for regions
  505. if g.Region != "" {
  506. isValid := false
  507. regions, _ := s.VoiceRegions()
  508. for _, r := range regions {
  509. if g.Region == r.ID {
  510. isValid = true
  511. }
  512. }
  513. if !isValid {
  514. var valid []string
  515. for _, r := range regions {
  516. valid = append(valid, r.ID)
  517. }
  518. err = fmt.Errorf("Region not a valid region (%q)", valid)
  519. return
  520. }
  521. }
  522. body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID))
  523. if err != nil {
  524. return
  525. }
  526. err = unmarshal(body, &st)
  527. return
  528. }
  529. // GuildDelete deletes a Guild.
  530. // guildID : The ID of a Guild
  531. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  532. body, err := s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  533. if err != nil {
  534. return
  535. }
  536. err = unmarshal(body, &st)
  537. return
  538. }
  539. // GuildLeave leaves a Guild.
  540. // guildID : The ID of a Guild
  541. func (s *Session) GuildLeave(guildID string) (err error) {
  542. _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID))
  543. return
  544. }
  545. // GuildBans returns an array of User structures for all bans of a
  546. // given guild.
  547. // guildID : The ID of a Guild.
  548. func (s *Session) GuildBans(guildID string) (st []*GuildBan, err error) {
  549. body, err := s.RequestWithBucketID("GET", EndpointGuildBans(guildID), nil, EndpointGuildBans(guildID))
  550. if err != nil {
  551. return
  552. }
  553. err = unmarshal(body, &st)
  554. return
  555. }
  556. // GuildBanCreate bans the given user from the given guild.
  557. // guildID : The ID of a Guild.
  558. // userID : The ID of a User
  559. // days : The number of days of previous comments to delete.
  560. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  561. return s.GuildBanCreateWithReason(guildID, userID, "", days)
  562. }
  563. // GuildBanCreateWithReason bans the given user from the given guild also providing a reaso.
  564. // guildID : The ID of a Guild.
  565. // userID : The ID of a User
  566. // reason : The reason for this ban
  567. // days : The number of days of previous comments to delete.
  568. func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int) (err error) {
  569. uri := EndpointGuildBan(guildID, userID)
  570. queryParams := url.Values{}
  571. if days > 0 {
  572. queryParams.Set("delete-message-days", strconv.Itoa(days))
  573. }
  574. if reason != "" {
  575. queryParams.Set("reason", reason)
  576. }
  577. if len(queryParams) > 0 {
  578. uri += "?" + queryParams.Encode()
  579. }
  580. _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""))
  581. return
  582. }
  583. // GuildBanDelete removes the given user from the guild bans
  584. // guildID : The ID of a Guild.
  585. // userID : The ID of a User
  586. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  587. _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""))
  588. return
  589. }
  590. // GuildMembers returns a list of members for a guild.
  591. // guildID : The ID of a Guild.
  592. // after : The id of the member to return members after
  593. // limit : max number of members to return (max 1000)
  594. func (s *Session) GuildMembers(guildID string, after string, limit int) (st []*Member, err error) {
  595. uri := EndpointGuildMembers(guildID)
  596. v := url.Values{}
  597. if after != "" {
  598. v.Set("after", after)
  599. }
  600. if limit > 0 {
  601. v.Set("limit", strconv.Itoa(limit))
  602. }
  603. if len(v) > 0 {
  604. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  605. }
  606. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID))
  607. if err != nil {
  608. return
  609. }
  610. err = unmarshal(body, &st)
  611. return
  612. }
  613. // GuildMember returns a member of a guild.
  614. // guildID : The ID of a Guild.
  615. // userID : The ID of a User
  616. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  617. body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""))
  618. if err != nil {
  619. return
  620. }
  621. err = unmarshal(body, &st)
  622. return
  623. }
  624. // GuildMemberAdd force joins a user to the guild.
  625. // accessToken : Valid access_token for the user.
  626. // guildID : The ID of a Guild.
  627. // userID : The ID of a User.
  628. // nick : Value to set users nickname to
  629. // roles : A list of role ID's to set on the member.
  630. // mute : If the user is muted.
  631. // deaf : If the user is deafened.
  632. func (s *Session) GuildMemberAdd(accessToken, guildID, userID, nick string, roles []string, mute, deaf bool) (err error) {
  633. data := struct {
  634. AccessToken string `json:"access_token"`
  635. Nick string `json:"nick,omitempty"`
  636. Roles []string `json:"roles,omitempty"`
  637. Mute bool `json:"mute,omitempty"`
  638. Deaf bool `json:"deaf,omitempty"`
  639. }{accessToken, nick, roles, mute, deaf}
  640. _, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  641. if err != nil {
  642. return err
  643. }
  644. return err
  645. }
  646. // GuildMemberDelete removes the given user from the given guild.
  647. // guildID : The ID of a Guild.
  648. // userID : The ID of a User
  649. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  650. return s.GuildMemberDeleteWithReason(guildID, userID, "")
  651. }
  652. // GuildMemberDeleteWithReason removes the given user from the given guild.
  653. // guildID : The ID of a Guild.
  654. // userID : The ID of a User
  655. // reason : The reason for the kick
  656. func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string) (err error) {
  657. uri := EndpointGuildMember(guildID, userID)
  658. if reason != "" {
  659. uri += "?reason=" + url.QueryEscape(reason)
  660. }
  661. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""))
  662. return
  663. }
  664. // GuildMemberEdit edits the roles of a member.
  665. // guildID : The ID of a Guild.
  666. // userID : The ID of a User.
  667. // roles : A list of role ID's to set on the member.
  668. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  669. data := struct {
  670. Roles []string `json:"roles"`
  671. }{roles}
  672. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  673. if err != nil {
  674. return
  675. }
  676. return
  677. }
  678. // GuildMemberMove moves a guild member from one voice channel to another/none
  679. // guildID : The ID of a Guild.
  680. // userID : The ID of a User.
  681. // channelID : The ID of a channel to move user to, or null?
  682. // NOTE : I am not entirely set on the name of this function and it may change
  683. // prior to the final 1.0.0 release of Discordgo
  684. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  685. data := struct {
  686. ChannelID string `json:"channel_id"`
  687. }{channelID}
  688. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  689. if err != nil {
  690. return
  691. }
  692. return
  693. }
  694. // GuildMemberNickname updates the nickname of a guild member
  695. // guildID : The ID of a guild
  696. // userID : The ID of a user
  697. // userID : The ID of a user or "@me" which is a shortcut of the current user ID
  698. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  699. data := struct {
  700. Nick string `json:"nick"`
  701. }{nickname}
  702. if userID == "@me" {
  703. userID += "/nick"
  704. }
  705. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  706. return
  707. }
  708. // GuildMemberRoleAdd adds the specified role to a given member
  709. // guildID : The ID of a Guild.
  710. // userID : The ID of a User.
  711. // roleID : The ID of a Role to be assigned to the user.
  712. func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string) (err error) {
  713. _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  714. return
  715. }
  716. // GuildMemberRoleRemove removes the specified role to a given member
  717. // guildID : The ID of a Guild.
  718. // userID : The ID of a User.
  719. // roleID : The ID of a Role to be removed from the user.
  720. func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string) (err error) {
  721. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  722. return
  723. }
  724. // GuildChannels returns an array of Channel structures for all channels of a
  725. // given guild.
  726. // guildID : The ID of a Guild.
  727. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  728. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0)
  729. if err != nil {
  730. return
  731. }
  732. err = unmarshal(body, &st)
  733. return
  734. }
  735. // GuildChannelCreate creates a new channel in the given guild
  736. // guildID : The ID of a Guild.
  737. // name : Name of the channel (2-100 chars length)
  738. // ctype : Type of the channel
  739. func (s *Session) GuildChannelCreate(guildID, name string, ctype ChannelType) (st *Channel, err error) {
  740. data := struct {
  741. Name string `json:"name"`
  742. Type ChannelType `json:"type"`
  743. }{name, ctype}
  744. body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  745. if err != nil {
  746. return
  747. }
  748. err = unmarshal(body, &st)
  749. return
  750. }
  751. // GuildChannelsReorder updates the order of channels in a guild
  752. // guildID : The ID of a Guild.
  753. // channels : Updated channels.
  754. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  755. _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), channels, EndpointGuildChannels(guildID))
  756. return
  757. }
  758. // GuildInvites returns an array of Invite structures for the given guild
  759. // guildID : The ID of a Guild.
  760. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  761. body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID))
  762. if err != nil {
  763. return
  764. }
  765. err = unmarshal(body, &st)
  766. return
  767. }
  768. // GuildRoles returns all roles for a given guild.
  769. // guildID : The ID of a Guild.
  770. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  771. body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  772. if err != nil {
  773. return
  774. }
  775. err = unmarshal(body, &st)
  776. return // TODO return pointer
  777. }
  778. // GuildRoleCreate returns a new Guild Role.
  779. // guildID: The ID of a Guild.
  780. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  781. body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  782. if err != nil {
  783. return
  784. }
  785. err = unmarshal(body, &st)
  786. return
  787. }
  788. // GuildRoleEdit updates an existing Guild Role with new values
  789. // guildID : The ID of a Guild.
  790. // roleID : The ID of a Role.
  791. // name : The name of the Role.
  792. // color : The color of the role (decimal, not hex).
  793. // hoist : Whether to display the role's users separately.
  794. // perm : The permissions for the role.
  795. // mention : Whether this role is mentionable
  796. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int, mention bool) (st *Role, err error) {
  797. // Prevent sending a color int that is too big.
  798. if color > 0xFFFFFF {
  799. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  800. return nil, err
  801. }
  802. data := struct {
  803. Name string `json:"name"` // The role's name (overwrites existing)
  804. Color int `json:"color"` // The color the role should have (as a decimal, not hex)
  805. Hoist bool `json:"hoist"` // Whether to display the role's users separately
  806. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  807. Mentionable bool `json:"mentionable"` // Whether this role is mentionable
  808. }{name, color, hoist, perm, mention}
  809. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""))
  810. if err != nil {
  811. return
  812. }
  813. err = unmarshal(body, &st)
  814. return
  815. }
  816. // GuildRoleReorder reoders guild roles
  817. // guildID : The ID of a Guild.
  818. // roles : A list of ordered roles.
  819. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  820. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID))
  821. if err != nil {
  822. return
  823. }
  824. err = unmarshal(body, &st)
  825. return
  826. }
  827. // GuildRoleDelete deletes an existing role.
  828. // guildID : The ID of a Guild.
  829. // roleID : The ID of a Role.
  830. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  831. _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""))
  832. return
  833. }
  834. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  835. // Requires 'KICK_MEMBER' permission.
  836. // guildID : The ID of a Guild.
  837. // days : The number of days to count prune for (1 or more).
  838. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  839. count = 0
  840. if days <= 0 {
  841. err = ErrPruneDaysBounds
  842. return
  843. }
  844. p := struct {
  845. Pruned uint32 `json:"pruned"`
  846. }{}
  847. uri := EndpointGuildPrune(guildID) + fmt.Sprintf("?days=%d", days)
  848. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  849. if err != nil {
  850. return
  851. }
  852. err = unmarshal(body, &p)
  853. if err != nil {
  854. return
  855. }
  856. count = p.Pruned
  857. return
  858. }
  859. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  860. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  861. // guildID : The ID of a Guild.
  862. // days : The number of days to count prune for (1 or more).
  863. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  864. count = 0
  865. if days <= 0 {
  866. err = ErrPruneDaysBounds
  867. return
  868. }
  869. data := struct {
  870. days uint32
  871. }{days}
  872. p := struct {
  873. Pruned uint32 `json:"pruned"`
  874. }{}
  875. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  876. if err != nil {
  877. return
  878. }
  879. err = unmarshal(body, &p)
  880. if err != nil {
  881. return
  882. }
  883. count = p.Pruned
  884. return
  885. }
  886. // GuildIntegrations returns an array of Integrations for a guild.
  887. // guildID : The ID of a Guild.
  888. func (s *Session) GuildIntegrations(guildID string) (st []*Integration, err error) {
  889. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  890. if err != nil {
  891. return
  892. }
  893. err = unmarshal(body, &st)
  894. return
  895. }
  896. // GuildIntegrationCreate creates a Guild Integration.
  897. // guildID : The ID of a Guild.
  898. // integrationType : The Integration type.
  899. // integrationID : The ID of an integration.
  900. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  901. data := struct {
  902. Type string `json:"type"`
  903. ID string `json:"id"`
  904. }{integrationType, integrationID}
  905. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  906. return
  907. }
  908. // GuildIntegrationEdit edits a Guild Integration.
  909. // guildID : The ID of a Guild.
  910. // integrationType : The Integration type.
  911. // integrationID : The ID of an integration.
  912. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  913. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  914. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  915. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  916. data := struct {
  917. ExpireBehavior int `json:"expire_behavior"`
  918. ExpireGracePeriod int `json:"expire_grace_period"`
  919. EnableEmoticons bool `json:"enable_emoticons"`
  920. }{expireBehavior, expireGracePeriod, enableEmoticons}
  921. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  922. return
  923. }
  924. // GuildIntegrationDelete removes the given integration from the Guild.
  925. // guildID : The ID of a Guild.
  926. // integrationID : The ID of an integration.
  927. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  928. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  929. return
  930. }
  931. // GuildIntegrationSync syncs an integration.
  932. // guildID : The ID of a Guild.
  933. // integrationID : The ID of an integration.
  934. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  935. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  936. return
  937. }
  938. // GuildIcon returns an image.Image of a guild icon.
  939. // guildID : The ID of a Guild.
  940. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  941. g, err := s.Guild(guildID)
  942. if err != nil {
  943. return
  944. }
  945. if g.Icon == "" {
  946. err = ErrGuildNoIcon
  947. return
  948. }
  949. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  950. if err != nil {
  951. return
  952. }
  953. img, _, err = image.Decode(bytes.NewReader(body))
  954. return
  955. }
  956. // GuildSplash returns an image.Image of a guild splash image.
  957. // guildID : The ID of a Guild.
  958. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  959. g, err := s.Guild(guildID)
  960. if err != nil {
  961. return
  962. }
  963. if g.Splash == "" {
  964. err = ErrGuildNoSplash
  965. return
  966. }
  967. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  968. if err != nil {
  969. return
  970. }
  971. img, _, err = image.Decode(bytes.NewReader(body))
  972. return
  973. }
  974. // GuildEmbed returns the embed for a Guild.
  975. // guildID : The ID of a Guild.
  976. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  977. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  978. if err != nil {
  979. return
  980. }
  981. err = unmarshal(body, &st)
  982. return
  983. }
  984. // GuildEmbedEdit returns the embed for a Guild.
  985. // guildID : The ID of a Guild.
  986. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  987. data := GuildEmbed{enabled, channelID}
  988. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  989. return
  990. }
  991. // GuildAuditLog returns the audit log for a Guild.
  992. // guildID : The ID of a Guild.
  993. // userID : If provided the log will be filtered for the given ID.
  994. // beforeID : If provided all log entries returned will be before the given ID.
  995. // actionType : If provided the log will be filtered for the given Action Type.
  996. // limit : The number messages that can be returned. (default 50, min 1, max 100)
  997. func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int) (st *GuildAuditLog, err error) {
  998. uri := EndpointGuildAuditLogs(guildID)
  999. v := url.Values{}
  1000. if userID != "" {
  1001. v.Set("user_id", userID)
  1002. }
  1003. if beforeID != "" {
  1004. v.Set("before", beforeID)
  1005. }
  1006. if actionType > 0 {
  1007. v.Set("action_type", strconv.Itoa(actionType))
  1008. }
  1009. if limit > 0 {
  1010. v.Set("limit", strconv.Itoa(limit))
  1011. }
  1012. if len(v) > 0 {
  1013. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1014. }
  1015. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID))
  1016. if err != nil {
  1017. return
  1018. }
  1019. err = unmarshal(body, &st)
  1020. return
  1021. }
  1022. // ------------------------------------------------------------------------------------------------
  1023. // Functions specific to Discord Channels
  1024. // ------------------------------------------------------------------------------------------------
  1025. // Channel returns a Channel structure of a specific Channel.
  1026. // channelID : The ID of the Channel you want returned.
  1027. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  1028. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1029. if err != nil {
  1030. return
  1031. }
  1032. err = unmarshal(body, &st)
  1033. return
  1034. }
  1035. // ChannelEdit edits the given channel
  1036. // channelID : The ID of a Channel
  1037. // name : The new name to assign the channel.
  1038. func (s *Session) ChannelEdit(channelID, name string) (*Channel, error) {
  1039. return s.ChannelEditComplex(channelID, &ChannelEdit{
  1040. Name: name,
  1041. })
  1042. }
  1043. // ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct
  1044. // channelID : The ID of a Channel
  1045. // data : The channel struct to send
  1046. func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit) (st *Channel, err error) {
  1047. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  1048. if err != nil {
  1049. return
  1050. }
  1051. err = unmarshal(body, &st)
  1052. return
  1053. }
  1054. // ChannelDelete deletes the given channel
  1055. // channelID : The ID of a Channel
  1056. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  1057. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1058. if err != nil {
  1059. return
  1060. }
  1061. err = unmarshal(body, &st)
  1062. return
  1063. }
  1064. // ChannelTyping broadcasts to all members that authenticated user is typing in
  1065. // the given channel.
  1066. // channelID : The ID of a Channel
  1067. func (s *Session) ChannelTyping(channelID string) (err error) {
  1068. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  1069. return
  1070. }
  1071. // ChannelMessages returns an array of Message structures for messages within
  1072. // a given channel.
  1073. // channelID : The ID of a Channel.
  1074. // limit : The number messages that can be returned. (max 100)
  1075. // beforeID : If provided all messages returned will be before given ID.
  1076. // afterID : If provided all messages returned will be after given ID.
  1077. // aroundID : If provided all messages returned will be around given ID.
  1078. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  1079. uri := EndpointChannelMessages(channelID)
  1080. v := url.Values{}
  1081. if limit > 0 {
  1082. v.Set("limit", strconv.Itoa(limit))
  1083. }
  1084. if afterID != "" {
  1085. v.Set("after", afterID)
  1086. }
  1087. if beforeID != "" {
  1088. v.Set("before", beforeID)
  1089. }
  1090. if aroundID != "" {
  1091. v.Set("around", aroundID)
  1092. }
  1093. if len(v) > 0 {
  1094. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1095. }
  1096. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  1097. if err != nil {
  1098. return
  1099. }
  1100. err = unmarshal(body, &st)
  1101. return
  1102. }
  1103. // ChannelMessage gets a single message by ID from a given channel.
  1104. // channeld : The ID of a Channel
  1105. // messageID : the ID of a Message
  1106. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  1107. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1108. if err != nil {
  1109. return
  1110. }
  1111. err = unmarshal(response, &st)
  1112. return
  1113. }
  1114. // ChannelMessageAck acknowledges and marks the given message as read
  1115. // channeld : The ID of a Channel
  1116. // messageID : the ID of a Message
  1117. // lastToken : token returned by last ack
  1118. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  1119. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  1120. if err != nil {
  1121. return
  1122. }
  1123. err = unmarshal(body, &st)
  1124. return
  1125. }
  1126. // ChannelMessageSend sends a message to the given channel.
  1127. // channelID : The ID of a Channel.
  1128. // content : The message to send.
  1129. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1130. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1131. Content: content,
  1132. })
  1133. }
  1134. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  1135. // ChannelMessageSendComplex sends a message to the given channel.
  1136. // channelID : The ID of a Channel.
  1137. // data : The message struct to send.
  1138. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1139. if data.Embed != nil && data.Embed.Type == "" {
  1140. data.Embed.Type = "rich"
  1141. }
  1142. endpoint := EndpointChannelMessages(channelID)
  1143. // TODO: Remove this when compatibility is not required.
  1144. files := data.Files
  1145. if data.File != nil {
  1146. if files == nil {
  1147. files = []*File{data.File}
  1148. } else {
  1149. err = fmt.Errorf("cannot specify both File and Files")
  1150. return
  1151. }
  1152. }
  1153. var response []byte
  1154. if len(files) > 0 {
  1155. body := &bytes.Buffer{}
  1156. bodywriter := multipart.NewWriter(body)
  1157. var payload []byte
  1158. payload, err = json.Marshal(data)
  1159. if err != nil {
  1160. return
  1161. }
  1162. var p io.Writer
  1163. h := make(textproto.MIMEHeader)
  1164. h.Set("Content-Disposition", `form-data; name="payload_json"`)
  1165. h.Set("Content-Type", "application/json")
  1166. p, err = bodywriter.CreatePart(h)
  1167. if err != nil {
  1168. return
  1169. }
  1170. if _, err = p.Write(payload); err != nil {
  1171. return
  1172. }
  1173. for i, file := range files {
  1174. h := make(textproto.MIMEHeader)
  1175. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file%d"; filename="%s"`, i, quoteEscaper.Replace(file.Name)))
  1176. contentType := file.ContentType
  1177. if contentType == "" {
  1178. contentType = "application/octet-stream"
  1179. }
  1180. h.Set("Content-Type", contentType)
  1181. p, err = bodywriter.CreatePart(h)
  1182. if err != nil {
  1183. return
  1184. }
  1185. if _, err = io.Copy(p, file.Reader); err != nil {
  1186. return
  1187. }
  1188. }
  1189. err = bodywriter.Close()
  1190. if err != nil {
  1191. return
  1192. }
  1193. response, err = s.request("POST", endpoint, bodywriter.FormDataContentType(), body.Bytes(), endpoint, 0)
  1194. } else {
  1195. response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1196. }
  1197. if err != nil {
  1198. return
  1199. }
  1200. err = unmarshal(response, &st)
  1201. return
  1202. }
  1203. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1204. // channelID : The ID of a Channel.
  1205. // content : The message to send.
  1206. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1207. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1208. Content: content,
  1209. Tts: true,
  1210. })
  1211. }
  1212. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1213. // channelID : The ID of a Channel.
  1214. // embed : The embed data to send.
  1215. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1216. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1217. Embed: embed,
  1218. })
  1219. }
  1220. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1221. // the given content.
  1222. // channelID : The ID of a Channel
  1223. // messageID : The ID of a Message
  1224. // content : The contents of the message
  1225. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1226. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content))
  1227. }
  1228. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1229. // the given MessageEdit struct
  1230. func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) {
  1231. if m.Embed != nil && m.Embed.Type == "" {
  1232. m.Embed.Type = "rich"
  1233. }
  1234. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, ""))
  1235. if err != nil {
  1236. return
  1237. }
  1238. err = unmarshal(response, &st)
  1239. return
  1240. }
  1241. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1242. // channelID : The ID of a Channel
  1243. // messageID : The ID of a Message
  1244. // embed : The embed data to send
  1245. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1246. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbed(embed))
  1247. }
  1248. // ChannelMessageDelete deletes a message from the Channel.
  1249. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1250. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1251. return
  1252. }
  1253. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1254. // If only one messageID is in the slice call channelMessageDelete function.
  1255. // If the slice is empty do nothing.
  1256. // channelID : The ID of the channel for the messages to delete.
  1257. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1258. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1259. if len(messages) == 0 {
  1260. return
  1261. }
  1262. if len(messages) == 1 {
  1263. err = s.ChannelMessageDelete(channelID, messages[0])
  1264. return
  1265. }
  1266. if len(messages) > 100 {
  1267. messages = messages[:100]
  1268. }
  1269. data := struct {
  1270. Messages []string `json:"messages"`
  1271. }{messages}
  1272. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1273. return
  1274. }
  1275. // ChannelMessagePin pins a message within a given channel.
  1276. // channelID: The ID of a channel.
  1277. // messageID: The ID of a message.
  1278. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1279. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1280. return
  1281. }
  1282. // ChannelMessageUnpin unpins a message within a given channel.
  1283. // channelID: The ID of a channel.
  1284. // messageID: The ID of a message.
  1285. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1286. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1287. return
  1288. }
  1289. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1290. // within a given channel
  1291. // channelID : The ID of a Channel.
  1292. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1293. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1294. if err != nil {
  1295. return
  1296. }
  1297. err = unmarshal(body, &st)
  1298. return
  1299. }
  1300. // ChannelFileSend sends a file to the given channel.
  1301. // channelID : The ID of a Channel.
  1302. // name: The name of the file.
  1303. // io.Reader : A reader for the file contents.
  1304. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (*Message, error) {
  1305. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}})
  1306. }
  1307. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1308. // DEPRECATED. Use ChannelMessageSendComplex instead.
  1309. // channelID : The ID of a Channel.
  1310. // content: Optional Message content.
  1311. // name: The name of the file.
  1312. // io.Reader : A reader for the file contents.
  1313. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (*Message, error) {
  1314. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content})
  1315. }
  1316. // ChannelInvites returns an array of Invite structures for the given channel
  1317. // channelID : The ID of a Channel
  1318. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1319. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1320. if err != nil {
  1321. return
  1322. }
  1323. err = unmarshal(body, &st)
  1324. return
  1325. }
  1326. // ChannelInviteCreate creates a new invite for the given channel.
  1327. // channelID : The ID of a Channel
  1328. // i : An Invite struct with the values MaxAge, MaxUses and Temporary defined.
  1329. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1330. data := struct {
  1331. MaxAge int `json:"max_age"`
  1332. MaxUses int `json:"max_uses"`
  1333. Temporary bool `json:"temporary"`
  1334. }{i.MaxAge, i.MaxUses, i.Temporary}
  1335. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1336. if err != nil {
  1337. return
  1338. }
  1339. err = unmarshal(body, &st)
  1340. return
  1341. }
  1342. // ChannelPermissionSet creates a Permission Override for the given channel.
  1343. // NOTE: This func name may changed. Using Set instead of Create because
  1344. // you can both create a new override or update an override with this function.
  1345. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1346. data := struct {
  1347. ID string `json:"id"`
  1348. Type string `json:"type"`
  1349. Allow int `json:"allow"`
  1350. Deny int `json:"deny"`
  1351. }{targetID, targetType, allow, deny}
  1352. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1353. return
  1354. }
  1355. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1356. // NOTE: Name of this func may change.
  1357. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1358. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1359. return
  1360. }
  1361. // ------------------------------------------------------------------------------------------------
  1362. // Functions specific to Discord Invites
  1363. // ------------------------------------------------------------------------------------------------
  1364. // Invite returns an Invite structure of the given invite
  1365. // inviteID : The invite code
  1366. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1367. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1368. if err != nil {
  1369. return
  1370. }
  1371. err = unmarshal(body, &st)
  1372. return
  1373. }
  1374. // InviteDelete deletes an existing invite
  1375. // inviteID : the code of an invite
  1376. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1377. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1378. if err != nil {
  1379. return
  1380. }
  1381. err = unmarshal(body, &st)
  1382. return
  1383. }
  1384. // InviteAccept accepts an Invite to a Guild or Channel
  1385. // inviteID : The invite code
  1386. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1387. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1388. if err != nil {
  1389. return
  1390. }
  1391. err = unmarshal(body, &st)
  1392. return
  1393. }
  1394. // ------------------------------------------------------------------------------------------------
  1395. // Functions specific to Discord Voice
  1396. // ------------------------------------------------------------------------------------------------
  1397. // VoiceRegions returns the voice server regions
  1398. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1399. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1400. if err != nil {
  1401. return
  1402. }
  1403. err = unmarshal(body, &st)
  1404. return
  1405. }
  1406. // VoiceICE returns the voice server ICE information
  1407. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1408. body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce)
  1409. if err != nil {
  1410. return
  1411. }
  1412. err = unmarshal(body, &st)
  1413. return
  1414. }
  1415. // ------------------------------------------------------------------------------------------------
  1416. // Functions specific to Discord Websockets
  1417. // ------------------------------------------------------------------------------------------------
  1418. // Gateway returns the websocket Gateway address
  1419. func (s *Session) Gateway() (gateway string, err error) {
  1420. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1421. if err != nil {
  1422. return
  1423. }
  1424. temp := struct {
  1425. URL string `json:"url"`
  1426. }{}
  1427. err = unmarshal(response, &temp)
  1428. if err != nil {
  1429. return
  1430. }
  1431. gateway = temp.URL
  1432. // Ensure the gateway always has a trailing slash.
  1433. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1434. if !strings.HasSuffix(gateway, "/") {
  1435. gateway += "/"
  1436. }
  1437. return
  1438. }
  1439. // GatewayBot returns the websocket Gateway address and the recommended number of shards
  1440. func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) {
  1441. response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot)
  1442. if err != nil {
  1443. return
  1444. }
  1445. err = unmarshal(response, &st)
  1446. if err != nil {
  1447. return
  1448. }
  1449. // Ensure the gateway always has a trailing slash.
  1450. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1451. if !strings.HasSuffix(st.URL, "/") {
  1452. st.URL += "/"
  1453. }
  1454. return
  1455. }
  1456. // Functions specific to Webhooks
  1457. // WebhookCreate returns a new Webhook.
  1458. // channelID: The ID of a Channel.
  1459. // name : The name of the webhook.
  1460. // avatar : The avatar of the webhook.
  1461. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1462. data := struct {
  1463. Name string `json:"name"`
  1464. Avatar string `json:"avatar,omitempty"`
  1465. }{name, avatar}
  1466. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1467. if err != nil {
  1468. return
  1469. }
  1470. err = unmarshal(body, &st)
  1471. return
  1472. }
  1473. // ChannelWebhooks returns all webhooks for a given channel.
  1474. // channelID: The ID of a channel.
  1475. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1476. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1477. if err != nil {
  1478. return
  1479. }
  1480. err = unmarshal(body, &st)
  1481. return
  1482. }
  1483. // GuildWebhooks returns all webhooks for a given guild.
  1484. // guildID: The ID of a Guild.
  1485. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1486. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1487. if err != nil {
  1488. return
  1489. }
  1490. err = unmarshal(body, &st)
  1491. return
  1492. }
  1493. // Webhook returns a webhook for a given ID
  1494. // webhookID: The ID of a webhook.
  1495. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1496. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1497. if err != nil {
  1498. return
  1499. }
  1500. err = unmarshal(body, &st)
  1501. return
  1502. }
  1503. // WebhookWithToken returns a webhook for a given ID
  1504. // webhookID: The ID of a webhook.
  1505. // token : The auth token for the webhook.
  1506. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1507. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1508. if err != nil {
  1509. return
  1510. }
  1511. err = unmarshal(body, &st)
  1512. return
  1513. }
  1514. // WebhookEdit updates an existing Webhook.
  1515. // webhookID: The ID of a webhook.
  1516. // name : The name of the webhook.
  1517. // avatar : The avatar of the webhook.
  1518. func (s *Session) WebhookEdit(webhookID, name, avatar, channelID string) (st *Role, err error) {
  1519. data := struct {
  1520. Name string `json:"name,omitempty"`
  1521. Avatar string `json:"avatar,omitempty"`
  1522. ChannelID string `json:"channel_id,omitempty"`
  1523. }{name, avatar, channelID}
  1524. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1525. if err != nil {
  1526. return
  1527. }
  1528. err = unmarshal(body, &st)
  1529. return
  1530. }
  1531. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1532. // webhookID: The ID of a webhook.
  1533. // token : The auth token for the webhook.
  1534. // name : The name of the webhook.
  1535. // avatar : The avatar of the webhook.
  1536. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1537. data := struct {
  1538. Name string `json:"name,omitempty"`
  1539. Avatar string `json:"avatar,omitempty"`
  1540. }{name, avatar}
  1541. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1542. if err != nil {
  1543. return
  1544. }
  1545. err = unmarshal(body, &st)
  1546. return
  1547. }
  1548. // WebhookDelete deletes a webhook for a given ID
  1549. // webhookID: The ID of a webhook.
  1550. func (s *Session) WebhookDelete(webhookID string) (err error) {
  1551. _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1552. return
  1553. }
  1554. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1555. // webhookID: The ID of a webhook.
  1556. // token : The auth token for the webhook.
  1557. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1558. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1559. if err != nil {
  1560. return
  1561. }
  1562. err = unmarshal(body, &st)
  1563. return
  1564. }
  1565. // WebhookExecute executes a webhook.
  1566. // webhookID: The ID of a webhook.
  1567. // token : The auth token for the webhook
  1568. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (err error) {
  1569. uri := EndpointWebhookToken(webhookID, token)
  1570. if wait {
  1571. uri += "?wait=true"
  1572. }
  1573. _, err = s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))
  1574. return
  1575. }
  1576. // MessageReactionAdd creates an emoji reaction to a message.
  1577. // channelID : The channel ID.
  1578. // messageID : The message ID.
  1579. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1580. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1581. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1582. return err
  1583. }
  1584. // MessageReactionRemove deletes an emoji reaction to a message.
  1585. // channelID : The channel ID.
  1586. // messageID : The message ID.
  1587. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1588. // userID : @me or ID of the user to delete the reaction for.
  1589. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1590. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1591. return err
  1592. }
  1593. // MessageReactionsRemoveAll deletes all reactions from a message
  1594. // channelID : The channel ID
  1595. // messageID : The message ID.
  1596. func (s *Session) MessageReactionsRemoveAll(channelID, messageID string) error {
  1597. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID))
  1598. return err
  1599. }
  1600. // MessageReactions gets all the users reactions for a specific emoji.
  1601. // channelID : The channel ID.
  1602. // messageID : The message ID.
  1603. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1604. // limit : max number of users to return (max 100)
  1605. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int) (st []*User, err error) {
  1606. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1607. v := url.Values{}
  1608. if limit > 0 {
  1609. v.Set("limit", strconv.Itoa(limit))
  1610. }
  1611. if len(v) > 0 {
  1612. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1613. }
  1614. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1615. if err != nil {
  1616. return
  1617. }
  1618. err = unmarshal(body, &st)
  1619. return
  1620. }
  1621. // ------------------------------------------------------------------------------------------------
  1622. // Functions specific to user notes
  1623. // ------------------------------------------------------------------------------------------------
  1624. // UserNoteSet sets the note for a specific user.
  1625. func (s *Session) UserNoteSet(userID string, message string) (err error) {
  1626. data := struct {
  1627. Note string `json:"note"`
  1628. }{message}
  1629. _, err = s.RequestWithBucketID("PUT", EndpointUserNotes(userID), data, EndpointUserNotes(""))
  1630. return
  1631. }
  1632. // ------------------------------------------------------------------------------------------------
  1633. // Functions specific to Discord Relationships (Friends list)
  1634. // ------------------------------------------------------------------------------------------------
  1635. // RelationshipsGet returns an array of all the relationships of the user.
  1636. func (s *Session) RelationshipsGet() (r []*Relationship, err error) {
  1637. body, err := s.RequestWithBucketID("GET", EndpointRelationships(), nil, EndpointRelationships())
  1638. if err != nil {
  1639. return
  1640. }
  1641. err = unmarshal(body, &r)
  1642. return
  1643. }
  1644. // relationshipCreate creates a new relationship. (I.e. send or accept a friend request, block a user.)
  1645. // relationshipType : 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  1646. func (s *Session) relationshipCreate(userID string, relationshipType int) (err error) {
  1647. data := struct {
  1648. Type int `json:"type"`
  1649. }{relationshipType}
  1650. _, err = s.RequestWithBucketID("PUT", EndpointRelationship(userID), data, EndpointRelationships())
  1651. return
  1652. }
  1653. // RelationshipFriendRequestSend sends a friend request to a user.
  1654. // userID: ID of the user.
  1655. func (s *Session) RelationshipFriendRequestSend(userID string) (err error) {
  1656. err = s.relationshipCreate(userID, 4)
  1657. return
  1658. }
  1659. // RelationshipFriendRequestAccept accepts a friend request from a user.
  1660. // userID: ID of the user.
  1661. func (s *Session) RelationshipFriendRequestAccept(userID string) (err error) {
  1662. err = s.relationshipCreate(userID, 1)
  1663. return
  1664. }
  1665. // RelationshipUserBlock blocks a user.
  1666. // userID: ID of the user.
  1667. func (s *Session) RelationshipUserBlock(userID string) (err error) {
  1668. err = s.relationshipCreate(userID, 2)
  1669. return
  1670. }
  1671. // RelationshipDelete removes the relationship with a user.
  1672. // userID: ID of the user.
  1673. func (s *Session) RelationshipDelete(userID string) (err error) {
  1674. _, err = s.RequestWithBucketID("DELETE", EndpointRelationship(userID), nil, EndpointRelationships())
  1675. return
  1676. }
  1677. // RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with.
  1678. // userID: ID of the user.
  1679. func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) {
  1680. body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID))
  1681. if err != nil {
  1682. return
  1683. }
  1684. err = unmarshal(body, &mf)
  1685. return
  1686. }