restapi.go 64 KB

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