restapi.go 65 KB

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