restapi.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085
  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. // GuildAuditLog returns the audit log for a Guild.
  965. // guildID : The ID of a Guild.
  966. // userID : If provided the log will be filtered for the given ID.
  967. // beforeID : If provided all log entries returned will be before the given ID.
  968. // actionType : If provided the log will be filtered for the given Action Type.
  969. // limit : The number messages that can be returned. (default 50, min 1, max 100)
  970. func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int) (st *GuildAuditLog, err error) {
  971. uri := EndpointGuildAuditLogs(guildID)
  972. v := url.Values{}
  973. if userID != "" {
  974. v.Set("user_id", userID)
  975. }
  976. if beforeID != "" {
  977. v.Set("before", beforeID)
  978. }
  979. if actionType > 0 {
  980. v.Set("action_type", strconv.Itoa(actionType))
  981. }
  982. if limit > 0 {
  983. v.Set("limit", strconv.Itoa(limit))
  984. }
  985. if len(v) > 0 {
  986. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  987. }
  988. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID))
  989. if err != nil {
  990. return
  991. }
  992. err = unmarshal(body, &st)
  993. return
  994. }
  995. // ------------------------------------------------------------------------------------------------
  996. // Functions specific to Discord Channels
  997. // ------------------------------------------------------------------------------------------------
  998. // Channel returns a Channel structure of a specific Channel.
  999. // channelID : The ID of the Channel you want returned.
  1000. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  1001. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1002. if err != nil {
  1003. return
  1004. }
  1005. err = unmarshal(body, &st)
  1006. return
  1007. }
  1008. // ChannelEdit edits the given channel
  1009. // channelID : The ID of a Channel
  1010. // name : The new name to assign the channel.
  1011. func (s *Session) ChannelEdit(channelID, name string) (*Channel, error) {
  1012. return s.ChannelEditComplex(channelID, &ChannelEdit{
  1013. Name: name,
  1014. })
  1015. }
  1016. // ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct
  1017. // channelID : The ID of a Channel
  1018. // data : The channel struct to send
  1019. func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit) (st *Channel, err error) {
  1020. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  1021. if err != nil {
  1022. return
  1023. }
  1024. err = unmarshal(body, &st)
  1025. return
  1026. }
  1027. // ChannelDelete deletes the given channel
  1028. // channelID : The ID of a Channel
  1029. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  1030. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1031. if err != nil {
  1032. return
  1033. }
  1034. err = unmarshal(body, &st)
  1035. return
  1036. }
  1037. // ChannelTyping broadcasts to all members that authenticated user is typing in
  1038. // the given channel.
  1039. // channelID : The ID of a Channel
  1040. func (s *Session) ChannelTyping(channelID string) (err error) {
  1041. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  1042. return
  1043. }
  1044. // ChannelMessages returns an array of Message structures for messages within
  1045. // a given channel.
  1046. // channelID : The ID of a Channel.
  1047. // limit : The number messages that can be returned. (max 100)
  1048. // beforeID : If provided all messages returned will be before given ID.
  1049. // afterID : If provided all messages returned will be after given ID.
  1050. // aroundID : If provided all messages returned will be around given ID.
  1051. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  1052. uri := EndpointChannelMessages(channelID)
  1053. v := url.Values{}
  1054. if limit > 0 {
  1055. v.Set("limit", strconv.Itoa(limit))
  1056. }
  1057. if afterID != "" {
  1058. v.Set("after", afterID)
  1059. }
  1060. if beforeID != "" {
  1061. v.Set("before", beforeID)
  1062. }
  1063. if aroundID != "" {
  1064. v.Set("around", aroundID)
  1065. }
  1066. if len(v) > 0 {
  1067. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1068. }
  1069. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  1070. if err != nil {
  1071. return
  1072. }
  1073. err = unmarshal(body, &st)
  1074. return
  1075. }
  1076. // ChannelMessage gets a single message by ID from a given channel.
  1077. // channeld : The ID of a Channel
  1078. // messageID : the ID of a Message
  1079. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  1080. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1081. if err != nil {
  1082. return
  1083. }
  1084. err = unmarshal(response, &st)
  1085. return
  1086. }
  1087. // ChannelMessageAck acknowledges and marks the given message as read
  1088. // channeld : The ID of a Channel
  1089. // messageID : the ID of a Message
  1090. // lastToken : token returned by last ack
  1091. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  1092. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  1093. if err != nil {
  1094. return
  1095. }
  1096. err = unmarshal(body, &st)
  1097. return
  1098. }
  1099. // ChannelMessageSend sends a message to the given channel.
  1100. // channelID : The ID of a Channel.
  1101. // content : The message to send.
  1102. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1103. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1104. Content: content,
  1105. })
  1106. }
  1107. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  1108. // ChannelMessageSendComplex sends a message to the given channel.
  1109. // channelID : The ID of a Channel.
  1110. // data : The message struct to send.
  1111. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1112. if data.Embed != nil && data.Embed.Type == "" {
  1113. data.Embed.Type = "rich"
  1114. }
  1115. endpoint := EndpointChannelMessages(channelID)
  1116. // TODO: Remove this when compatibility is not required.
  1117. files := data.Files
  1118. if data.File != nil {
  1119. if files == nil {
  1120. files = []*File{data.File}
  1121. } else {
  1122. err = fmt.Errorf("cannot specify both File and Files")
  1123. return
  1124. }
  1125. }
  1126. var response []byte
  1127. if len(files) > 0 {
  1128. body := &bytes.Buffer{}
  1129. bodywriter := multipart.NewWriter(body)
  1130. var payload []byte
  1131. payload, err = json.Marshal(data)
  1132. if err != nil {
  1133. return
  1134. }
  1135. var p io.Writer
  1136. h := make(textproto.MIMEHeader)
  1137. h.Set("Content-Disposition", `form-data; name="payload_json"`)
  1138. h.Set("Content-Type", "application/json")
  1139. p, err = bodywriter.CreatePart(h)
  1140. if err != nil {
  1141. return
  1142. }
  1143. if _, err = p.Write(payload); err != nil {
  1144. return
  1145. }
  1146. for i, file := range files {
  1147. h := make(textproto.MIMEHeader)
  1148. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file%d"; filename="%s"`, i, quoteEscaper.Replace(file.Name)))
  1149. contentType := file.ContentType
  1150. if contentType == "" {
  1151. contentType = "application/octet-stream"
  1152. }
  1153. h.Set("Content-Type", contentType)
  1154. p, err = bodywriter.CreatePart(h)
  1155. if err != nil {
  1156. return
  1157. }
  1158. if _, err = io.Copy(p, file.Reader); err != nil {
  1159. return
  1160. }
  1161. }
  1162. err = bodywriter.Close()
  1163. if err != nil {
  1164. return
  1165. }
  1166. response, err = s.request("POST", endpoint, bodywriter.FormDataContentType(), body.Bytes(), endpoint, 0)
  1167. } else {
  1168. response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1169. }
  1170. if err != nil {
  1171. return
  1172. }
  1173. err = unmarshal(response, &st)
  1174. return
  1175. }
  1176. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1177. // channelID : The ID of a Channel.
  1178. // content : The message to send.
  1179. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1180. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1181. Content: content,
  1182. Tts: true,
  1183. })
  1184. }
  1185. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1186. // channelID : The ID of a Channel.
  1187. // embed : The embed data to send.
  1188. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1189. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1190. Embed: embed,
  1191. })
  1192. }
  1193. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1194. // the given content.
  1195. // channelID : The ID of a Channel
  1196. // messageID : The ID of a Message
  1197. // content : The contents of the message
  1198. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1199. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content))
  1200. }
  1201. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1202. // the given MessageEdit struct
  1203. func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) {
  1204. if m.Embed != nil && m.Embed.Type == "" {
  1205. m.Embed.Type = "rich"
  1206. }
  1207. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, ""))
  1208. if err != nil {
  1209. return
  1210. }
  1211. err = unmarshal(response, &st)
  1212. return
  1213. }
  1214. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1215. // channelID : The ID of a Channel
  1216. // messageID : The ID of a Message
  1217. // embed : The embed data to send
  1218. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1219. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbed(embed))
  1220. }
  1221. // ChannelMessageDelete deletes a message from the Channel.
  1222. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1223. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1224. return
  1225. }
  1226. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1227. // If only one messageID is in the slice call channelMessageDelete function.
  1228. // If the slice is empty do nothing.
  1229. // channelID : The ID of the channel for the messages to delete.
  1230. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1231. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1232. if len(messages) == 0 {
  1233. return
  1234. }
  1235. if len(messages) == 1 {
  1236. err = s.ChannelMessageDelete(channelID, messages[0])
  1237. return
  1238. }
  1239. if len(messages) > 100 {
  1240. messages = messages[:100]
  1241. }
  1242. data := struct {
  1243. Messages []string `json:"messages"`
  1244. }{messages}
  1245. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1246. return
  1247. }
  1248. // ChannelMessagePin pins a message within a given channel.
  1249. // channelID: The ID of a channel.
  1250. // messageID: The ID of a message.
  1251. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1252. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1253. return
  1254. }
  1255. // ChannelMessageUnpin unpins a message within a given channel.
  1256. // channelID: The ID of a channel.
  1257. // messageID: The ID of a message.
  1258. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1259. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1260. return
  1261. }
  1262. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1263. // within a given channel
  1264. // channelID : The ID of a Channel.
  1265. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1266. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1267. if err != nil {
  1268. return
  1269. }
  1270. err = unmarshal(body, &st)
  1271. return
  1272. }
  1273. // ChannelFileSend sends a file to the given channel.
  1274. // channelID : The ID of a Channel.
  1275. // name: The name of the file.
  1276. // io.Reader : A reader for the file contents.
  1277. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (*Message, error) {
  1278. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}})
  1279. }
  1280. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1281. // DEPRECATED. Use ChannelMessageSendComplex instead.
  1282. // channelID : The ID of a Channel.
  1283. // content: Optional Message content.
  1284. // name: The name of the file.
  1285. // io.Reader : A reader for the file contents.
  1286. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (*Message, error) {
  1287. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content})
  1288. }
  1289. // ChannelInvites returns an array of Invite structures for the given channel
  1290. // channelID : The ID of a Channel
  1291. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1292. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1293. if err != nil {
  1294. return
  1295. }
  1296. err = unmarshal(body, &st)
  1297. return
  1298. }
  1299. // ChannelInviteCreate creates a new invite for the given channel.
  1300. // channelID : The ID of a Channel
  1301. // i : An Invite struct with the values MaxAge, MaxUses and Temporary defined.
  1302. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1303. data := struct {
  1304. MaxAge int `json:"max_age"`
  1305. MaxUses int `json:"max_uses"`
  1306. Temporary bool `json:"temporary"`
  1307. }{i.MaxAge, i.MaxUses, i.Temporary}
  1308. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1309. if err != nil {
  1310. return
  1311. }
  1312. err = unmarshal(body, &st)
  1313. return
  1314. }
  1315. // ChannelPermissionSet creates a Permission Override for the given channel.
  1316. // NOTE: This func name may changed. Using Set instead of Create because
  1317. // you can both create a new override or update an override with this function.
  1318. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1319. data := struct {
  1320. ID string `json:"id"`
  1321. Type string `json:"type"`
  1322. Allow int `json:"allow"`
  1323. Deny int `json:"deny"`
  1324. }{targetID, targetType, allow, deny}
  1325. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1326. return
  1327. }
  1328. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1329. // NOTE: Name of this func may change.
  1330. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1331. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1332. return
  1333. }
  1334. // ------------------------------------------------------------------------------------------------
  1335. // Functions specific to Discord Invites
  1336. // ------------------------------------------------------------------------------------------------
  1337. // Invite returns an Invite structure of the given invite
  1338. // inviteID : The invite code
  1339. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1340. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1341. if err != nil {
  1342. return
  1343. }
  1344. err = unmarshal(body, &st)
  1345. return
  1346. }
  1347. // InviteDelete deletes an existing invite
  1348. // inviteID : the code of an invite
  1349. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1350. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1351. if err != nil {
  1352. return
  1353. }
  1354. err = unmarshal(body, &st)
  1355. return
  1356. }
  1357. // InviteAccept accepts an Invite to a Guild or Channel
  1358. // inviteID : The invite code
  1359. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1360. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1361. if err != nil {
  1362. return
  1363. }
  1364. err = unmarshal(body, &st)
  1365. return
  1366. }
  1367. // ------------------------------------------------------------------------------------------------
  1368. // Functions specific to Discord Voice
  1369. // ------------------------------------------------------------------------------------------------
  1370. // VoiceRegions returns the voice server regions
  1371. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1372. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1373. if err != nil {
  1374. return
  1375. }
  1376. err = unmarshal(body, &st)
  1377. return
  1378. }
  1379. // VoiceICE returns the voice server ICE information
  1380. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1381. body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce)
  1382. if err != nil {
  1383. return
  1384. }
  1385. err = unmarshal(body, &st)
  1386. return
  1387. }
  1388. // ------------------------------------------------------------------------------------------------
  1389. // Functions specific to Discord Websockets
  1390. // ------------------------------------------------------------------------------------------------
  1391. // Gateway returns the websocket Gateway address
  1392. func (s *Session) Gateway() (gateway string, err error) {
  1393. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1394. if err != nil {
  1395. return
  1396. }
  1397. temp := struct {
  1398. URL string `json:"url"`
  1399. }{}
  1400. err = unmarshal(response, &temp)
  1401. if err != nil {
  1402. return
  1403. }
  1404. gateway = temp.URL
  1405. // Ensure the gateway always has a trailing slash.
  1406. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1407. if !strings.HasSuffix(gateway, "/") {
  1408. gateway += "/"
  1409. }
  1410. return
  1411. }
  1412. // GatewayBot returns the websocket Gateway address and the recommended number of shards
  1413. func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) {
  1414. response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot)
  1415. if err != nil {
  1416. return
  1417. }
  1418. err = unmarshal(response, &st)
  1419. if err != nil {
  1420. return
  1421. }
  1422. // Ensure the gateway always has a trailing slash.
  1423. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1424. if !strings.HasSuffix(st.URL, "/") {
  1425. st.URL += "/"
  1426. }
  1427. return
  1428. }
  1429. // Functions specific to Webhooks
  1430. // WebhookCreate returns a new Webhook.
  1431. // channelID: The ID of a Channel.
  1432. // name : The name of the webhook.
  1433. // avatar : The avatar of the webhook.
  1434. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1435. data := struct {
  1436. Name string `json:"name"`
  1437. Avatar string `json:"avatar,omitempty"`
  1438. }{name, avatar}
  1439. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1440. if err != nil {
  1441. return
  1442. }
  1443. err = unmarshal(body, &st)
  1444. return
  1445. }
  1446. // ChannelWebhooks returns all webhooks for a given channel.
  1447. // channelID: The ID of a channel.
  1448. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1449. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1450. if err != nil {
  1451. return
  1452. }
  1453. err = unmarshal(body, &st)
  1454. return
  1455. }
  1456. // GuildWebhooks returns all webhooks for a given guild.
  1457. // guildID: The ID of a Guild.
  1458. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1459. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1460. if err != nil {
  1461. return
  1462. }
  1463. err = unmarshal(body, &st)
  1464. return
  1465. }
  1466. // Webhook returns a webhook for a given ID
  1467. // webhookID: The ID of a webhook.
  1468. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1469. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1470. if err != nil {
  1471. return
  1472. }
  1473. err = unmarshal(body, &st)
  1474. return
  1475. }
  1476. // WebhookWithToken returns a webhook for a given ID
  1477. // webhookID: The ID of a webhook.
  1478. // token : The auth token for the webhook.
  1479. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1480. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1481. if err != nil {
  1482. return
  1483. }
  1484. err = unmarshal(body, &st)
  1485. return
  1486. }
  1487. // WebhookEdit updates an existing Webhook.
  1488. // webhookID: The ID of a webhook.
  1489. // name : The name of the webhook.
  1490. // avatar : The avatar of the webhook.
  1491. func (s *Session) WebhookEdit(webhookID, name, avatar string) (st *Role, err error) {
  1492. data := struct {
  1493. Name string `json:"name,omitempty"`
  1494. Avatar string `json:"avatar,omitempty"`
  1495. }{name, avatar}
  1496. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1497. if err != nil {
  1498. return
  1499. }
  1500. err = unmarshal(body, &st)
  1501. return
  1502. }
  1503. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1504. // webhookID: The ID of a webhook.
  1505. // token : The auth token for the webhook.
  1506. // name : The name of the webhook.
  1507. // avatar : The avatar of the webhook.
  1508. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1509. data := struct {
  1510. Name string `json:"name,omitempty"`
  1511. Avatar string `json:"avatar,omitempty"`
  1512. }{name, avatar}
  1513. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1514. if err != nil {
  1515. return
  1516. }
  1517. err = unmarshal(body, &st)
  1518. return
  1519. }
  1520. // WebhookDelete deletes a webhook for a given ID
  1521. // webhookID: The ID of a webhook.
  1522. func (s *Session) WebhookDelete(webhookID string) (err error) {
  1523. _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1524. return
  1525. }
  1526. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1527. // webhookID: The ID of a webhook.
  1528. // token : The auth token for the webhook.
  1529. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1530. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1531. if err != nil {
  1532. return
  1533. }
  1534. err = unmarshal(body, &st)
  1535. return
  1536. }
  1537. // WebhookExecute executes a webhook.
  1538. // webhookID: The ID of a webhook.
  1539. // token : The auth token for the webhook
  1540. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (err error) {
  1541. uri := EndpointWebhookToken(webhookID, token)
  1542. if wait {
  1543. uri += "?wait=true"
  1544. }
  1545. _, err = s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))
  1546. return
  1547. }
  1548. // MessageReactionAdd creates an emoji reaction to a message.
  1549. // channelID : The channel ID.
  1550. // messageID : The message ID.
  1551. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1552. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1553. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1554. return err
  1555. }
  1556. // MessageReactionRemove deletes an emoji reaction to a message.
  1557. // channelID : The channel ID.
  1558. // messageID : The message ID.
  1559. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1560. // userID : @me or ID of the user to delete the reaction for.
  1561. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1562. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1563. return err
  1564. }
  1565. // MessageReactionsRemoveAll deletes all reactions from a message
  1566. // channelID : The channel ID
  1567. // messageID : The message ID.
  1568. func (s *Session) MessageReactionsRemoveAll(channelID, messageID string) error {
  1569. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID))
  1570. return err
  1571. }
  1572. // MessageReactions gets all the users reactions for a specific emoji.
  1573. // channelID : The channel ID.
  1574. // messageID : The message ID.
  1575. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1576. // limit : max number of users to return (max 100)
  1577. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int) (st []*User, err error) {
  1578. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1579. v := url.Values{}
  1580. if limit > 0 {
  1581. v.Set("limit", strconv.Itoa(limit))
  1582. }
  1583. if len(v) > 0 {
  1584. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1585. }
  1586. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1587. if err != nil {
  1588. return
  1589. }
  1590. err = unmarshal(body, &st)
  1591. return
  1592. }
  1593. // ------------------------------------------------------------------------------------------------
  1594. // Functions specific to user notes
  1595. // ------------------------------------------------------------------------------------------------
  1596. // UserNoteSet sets the note for a specific user.
  1597. func (s *Session) UserNoteSet(userID string, message string) (err error) {
  1598. data := struct {
  1599. Note string `json:"note"`
  1600. }{message}
  1601. _, err = s.RequestWithBucketID("PUT", EndpointUserNotes(userID), data, EndpointUserNotes(""))
  1602. return
  1603. }
  1604. // ------------------------------------------------------------------------------------------------
  1605. // Functions specific to Discord Relationships (Friends list)
  1606. // ------------------------------------------------------------------------------------------------
  1607. // RelationshipsGet returns an array of all the relationships of the user.
  1608. func (s *Session) RelationshipsGet() (r []*Relationship, err error) {
  1609. body, err := s.RequestWithBucketID("GET", EndpointRelationships(), nil, EndpointRelationships())
  1610. if err != nil {
  1611. return
  1612. }
  1613. err = unmarshal(body, &r)
  1614. return
  1615. }
  1616. // relationshipCreate creates a new relationship. (I.e. send or accept a friend request, block a user.)
  1617. // relationshipType : 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  1618. func (s *Session) relationshipCreate(userID string, relationshipType int) (err error) {
  1619. data := struct {
  1620. Type int `json:"type"`
  1621. }{relationshipType}
  1622. _, err = s.RequestWithBucketID("PUT", EndpointRelationship(userID), data, EndpointRelationships())
  1623. return
  1624. }
  1625. // RelationshipFriendRequestSend sends a friend request to a user.
  1626. // userID: ID of the user.
  1627. func (s *Session) RelationshipFriendRequestSend(userID string) (err error) {
  1628. err = s.relationshipCreate(userID, 4)
  1629. return
  1630. }
  1631. // RelationshipFriendRequestAccept accepts a friend request from a user.
  1632. // userID: ID of the user.
  1633. func (s *Session) RelationshipFriendRequestAccept(userID string) (err error) {
  1634. err = s.relationshipCreate(userID, 1)
  1635. return
  1636. }
  1637. // RelationshipUserBlock blocks a user.
  1638. // userID: ID of the user.
  1639. func (s *Session) RelationshipUserBlock(userID string) (err error) {
  1640. err = s.relationshipCreate(userID, 2)
  1641. return
  1642. }
  1643. // RelationshipDelete removes the relationship with a user.
  1644. // userID: ID of the user.
  1645. func (s *Session) RelationshipDelete(userID string) (err error) {
  1646. _, err = s.RequestWithBucketID("DELETE", EndpointRelationship(userID), nil, EndpointRelationships())
  1647. return
  1648. }
  1649. // RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with.
  1650. // userID: ID of the user.
  1651. func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) {
  1652. body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID))
  1653. if err != nil {
  1654. return
  1655. }
  1656. err = unmarshal(body, &mf)
  1657. return
  1658. }