restapi.go 61 KB

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