restapi.go 69 KB

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