restapi.go 27 KB

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