restapi.go 63 KB

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