restapi.go 54 KB

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