restapi.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. "mime/multipart"
  20. "net/http"
  21. "net/url"
  22. "strconv"
  23. "time"
  24. )
  25. // ErrJSONUnmarshal is returned for JSON Unmarshall errors.
  26. var ErrJSONUnmarshal = errors.New("json unmarshal")
  27. // Request makes a (GET/POST/...) Requests to Discord REST API with JSON data.
  28. // All the other Discord REST Calls in this file use this function.
  29. func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
  30. if s.Debug {
  31. fmt.Println("API REQUEST PAYLOAD :: [" + fmt.Sprintf("%+v", data) + "]")
  32. }
  33. var body []byte
  34. if data != nil {
  35. body, err = json.Marshal(data)
  36. if err != nil {
  37. return
  38. }
  39. }
  40. return s.request(method, urlStr, "application/json", body)
  41. }
  42. // request makes a (GET/POST/...) Requests to Discord REST API.
  43. func (s *Session) request(method, urlStr, contentType string, b []byte) (response []byte, err error) {
  44. if s.Debug {
  45. fmt.Printf("API REQUEST %8s :: %s\n", method, urlStr)
  46. }
  47. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
  48. if err != nil {
  49. return
  50. }
  51. // Not used on initial login..
  52. // TODO: Verify if a login, otherwise complain about no-token
  53. if s.Token != "" {
  54. req.Header.Set("authorization", s.Token)
  55. }
  56. req.Header.Set("Content-Type", contentType)
  57. // TODO: Make a configurable static variable.
  58. req.Header.Set("User-Agent", fmt.Sprintf("DiscordBot (https://github.com/bwmarrin/discordgo, v%s)", VERSION))
  59. if s.Debug {
  60. for k, v := range req.Header {
  61. fmt.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
  62. }
  63. }
  64. client := &http.Client{Timeout: (20 * time.Second)}
  65. resp, err := client.Do(req)
  66. if err != nil {
  67. return
  68. }
  69. defer func() {
  70. err := resp.Body.Close()
  71. if err != nil {
  72. fmt.Println("error closing resp body")
  73. }
  74. }()
  75. response, err = ioutil.ReadAll(resp.Body)
  76. if err != nil {
  77. return
  78. }
  79. if s.Debug {
  80. fmt.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
  81. for k, v := range resp.Header {
  82. fmt.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
  83. }
  84. fmt.Printf("API RESPONSE BODY :: [%s]\n", response)
  85. }
  86. switch resp.StatusCode {
  87. case http.StatusOK:
  88. case http.StatusNoContent:
  89. // TODO check for 401 response, invalidate token if we get one.
  90. case 429: // TOO MANY REQUESTS - Rate limiting
  91. rl := RateLimit{}
  92. err = json.Unmarshal(response, &rl)
  93. if err != nil {
  94. err = fmt.Errorf("Request unmarshal rate limit error : %+v", err)
  95. return
  96. }
  97. time.Sleep(rl.RetryAfter)
  98. response, err = s.request(method, urlStr, contentType, b)
  99. default: // Error condition
  100. err = fmt.Errorf("HTTP %s, %s", resp.Status, response)
  101. }
  102. return
  103. }
  104. func unmarshal(data []byte, v interface{}) error {
  105. err := json.Unmarshal(data, v)
  106. if err != nil {
  107. return ErrJSONUnmarshal
  108. }
  109. return nil
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Functions specific to Discord Sessions
  113. // ------------------------------------------------------------------------------------------------
  114. // Login asks the Discord server for an authentication token.
  115. func (s *Session) Login(email, password string) (err error) {
  116. data := struct {
  117. Email string `json:"email"`
  118. Password string `json:"password"`
  119. }{email, password}
  120. response, err := s.Request("POST", LOGIN, data)
  121. if err != nil {
  122. return
  123. }
  124. temp := struct {
  125. Token string `json:"token"`
  126. }{}
  127. err = unmarshal(response, &temp)
  128. if err != nil {
  129. return
  130. }
  131. s.Token = temp.Token
  132. return
  133. }
  134. // Register sends a Register request to Discord, and returns the authentication token
  135. // Note that this account is temporary and should be verified for future use.
  136. // Another option is to save the authentication token external, but this isn't recommended.
  137. func (s *Session) Register(username string) (token string, err error) {
  138. data := struct {
  139. Username string `json:"username"`
  140. }{username}
  141. response, err := s.Request("POST", REGISTER, data)
  142. if err != nil {
  143. return
  144. }
  145. temp := struct {
  146. Token string `json:"token"`
  147. }{}
  148. err = unmarshal(response, &temp)
  149. if err != nil {
  150. return
  151. }
  152. token = temp.Token
  153. return
  154. }
  155. // Logout sends a logout request to Discord.
  156. // This does not seem to actually invalidate the token. So you can still
  157. // make API calls even after a Logout. So, it seems almost pointless to
  158. // even use.
  159. func (s *Session) Logout() (err error) {
  160. // _, err = s.Request("POST", LOGOUT, fmt.Sprintf(`{"token": "%s"}`, s.Token))
  161. if s.Token == "" {
  162. return
  163. }
  164. data := struct {
  165. Token string `json:"token"`
  166. }{s.Token}
  167. _, err = s.Request("POST", LOGOUT, data)
  168. return
  169. }
  170. // ------------------------------------------------------------------------------------------------
  171. // Functions specific to Discord Users
  172. // ------------------------------------------------------------------------------------------------
  173. // User returns the user details of the given userID
  174. // userID : A user ID or "@me" which is a shortcut of current user ID
  175. func (s *Session) User(userID string) (st *User, err error) {
  176. body, err := s.Request("GET", USER(userID), nil)
  177. if err != nil {
  178. return
  179. }
  180. err = unmarshal(body, &st)
  181. return
  182. }
  183. // UserAvatar returns an image.Image of a users Avatar.
  184. // userID : A user ID or "@me" which is a shortcut of current user ID
  185. func (s *Session) UserAvatar(userID string) (img image.Image, err error) {
  186. u, err := s.User(userID)
  187. if err != nil {
  188. return
  189. }
  190. body, err := s.Request("GET", USER_AVATAR(userID, u.Avatar), nil)
  191. if err != nil {
  192. return
  193. }
  194. img, _, err = image.Decode(bytes.NewReader(body))
  195. return
  196. }
  197. // UserUpdate updates a users settings.
  198. func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {
  199. // NOTE: Avatar must be either the hash/id of existing Avatar or
  200. // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
  201. // to set a new avatar.
  202. // If left blank, avatar will be set to null/blank
  203. data := struct {
  204. Email string `json:"email"`
  205. Password string `json:"password"`
  206. Username string `json:"username"`
  207. Avatar string `json:"avatar,omitempty"`
  208. NewPassword string `json:"new_password,omitempty"`
  209. }{email, password, username, avatar, newPassword}
  210. body, err := s.Request("PATCH", USER("@me"), data)
  211. if err != nil {
  212. return
  213. }
  214. err = unmarshal(body, &st)
  215. return
  216. }
  217. // UserSettings returns the settings for a given user
  218. func (s *Session) UserSettings() (st *Settings, err error) {
  219. body, err := s.Request("GET", USER_SETTINGS("@me"), nil)
  220. if err != nil {
  221. return
  222. }
  223. err = unmarshal(body, &st)
  224. return
  225. }
  226. // UserChannels returns an array of Channel structures for all private
  227. // channels.
  228. func (s *Session) UserChannels() (st []*Channel, err error) {
  229. body, err := s.Request("GET", USER_CHANNELS("@me"), nil)
  230. if err != nil {
  231. return
  232. }
  233. err = unmarshal(body, &st)
  234. return
  235. }
  236. // UserChannelCreate creates a new User (Private) Channel with another User
  237. // recipientID : A user ID for the user to which this channel is opened with.
  238. func (s *Session) UserChannelCreate(recipientID string) (st *Channel, err error) {
  239. data := struct {
  240. RecipientID string `json:"recipient_id"`
  241. }{recipientID}
  242. body, err := s.Request("POST", USER_CHANNELS("@me"), data)
  243. if err != nil {
  244. return
  245. }
  246. err = unmarshal(body, &st)
  247. return
  248. }
  249. // UserGuilds returns an array of Guild structures for all guilds.
  250. func (s *Session) UserGuilds() (st []*Guild, err error) {
  251. body, err := s.Request("GET", USER_GUILDS("@me"), nil)
  252. if err != nil {
  253. return
  254. }
  255. err = unmarshal(body, &st)
  256. return
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. // Functions specific to Discord Guilds
  260. // ------------------------------------------------------------------------------------------------
  261. // Guild returns a Guild structure of a specific Guild.
  262. // guildID : The ID of a Guild
  263. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  264. if s.StateEnabled {
  265. // Attempt to grab the guild from State first.
  266. st, err = s.State.Guild(guildID)
  267. if err == nil {
  268. return
  269. }
  270. }
  271. body, err := s.Request("GET", GUILD(guildID), nil)
  272. if err != nil {
  273. return
  274. }
  275. err = unmarshal(body, &st)
  276. return
  277. }
  278. // GuildCreate creates a new Guild
  279. // name : A name for the Guild (2-100 characters)
  280. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  281. data := struct {
  282. Name string `json:"name"`
  283. }{name}
  284. body, err := s.Request("POST", GUILDS, data)
  285. if err != nil {
  286. return
  287. }
  288. err = unmarshal(body, &st)
  289. return
  290. }
  291. // GuildEdit edits a new Guild
  292. // guildID : The ID of a Guild
  293. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  294. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  295. // Bounds checking for VerificationLevel, interval: [0, 3]
  296. if g.VerificationLevel != nil {
  297. val := *g.VerificationLevel
  298. if val < 0 || val > 3 {
  299. err = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  300. return
  301. }
  302. }
  303. //Bounds checking for regions
  304. if g.Region != "" {
  305. isValid := false
  306. regions, _ := s.VoiceRegions()
  307. for _, r := range regions {
  308. if g.Region == r.ID {
  309. isValid = true
  310. }
  311. }
  312. if !isValid {
  313. var valid []string
  314. for _, r := range regions {
  315. valid = append(valid, r.ID)
  316. }
  317. err = errors.New(fmt.Sprintf("Region not a valid region (%q)", valid))
  318. return
  319. }
  320. }
  321. data := struct {
  322. Name string `json:"name,omitempty"`
  323. Region string `json:"region,omitempty"`
  324. VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
  325. }{g.Name, g.Region, g.VerificationLevel}
  326. body, err := s.Request("PATCH", GUILD(guildID), data)
  327. if err != nil {
  328. return
  329. }
  330. err = unmarshal(body, &st)
  331. return
  332. }
  333. // GuildDelete deletes a Guild.
  334. // guildID : The ID of a Guild
  335. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  336. body, err := s.Request("DELETE", GUILD(guildID), nil)
  337. if err != nil {
  338. return
  339. }
  340. err = unmarshal(body, &st)
  341. return
  342. }
  343. // GuildLeave leaves a Guild.
  344. // guildID : The ID of a Guild
  345. func (s *Session) GuildLeave(guildID string) (err error) {
  346. _, err = s.Request("DELETE", USER_GUILD("@me", guildID), nil)
  347. return
  348. }
  349. // GuildBans returns an array of User structures for all bans of a
  350. // given guild.
  351. // guildID : The ID of a Guild.
  352. func (s *Session) GuildBans(guildID string) (st []*User, err error) {
  353. body, err := s.Request("GET", GUILD_BANS(guildID), nil)
  354. if err != nil {
  355. return
  356. }
  357. err = unmarshal(body, &st)
  358. return
  359. }
  360. // GuildBanCreate bans the given user from the given guild.
  361. // guildID : The ID of a Guild.
  362. // userID : The ID of a User
  363. // days : The number of days of previous comments to delete.
  364. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  365. uri := GUILD_BAN(guildID, userID)
  366. if days > 0 {
  367. uri = fmt.Sprintf("%s?delete-message-days=%d", uri, days)
  368. }
  369. _, err = s.Request("PUT", uri, nil)
  370. return
  371. }
  372. // GuildBanDelete removes the given user from the guild bans
  373. // guildID : The ID of a Guild.
  374. // userID : The ID of a User
  375. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  376. _, err = s.Request("DELETE", GUILD_BAN(guildID, userID), nil)
  377. return
  378. }
  379. // GuildMembers returns a list of members for a guild.
  380. // guildID : The ID of a Guild.
  381. // offset : A number of members to skip
  382. // limit : max number of members to return (max 1000)
  383. func (s *Session) GuildMembers(guildID string, offset, limit int) (st []*Member, err error) {
  384. uri := GUILD_MEMBERS(guildID)
  385. v := url.Values{}
  386. if offset > 0 {
  387. v.Set("offset", strconv.Itoa(offset))
  388. }
  389. if limit > 0 {
  390. v.Set("limit", strconv.Itoa(limit))
  391. }
  392. if len(v) > 0 {
  393. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  394. }
  395. body, err := s.Request("GET", uri, nil)
  396. if err != nil {
  397. return
  398. }
  399. err = unmarshal(body, &st)
  400. return
  401. }
  402. // GuildMember returns a member of a guild.
  403. // guildID : The ID of a Guild.
  404. // userID : The ID of a User
  405. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  406. body, err := s.Request("GET", GUILD_MEMBER(guildID, userID), nil)
  407. if err != nil {
  408. return
  409. }
  410. err = unmarshal(body, &st)
  411. return
  412. }
  413. // GuildMemberDelete removes the given user from the given guild.
  414. // guildID : The ID of a Guild.
  415. // userID : The ID of a User
  416. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  417. _, err = s.Request("DELETE", GUILD_MEMBER(guildID, userID), nil)
  418. return
  419. }
  420. // GuildMemberEdit edits the roles of a member.
  421. // guildID : The ID of a Guild.
  422. // userID : The ID of a User.
  423. // roles : A list of role ID's to set on the member.
  424. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  425. data := struct {
  426. Roles []string `json:"roles"`
  427. }{roles}
  428. _, err = s.Request("PATCH", GUILD_MEMBER(guildID, userID), data)
  429. if err != nil {
  430. return
  431. }
  432. return
  433. }
  434. // GuildMemberMove moves a guild member from one voice channel to another/none
  435. // guildID : The ID of a Guild.
  436. // userID : The ID of a User.
  437. // channelID : The ID of a channel to move user to, or null?
  438. // NOTE : I am not entirely set on the name of this function and it may change
  439. // prior to the final 1.0.0 release of Discordgo
  440. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  441. data := struct {
  442. ChannelID string `json:"channel_id"`
  443. }{channelID}
  444. _, err = s.Request("PATCH", GUILD_MEMBER(guildID, userID), data)
  445. if err != nil {
  446. return
  447. }
  448. return
  449. }
  450. // GuildChannels returns an array of Channel structures for all channels of a
  451. // given guild.
  452. // guildID : The ID of a Guild.
  453. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  454. body, err := s.Request("GET", GUILD_CHANNELS(guildID), nil)
  455. if err != nil {
  456. return
  457. }
  458. err = unmarshal(body, &st)
  459. return
  460. }
  461. // GuildChannelCreate creates a new channel in the given guild
  462. // guildID : The ID of a Guild.
  463. // name : Name of the channel (2-100 chars length)
  464. // ctype : Tpye of the channel (voice or text)
  465. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st *Channel, err error) {
  466. data := struct {
  467. Name string `json:"name"`
  468. Type string `json:"type"`
  469. }{name, ctype}
  470. body, err := s.Request("POST", GUILD_CHANNELS(guildID), data)
  471. if err != nil {
  472. return
  473. }
  474. err = unmarshal(body, &st)
  475. return
  476. }
  477. // GuildInvites returns an array of Invite structures for the given guild
  478. // guildID : The ID of a Guild.
  479. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  480. body, err := s.Request("GET", GUILD_INVITES(guildID), nil)
  481. if err != nil {
  482. return
  483. }
  484. err = unmarshal(body, &st)
  485. return
  486. }
  487. // GuildRoles returns all roles for a given guild.
  488. // guildID : The ID of a Guild.
  489. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  490. body, err := s.Request("GET", GUILD_ROLES(guildID), nil)
  491. if err != nil {
  492. return
  493. }
  494. err = unmarshal(body, &st)
  495. return // TODO return pointer
  496. }
  497. // GuildRoleCreate returns a new Guild Role.
  498. // guildID: The ID of a Guild.
  499. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  500. body, err := s.Request("POST", GUILD_ROLES(guildID), nil)
  501. if err != nil {
  502. return
  503. }
  504. err = unmarshal(body, &st)
  505. return
  506. }
  507. // GuildRoleEdit updates an existing Guild Role with new values
  508. // guildID : The ID of a Guild.
  509. // roleID : The ID of a Role.
  510. // name : The name of the Role.
  511. // color : The color of the role (decimal, not hex).
  512. // hoist : Whether to display the role's users separately.
  513. // perm : The permissions for the role.
  514. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int) (st *Role, err error) {
  515. data := struct {
  516. Name string `json:"name"` // The color the role should have (as a decimal, not hex)
  517. Color int `json:"color"` // Whether to display the role's users separately
  518. Hoist bool `json:"hoist"` // The role's name (overwrites existing)
  519. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  520. }{name, color, hoist, perm}
  521. body, err := s.Request("PATCH", GUILD_ROLE(guildID, roleID), data)
  522. if err != nil {
  523. return
  524. }
  525. err = unmarshal(body, &st)
  526. return
  527. }
  528. // GuildRoleReorder reoders guild roles
  529. // guildID : The ID of a Guild.
  530. // roles : A list of ordered roles.
  531. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  532. body, err := s.Request("PATCH", GUILD_ROLES(guildID), roles)
  533. if err != nil {
  534. return
  535. }
  536. err = unmarshal(body, &st)
  537. return
  538. }
  539. // GuildRoleDelete deletes an existing role.
  540. // guildID : The ID of a Guild.
  541. // roleID : The ID of a Role.
  542. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  543. _, err = s.Request("DELETE", GUILD_ROLE(guildID, roleID), nil)
  544. return
  545. }
  546. // GuildIcon returns an image.Image of a guild icon.
  547. // guildID : The ID of a Guild.
  548. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  549. g, err := s.Guild(guildID)
  550. if err != nil {
  551. return
  552. }
  553. if g.Icon == "" {
  554. err = errors.New("Guild does not have an icon set.")
  555. return
  556. }
  557. body, err := s.Request("GET", GUILD_ICON(guildID, g.Icon), nil)
  558. if err != nil {
  559. return
  560. }
  561. img, _, err = image.Decode(bytes.NewReader(body))
  562. return
  563. }
  564. // GuildSplash returns an image.Image of a guild splash image.
  565. // guildID : The ID of a Guild.
  566. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  567. g, err := s.Guild(guildID)
  568. if err != nil {
  569. return
  570. }
  571. if g.Splash == "" {
  572. err = errors.New("Guild does not have a splash set.")
  573. return
  574. }
  575. body, err := s.Request("GET", GUILD_SPLASH(guildID, g.Splash), nil)
  576. if err != nil {
  577. return
  578. }
  579. img, _, err = image.Decode(bytes.NewReader(body))
  580. return
  581. }
  582. // ------------------------------------------------------------------------------------------------
  583. // Functions specific to Discord Channels
  584. // ------------------------------------------------------------------------------------------------
  585. // Channel returns a Channel strucutre of a specific Channel.
  586. // channelID : The ID of the Channel you want returned.
  587. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  588. body, err := s.Request("GET", CHANNEL(channelID), nil)
  589. if err != nil {
  590. return
  591. }
  592. err = unmarshal(body, &st)
  593. return
  594. }
  595. // ChannelEdit edits the given channel
  596. // channelID : The ID of a Channel
  597. // name : The new name to assign the channel.
  598. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  599. data := struct {
  600. Name string `json:"name"`
  601. }{name}
  602. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  603. if err != nil {
  604. return
  605. }
  606. err = unmarshal(body, &st)
  607. return
  608. }
  609. // ChannelDelete deletes the given channel
  610. // channelID : The ID of a Channel
  611. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  612. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  613. if err != nil {
  614. return
  615. }
  616. err = unmarshal(body, &st)
  617. return
  618. }
  619. // ChannelTyping broadcasts to all members that authenticated user is typing in
  620. // the given channel.
  621. // channelID : The ID of a Channel
  622. func (s *Session) ChannelTyping(channelID string) (err error) {
  623. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  624. return
  625. }
  626. // ChannelMessages returns an array of Message structures for messages within
  627. // a given channel.
  628. // channelID : The ID of a Channel.
  629. // limit : The number messages that can be returned. (max 100)
  630. // beforeID : If provided all messages returned will be before given ID.
  631. // afterID : If provided all messages returned will be after given ID.
  632. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID string) (st []*Message, err error) {
  633. uri := CHANNEL_MESSAGES(channelID)
  634. v := url.Values{}
  635. if limit > 0 {
  636. v.Set("limit", strconv.Itoa(limit))
  637. }
  638. if afterID != "" {
  639. v.Set("after", afterID)
  640. }
  641. if beforeID != "" {
  642. v.Set("before", beforeID)
  643. }
  644. if len(v) > 0 {
  645. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  646. }
  647. body, err := s.Request("GET", uri, nil)
  648. if err != nil {
  649. return
  650. }
  651. err = unmarshal(body, &st)
  652. return
  653. }
  654. // ChannelMessageAck acknowledges and marks the given message as read
  655. // channeld : The ID of a Channel
  656. // messageID : the ID of a Message
  657. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  658. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  659. return
  660. }
  661. // channelMessageSend sends a message to the given channel.
  662. // channelID : The ID of a Channel.
  663. // content : The message to send.
  664. // tts : Whether to send the message with TTS.
  665. func (s *Session) channelMessageSend(channelID, content string, tts bool) (st *Message, err error) {
  666. // TODO: nonce string ?
  667. data := struct {
  668. Content string `json:"content"`
  669. TTS bool `json:"tts"`
  670. }{content, tts}
  671. // Send the message to the given channel
  672. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  673. if err != nil {
  674. return
  675. }
  676. err = unmarshal(response, &st)
  677. return
  678. }
  679. // ChannelMessageSend sends a message to the given channel.
  680. // channelID : The ID of a Channel.
  681. // content : The message to send.
  682. func (s *Session) ChannelMessageSend(channelID string, content string) (st *Message, err error) {
  683. return s.channelMessageSend(channelID, content, false)
  684. }
  685. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  686. // channelID : The ID of a Channel.
  687. // content : The message to send.
  688. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (st *Message, err error) {
  689. return s.channelMessageSend(channelID, content, true)
  690. }
  691. // ChannelMessageEdit edits an existing message, replacing it entirely with
  692. // the given content.
  693. // channeld : The ID of a Channel
  694. // messageID : the ID of a Message
  695. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st *Message, err error) {
  696. data := struct {
  697. Content string `json:"content"`
  698. }{content}
  699. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  700. if err != nil {
  701. return
  702. }
  703. err = unmarshal(response, &st)
  704. return
  705. }
  706. // ChannelMessageDelete deletes a message from the Channel.
  707. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  708. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  709. return
  710. }
  711. // ChannelFileSend sends a file to the given channel.
  712. // channelID : The ID of a Channel.
  713. // io.Reader : A reader for the file contents.
  714. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  715. body := &bytes.Buffer{}
  716. bodywriter := multipart.NewWriter(body)
  717. writer, err := bodywriter.CreateFormFile("file", name)
  718. if err != nil {
  719. return nil, err
  720. }
  721. _, err = io.Copy(writer, r)
  722. if err != nil {
  723. return
  724. }
  725. err = bodywriter.Close()
  726. if err != nil {
  727. return
  728. }
  729. response, err := s.request("POST", CHANNEL_MESSAGES(channelID), bodywriter.FormDataContentType(), body.Bytes())
  730. if err != nil {
  731. return
  732. }
  733. err = unmarshal(response, &st)
  734. return
  735. }
  736. // ChannelInvites returns an array of Invite structures for the given channel
  737. // channelID : The ID of a Channel
  738. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  739. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  740. if err != nil {
  741. return
  742. }
  743. err = unmarshal(body, &st)
  744. return
  745. }
  746. // ChannelInviteCreate creates a new invite for the given channel.
  747. // channelID : The ID of a Channel
  748. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  749. // and XkcdPass defined.
  750. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  751. data := struct {
  752. MaxAge int `json:"max_age"`
  753. MaxUses int `json:"max_uses"`
  754. Temporary bool `json:"temporary"`
  755. XKCDPass bool `json:"xkcdpass"`
  756. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  757. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  758. if err != nil {
  759. return
  760. }
  761. err = unmarshal(body, &st)
  762. return
  763. }
  764. // ChannelPermissionSet creates a Permission Override for the given channel.
  765. // NOTE: This func name may changed. Using Set instead of Create because
  766. // you can both create a new override or update an override with this function.
  767. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  768. data := struct {
  769. ID string `json:"id"`
  770. Type string `json:"type"`
  771. Allow int `json:"allow"`
  772. Deny int `json:"deny"`
  773. }{targetID, targetType, allow, deny}
  774. _, err = s.Request("PUT", CHANNEL_PERMISSION(channelID, targetID), data)
  775. return
  776. }
  777. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  778. // NOTE: Name of this func may change.
  779. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  780. _, err = s.Request("DELETE", CHANNEL_PERMISSION(channelID, targetID), nil)
  781. return
  782. }
  783. // ------------------------------------------------------------------------------------------------
  784. // Functions specific to Discord Invites
  785. // ------------------------------------------------------------------------------------------------
  786. // Invite returns an Invite structure of the given invite
  787. // inviteID : The invite code (or maybe xkcdpass?)
  788. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  789. body, err := s.Request("GET", INVITE(inviteID), nil)
  790. if err != nil {
  791. return
  792. }
  793. err = unmarshal(body, &st)
  794. return
  795. }
  796. // InviteDelete deletes an existing invite
  797. // inviteID : the code (or maybe xkcdpass?) of an invite
  798. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  799. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  800. if err != nil {
  801. return
  802. }
  803. err = unmarshal(body, &st)
  804. return
  805. }
  806. // InviteAccept accepts an Invite to a Guild or Channel
  807. // inviteID : The invite code (or maybe xkcdpass?)
  808. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  809. body, err := s.Request("POST", INVITE(inviteID), nil)
  810. if err != nil {
  811. return
  812. }
  813. err = unmarshal(body, &st)
  814. return
  815. }
  816. // ------------------------------------------------------------------------------------------------
  817. // Functions specific to Discord Voice
  818. // ------------------------------------------------------------------------------------------------
  819. // VoiceRegions returns the voice server regions
  820. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  821. body, err := s.Request("GET", VOICE_REGIONS, nil)
  822. if err != nil {
  823. return
  824. }
  825. err = unmarshal(body, &st)
  826. return
  827. }
  828. // VoiceICE returns the voice server ICE information
  829. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  830. body, err := s.Request("GET", VOICE_ICE, nil)
  831. if err != nil {
  832. return
  833. }
  834. err = unmarshal(body, &st)
  835. return
  836. }
  837. // ------------------------------------------------------------------------------------------------
  838. // Functions specific to Discord Websockets
  839. // ------------------------------------------------------------------------------------------------
  840. // Gateway returns the a websocket Gateway address
  841. func (s *Session) Gateway() (gateway string, err error) {
  842. response, err := s.Request("GET", GATEWAY, nil)
  843. if err != nil {
  844. return
  845. }
  846. temp := struct {
  847. URL string `json:"url"`
  848. }{}
  849. err = unmarshal(response, &temp)
  850. if err != nil {
  851. return
  852. }
  853. gateway = temp.URL
  854. return
  855. }