restapi.go 65 KB

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