restapi.go 80 KB

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