restapi.go 78 KB

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