restapi.go 79 KB

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