restapi.go 59 KB

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