restapi.go 67 KB

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