restapi.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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.StatusCreated:
  89. case http.StatusNoContent:
  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. // UserChannelPermissions returns the permission of a user in a channel.
  260. // userID : The ID of the user to calculate permissions for.
  261. // channelID : The ID of the channel to calculate permission for.
  262. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int, err error) {
  263. channel, err := s.Channel(channelID)
  264. if err != nil {
  265. return
  266. }
  267. guild, err := s.Guild(channel.GuildID)
  268. if err != nil {
  269. return
  270. }
  271. if userID == guild.OwnerID {
  272. apermissions = PermissionAll
  273. return
  274. }
  275. member, err := s.GuildMember(guild.ID, userID)
  276. if err != nil {
  277. return
  278. }
  279. for _, role := range guild.Roles {
  280. for _, roleID := range member.Roles {
  281. if role.ID == roleID {
  282. apermissions |= role.Permissions
  283. break
  284. }
  285. }
  286. }
  287. if apermissions&PermissionManageRoles > 0 {
  288. apermissions |= PermissionAll
  289. }
  290. // Member overwrites can override role overrides, so do two passes
  291. for _, overwrite := range channel.PermissionOverwrites {
  292. for _, roleID := range member.Roles {
  293. if overwrite.Type == "role" && roleID == overwrite.ID {
  294. apermissions &= ^overwrite.Deny
  295. apermissions |= overwrite.Allow
  296. break
  297. }
  298. }
  299. }
  300. for _, overwrite := range channel.PermissionOverwrites {
  301. if overwrite.Type == "member" && overwrite.ID == userID {
  302. apermissions &= ^overwrite.Deny
  303. apermissions |= overwrite.Allow
  304. break
  305. }
  306. }
  307. if apermissions&PermissionManageRoles > 0 {
  308. apermissions |= PermissionAllChannel
  309. }
  310. return
  311. }
  312. // ------------------------------------------------------------------------------------------------
  313. // Functions specific to Discord Guilds
  314. // ------------------------------------------------------------------------------------------------
  315. // Guild returns a Guild structure of a specific Guild.
  316. // guildID : The ID of a Guild
  317. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  318. if s.StateEnabled {
  319. // Attempt to grab the guild from State first.
  320. st, err = s.State.Guild(guildID)
  321. if err == nil {
  322. return
  323. }
  324. }
  325. body, err := s.Request("GET", GUILD(guildID), nil)
  326. if err != nil {
  327. return
  328. }
  329. err = unmarshal(body, &st)
  330. return
  331. }
  332. // GuildCreate creates a new Guild
  333. // name : A name for the Guild (2-100 characters)
  334. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  335. data := struct {
  336. Name string `json:"name"`
  337. }{name}
  338. body, err := s.Request("POST", GUILDS, data)
  339. if err != nil {
  340. return
  341. }
  342. err = unmarshal(body, &st)
  343. return
  344. }
  345. // GuildEdit edits a new Guild
  346. // guildID : The ID of a Guild
  347. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  348. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  349. // Bounds checking for VerificationLevel, interval: [0, 3]
  350. if g.VerificationLevel != nil {
  351. val := *g.VerificationLevel
  352. if val < 0 || val > 3 {
  353. err = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  354. return
  355. }
  356. }
  357. //Bounds checking for regions
  358. if g.Region != "" {
  359. isValid := false
  360. regions, _ := s.VoiceRegions()
  361. for _, r := range regions {
  362. if g.Region == r.ID {
  363. isValid = true
  364. }
  365. }
  366. if !isValid {
  367. var valid []string
  368. for _, r := range regions {
  369. valid = append(valid, r.ID)
  370. }
  371. err = errors.New(fmt.Sprintf("Region not a valid region (%q)", valid))
  372. return
  373. }
  374. }
  375. data := struct {
  376. Name string `json:"name,omitempty"`
  377. Region string `json:"region,omitempty"`
  378. VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
  379. }{g.Name, g.Region, g.VerificationLevel}
  380. body, err := s.Request("PATCH", GUILD(guildID), data)
  381. if err != nil {
  382. return
  383. }
  384. err = unmarshal(body, &st)
  385. return
  386. }
  387. // GuildDelete deletes a Guild.
  388. // guildID : The ID of a Guild
  389. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  390. body, err := s.Request("DELETE", GUILD(guildID), nil)
  391. if err != nil {
  392. return
  393. }
  394. err = unmarshal(body, &st)
  395. return
  396. }
  397. // GuildLeave leaves a Guild.
  398. // guildID : The ID of a Guild
  399. func (s *Session) GuildLeave(guildID string) (err error) {
  400. _, err = s.Request("DELETE", USER_GUILD("@me", guildID), nil)
  401. return
  402. }
  403. // GuildBans returns an array of User structures for all bans of a
  404. // given guild.
  405. // guildID : The ID of a Guild.
  406. func (s *Session) GuildBans(guildID string) (st []*User, err error) {
  407. body, err := s.Request("GET", GUILD_BANS(guildID), nil)
  408. if err != nil {
  409. return
  410. }
  411. err = unmarshal(body, &st)
  412. return
  413. }
  414. // GuildBanCreate bans the given user from the given guild.
  415. // guildID : The ID of a Guild.
  416. // userID : The ID of a User
  417. // days : The number of days of previous comments to delete.
  418. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  419. uri := GUILD_BAN(guildID, userID)
  420. if days > 0 {
  421. uri = fmt.Sprintf("%s?delete-message-days=%d", uri, days)
  422. }
  423. _, err = s.Request("PUT", uri, nil)
  424. return
  425. }
  426. // GuildBanDelete removes the given user from the guild bans
  427. // guildID : The ID of a Guild.
  428. // userID : The ID of a User
  429. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  430. _, err = s.Request("DELETE", GUILD_BAN(guildID, userID), nil)
  431. return
  432. }
  433. // GuildMembers returns a list of members for a guild.
  434. // guildID : The ID of a Guild.
  435. // offset : A number of members to skip
  436. // limit : max number of members to return (max 1000)
  437. func (s *Session) GuildMembers(guildID string, offset, limit int) (st []*Member, err error) {
  438. uri := GUILD_MEMBERS(guildID)
  439. v := url.Values{}
  440. if offset > 0 {
  441. v.Set("offset", strconv.Itoa(offset))
  442. }
  443. if limit > 0 {
  444. v.Set("limit", strconv.Itoa(limit))
  445. }
  446. if len(v) > 0 {
  447. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  448. }
  449. body, err := s.Request("GET", uri, nil)
  450. if err != nil {
  451. return
  452. }
  453. err = unmarshal(body, &st)
  454. return
  455. }
  456. // GuildMember returns a member of a guild.
  457. // guildID : The ID of a Guild.
  458. // userID : The ID of a User
  459. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  460. body, err := s.Request("GET", GUILD_MEMBER(guildID, userID), nil)
  461. if err != nil {
  462. return
  463. }
  464. err = unmarshal(body, &st)
  465. return
  466. }
  467. // GuildMemberDelete removes the given user from the given guild.
  468. // guildID : The ID of a Guild.
  469. // userID : The ID of a User
  470. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  471. _, err = s.Request("DELETE", GUILD_MEMBER(guildID, userID), nil)
  472. return
  473. }
  474. // GuildMemberEdit edits the roles of a member.
  475. // guildID : The ID of a Guild.
  476. // userID : The ID of a User.
  477. // roles : A list of role ID's to set on the member.
  478. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  479. data := struct {
  480. Roles []string `json:"roles"`
  481. }{roles}
  482. _, err = s.Request("PATCH", GUILD_MEMBER(guildID, userID), data)
  483. if err != nil {
  484. return
  485. }
  486. return
  487. }
  488. // GuildMemberMove moves a guild member from one voice channel to another/none
  489. // guildID : The ID of a Guild.
  490. // userID : The ID of a User.
  491. // channelID : The ID of a channel to move user to, or null?
  492. // NOTE : I am not entirely set on the name of this function and it may change
  493. // prior to the final 1.0.0 release of Discordgo
  494. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  495. data := struct {
  496. ChannelID string `json:"channel_id"`
  497. }{channelID}
  498. _, err = s.Request("PATCH", GUILD_MEMBER(guildID, userID), data)
  499. if err != nil {
  500. return
  501. }
  502. return
  503. }
  504. // GuildChannels returns an array of Channel structures for all channels of a
  505. // given guild.
  506. // guildID : The ID of a Guild.
  507. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  508. body, err := s.Request("GET", GUILD_CHANNELS(guildID), nil)
  509. if err != nil {
  510. return
  511. }
  512. err = unmarshal(body, &st)
  513. return
  514. }
  515. // GuildChannelCreate creates a new channel in the given guild
  516. // guildID : The ID of a Guild.
  517. // name : Name of the channel (2-100 chars length)
  518. // ctype : Tpye of the channel (voice or text)
  519. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st *Channel, err error) {
  520. data := struct {
  521. Name string `json:"name"`
  522. Type string `json:"type"`
  523. }{name, ctype}
  524. body, err := s.Request("POST", GUILD_CHANNELS(guildID), data)
  525. if err != nil {
  526. return
  527. }
  528. err = unmarshal(body, &st)
  529. return
  530. }
  531. // GuildInvites returns an array of Invite structures for the given guild
  532. // guildID : The ID of a Guild.
  533. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  534. body, err := s.Request("GET", GUILD_INVITES(guildID), nil)
  535. if err != nil {
  536. return
  537. }
  538. err = unmarshal(body, &st)
  539. return
  540. }
  541. // GuildRoles returns all roles for a given guild.
  542. // guildID : The ID of a Guild.
  543. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  544. body, err := s.Request("GET", GUILD_ROLES(guildID), nil)
  545. if err != nil {
  546. return
  547. }
  548. err = unmarshal(body, &st)
  549. return // TODO return pointer
  550. }
  551. // GuildRoleCreate returns a new Guild Role.
  552. // guildID: The ID of a Guild.
  553. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  554. body, err := s.Request("POST", GUILD_ROLES(guildID), nil)
  555. if err != nil {
  556. return
  557. }
  558. err = unmarshal(body, &st)
  559. return
  560. }
  561. // GuildRoleEdit updates an existing Guild Role with new values
  562. // guildID : The ID of a Guild.
  563. // roleID : The ID of a Role.
  564. // name : The name of the Role.
  565. // color : The color of the role (decimal, not hex).
  566. // hoist : Whether to display the role's users separately.
  567. // perm : The permissions for the role.
  568. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int) (st *Role, err error) {
  569. data := struct {
  570. Name string `json:"name"` // The color the role should have (as a decimal, not hex)
  571. Color int `json:"color"` // Whether to display the role's users separately
  572. Hoist bool `json:"hoist"` // The role's name (overwrites existing)
  573. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  574. }{name, color, hoist, perm}
  575. body, err := s.Request("PATCH", GUILD_ROLE(guildID, roleID), data)
  576. if err != nil {
  577. return
  578. }
  579. err = unmarshal(body, &st)
  580. return
  581. }
  582. // GuildRoleReorder reoders guild roles
  583. // guildID : The ID of a Guild.
  584. // roles : A list of ordered roles.
  585. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  586. body, err := s.Request("PATCH", GUILD_ROLES(guildID), roles)
  587. if err != nil {
  588. return
  589. }
  590. err = unmarshal(body, &st)
  591. return
  592. }
  593. // GuildRoleDelete deletes an existing role.
  594. // guildID : The ID of a Guild.
  595. // roleID : The ID of a Role.
  596. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  597. _, err = s.Request("DELETE", GUILD_ROLE(guildID, roleID), nil)
  598. return
  599. }
  600. // GuildIcon returns an image.Image of a guild icon.
  601. // guildID : The ID of a Guild.
  602. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  603. g, err := s.Guild(guildID)
  604. if err != nil {
  605. return
  606. }
  607. if g.Icon == "" {
  608. err = errors.New("Guild does not have an icon set.")
  609. return
  610. }
  611. body, err := s.Request("GET", GUILD_ICON(guildID, g.Icon), nil)
  612. if err != nil {
  613. return
  614. }
  615. img, _, err = image.Decode(bytes.NewReader(body))
  616. return
  617. }
  618. // GuildSplash returns an image.Image of a guild splash image.
  619. // guildID : The ID of a Guild.
  620. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  621. g, err := s.Guild(guildID)
  622. if err != nil {
  623. return
  624. }
  625. if g.Splash == "" {
  626. err = errors.New("Guild does not have a splash set.")
  627. return
  628. }
  629. body, err := s.Request("GET", GUILD_SPLASH(guildID, g.Splash), nil)
  630. if err != nil {
  631. return
  632. }
  633. img, _, err = image.Decode(bytes.NewReader(body))
  634. return
  635. }
  636. // ------------------------------------------------------------------------------------------------
  637. // Functions specific to Discord Channels
  638. // ------------------------------------------------------------------------------------------------
  639. // Channel returns a Channel strucutre of a specific Channel.
  640. // channelID : The ID of the Channel you want returned.
  641. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  642. body, err := s.Request("GET", CHANNEL(channelID), nil)
  643. if err != nil {
  644. return
  645. }
  646. err = unmarshal(body, &st)
  647. return
  648. }
  649. // ChannelEdit edits the given channel
  650. // channelID : The ID of a Channel
  651. // name : The new name to assign the channel.
  652. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  653. data := struct {
  654. Name string `json:"name"`
  655. }{name}
  656. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  657. if err != nil {
  658. return
  659. }
  660. err = unmarshal(body, &st)
  661. return
  662. }
  663. // ChannelDelete deletes the given channel
  664. // channelID : The ID of a Channel
  665. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  666. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  667. if err != nil {
  668. return
  669. }
  670. err = unmarshal(body, &st)
  671. return
  672. }
  673. // ChannelTyping broadcasts to all members that authenticated user is typing in
  674. // the given channel.
  675. // channelID : The ID of a Channel
  676. func (s *Session) ChannelTyping(channelID string) (err error) {
  677. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  678. return
  679. }
  680. // ChannelMessages returns an array of Message structures for messages within
  681. // a given channel.
  682. // channelID : The ID of a Channel.
  683. // limit : The number messages that can be returned. (max 100)
  684. // beforeID : If provided all messages returned will be before given ID.
  685. // afterID : If provided all messages returned will be after given ID.
  686. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID string) (st []*Message, err error) {
  687. uri := CHANNEL_MESSAGES(channelID)
  688. v := url.Values{}
  689. if limit > 0 {
  690. v.Set("limit", strconv.Itoa(limit))
  691. }
  692. if afterID != "" {
  693. v.Set("after", afterID)
  694. }
  695. if beforeID != "" {
  696. v.Set("before", beforeID)
  697. }
  698. if len(v) > 0 {
  699. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  700. }
  701. body, err := s.Request("GET", uri, nil)
  702. if err != nil {
  703. return
  704. }
  705. err = unmarshal(body, &st)
  706. return
  707. }
  708. // ChannelMessageAck acknowledges and marks the given message as read
  709. // channeld : The ID of a Channel
  710. // messageID : the ID of a Message
  711. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  712. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  713. return
  714. }
  715. // channelMessageSend sends a message to the given channel.
  716. // channelID : The ID of a Channel.
  717. // content : The message to send.
  718. // tts : Whether to send the message with TTS.
  719. func (s *Session) channelMessageSend(channelID, content string, tts bool) (st *Message, err error) {
  720. // TODO: nonce string ?
  721. data := struct {
  722. Content string `json:"content"`
  723. TTS bool `json:"tts"`
  724. }{content, tts}
  725. // Send the message to the given channel
  726. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  727. if err != nil {
  728. return
  729. }
  730. err = unmarshal(response, &st)
  731. return
  732. }
  733. // ChannelMessageSend sends a message to the given channel.
  734. // channelID : The ID of a Channel.
  735. // content : The message to send.
  736. func (s *Session) ChannelMessageSend(channelID string, content string) (st *Message, err error) {
  737. return s.channelMessageSend(channelID, content, false)
  738. }
  739. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  740. // channelID : The ID of a Channel.
  741. // content : The message to send.
  742. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (st *Message, err error) {
  743. return s.channelMessageSend(channelID, content, true)
  744. }
  745. // ChannelMessageEdit edits an existing message, replacing it entirely with
  746. // the given content.
  747. // channeld : The ID of a Channel
  748. // messageID : the ID of a Message
  749. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st *Message, err error) {
  750. data := struct {
  751. Content string `json:"content"`
  752. }{content}
  753. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  754. if err != nil {
  755. return
  756. }
  757. err = unmarshal(response, &st)
  758. return
  759. }
  760. // ChannelMessageDelete deletes a message from the Channel.
  761. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  762. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  763. return
  764. }
  765. // ChannelFileSend sends a file to the given channel.
  766. // channelID : The ID of a Channel.
  767. // io.Reader : A reader for the file contents.
  768. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  769. body := &bytes.Buffer{}
  770. bodywriter := multipart.NewWriter(body)
  771. writer, err := bodywriter.CreateFormFile("file", name)
  772. if err != nil {
  773. return nil, err
  774. }
  775. _, err = io.Copy(writer, r)
  776. if err != nil {
  777. return
  778. }
  779. err = bodywriter.Close()
  780. if err != nil {
  781. return
  782. }
  783. response, err := s.request("POST", CHANNEL_MESSAGES(channelID), bodywriter.FormDataContentType(), body.Bytes())
  784. if err != nil {
  785. return
  786. }
  787. err = unmarshal(response, &st)
  788. return
  789. }
  790. // ChannelInvites returns an array of Invite structures for the given channel
  791. // channelID : The ID of a Channel
  792. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  793. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  794. if err != nil {
  795. return
  796. }
  797. err = unmarshal(body, &st)
  798. return
  799. }
  800. // ChannelInviteCreate creates a new invite for the given channel.
  801. // channelID : The ID of a Channel
  802. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  803. // and XkcdPass defined.
  804. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  805. data := struct {
  806. MaxAge int `json:"max_age"`
  807. MaxUses int `json:"max_uses"`
  808. Temporary bool `json:"temporary"`
  809. XKCDPass bool `json:"xkcdpass"`
  810. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  811. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  812. if err != nil {
  813. return
  814. }
  815. err = unmarshal(body, &st)
  816. return
  817. }
  818. // ChannelPermissionSet creates a Permission Override for the given channel.
  819. // NOTE: This func name may changed. Using Set instead of Create because
  820. // you can both create a new override or update an override with this function.
  821. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  822. data := struct {
  823. ID string `json:"id"`
  824. Type string `json:"type"`
  825. Allow int `json:"allow"`
  826. Deny int `json:"deny"`
  827. }{targetID, targetType, allow, deny}
  828. _, err = s.Request("PUT", CHANNEL_PERMISSION(channelID, targetID), data)
  829. return
  830. }
  831. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  832. // NOTE: Name of this func may change.
  833. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  834. _, err = s.Request("DELETE", CHANNEL_PERMISSION(channelID, targetID), nil)
  835. return
  836. }
  837. // ------------------------------------------------------------------------------------------------
  838. // Functions specific to Discord Invites
  839. // ------------------------------------------------------------------------------------------------
  840. // Invite returns an Invite structure of the given invite
  841. // inviteID : The invite code (or maybe xkcdpass?)
  842. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  843. body, err := s.Request("GET", INVITE(inviteID), nil)
  844. if err != nil {
  845. return
  846. }
  847. err = unmarshal(body, &st)
  848. return
  849. }
  850. // InviteDelete deletes an existing invite
  851. // inviteID : the code (or maybe xkcdpass?) of an invite
  852. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  853. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  854. if err != nil {
  855. return
  856. }
  857. err = unmarshal(body, &st)
  858. return
  859. }
  860. // InviteAccept accepts an Invite to a Guild or Channel
  861. // inviteID : The invite code (or maybe xkcdpass?)
  862. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  863. body, err := s.Request("POST", INVITE(inviteID), nil)
  864. if err != nil {
  865. return
  866. }
  867. err = unmarshal(body, &st)
  868. return
  869. }
  870. // ------------------------------------------------------------------------------------------------
  871. // Functions specific to Discord Voice
  872. // ------------------------------------------------------------------------------------------------
  873. // VoiceRegions returns the voice server regions
  874. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  875. body, err := s.Request("GET", VOICE_REGIONS, nil)
  876. if err != nil {
  877. return
  878. }
  879. err = unmarshal(body, &st)
  880. return
  881. }
  882. // VoiceICE returns the voice server ICE information
  883. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  884. body, err := s.Request("GET", VOICE_ICE, nil)
  885. if err != nil {
  886. return
  887. }
  888. err = unmarshal(body, &st)
  889. return
  890. }
  891. // ------------------------------------------------------------------------------------------------
  892. // Functions specific to Discord Websockets
  893. // ------------------------------------------------------------------------------------------------
  894. // Gateway returns the a websocket Gateway address
  895. func (s *Session) Gateway() (gateway string, err error) {
  896. response, err := s.Request("GET", GATEWAY, nil)
  897. if err != nil {
  898. return
  899. }
  900. temp := struct {
  901. URL string `json:"url"`
  902. }{}
  903. err = unmarshal(response, &temp)
  904. if err != nil {
  905. return
  906. }
  907. gateway = temp.URL
  908. return
  909. }