restapi.go 29 KB

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