restapi.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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. // GuildIntegrations returns an array of Integrations for a guild.
  602. // guildID : The ID of a Guild.
  603. func (s *Session) GuildIntegrations(guildID string) (st []*GuildIntegration, err error) {
  604. body, err := s.Request("GET", GUILD_INTEGRATIONS(guildID), nil)
  605. if err != nil {
  606. return
  607. }
  608. err = unmarshal(body, &st)
  609. return
  610. }
  611. // GuildIntegrationCreate creates a Guild Integration.
  612. // guildID : The ID of a Guild.
  613. // integrationType : The Integration type.
  614. // integrationID : The ID of an integration.
  615. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  616. data := struct {
  617. Type string `json:"type"`
  618. Id string `json:"id"`
  619. }{integrationType, integrationID}
  620. _, err = s.Request("POST", GUILD_INTEGRATIONS(guildID), data)
  621. return
  622. }
  623. // GuildIntegrationEdit edits a Guild Integration.
  624. // guildID : The ID of a Guild.
  625. // integrationType : The Integration type.
  626. // integrationID : The ID of an integration.
  627. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  628. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  629. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  630. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  631. data := struct {
  632. ExpireBehavior int `json:"expire_behavior"`
  633. ExpireGracePeriod int `json:"expire_grace_period"`
  634. EnableEmoticons bool `json:"enable_emoticons"`
  635. }{expireBehavior, expireGracePeriod, enableEmoticons}
  636. _, err = s.Request("PATCH", GUILD_INTEGRATION(guildID, integrationID), data)
  637. return
  638. }
  639. // GuildIntegrationDelete removes the given integration from the Guild.
  640. // guildID : The ID of a Guild.
  641. // integrationID : The ID of an integration.
  642. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  643. _, err = s.Request("DELETE", GUILD_INTEGRATION(guildID, integrationID), nil)
  644. return
  645. }
  646. // GuildIntegrationSync syncs an integration.
  647. // guildID : The ID of a Guild.
  648. // integrationID : The ID of an integration.
  649. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  650. _, err = s.Request("POST", GUILD_INTEGRATION_SYNC(guildID, integrationID), nil)
  651. return
  652. }
  653. // GuildIcon returns an image.Image of a guild icon.
  654. // guildID : The ID of a Guild.
  655. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  656. g, err := s.Guild(guildID)
  657. if err != nil {
  658. return
  659. }
  660. if g.Icon == "" {
  661. err = errors.New("Guild does not have an icon set.")
  662. return
  663. }
  664. body, err := s.Request("GET", GUILD_ICON(guildID, g.Icon), nil)
  665. if err != nil {
  666. return
  667. }
  668. img, _, err = image.Decode(bytes.NewReader(body))
  669. return
  670. }
  671. // GuildSplash returns an image.Image of a guild splash image.
  672. // guildID : The ID of a Guild.
  673. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  674. g, err := s.Guild(guildID)
  675. if err != nil {
  676. return
  677. }
  678. if g.Splash == "" {
  679. err = errors.New("Guild does not have a splash set.")
  680. return
  681. }
  682. body, err := s.Request("GET", GUILD_SPLASH(guildID, g.Splash), nil)
  683. if err != nil {
  684. return
  685. }
  686. img, _, err = image.Decode(bytes.NewReader(body))
  687. return
  688. }
  689. // GuildEmbed returns the embed for a Guild.
  690. // guildID : The ID of a Guild.
  691. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  692. body, err := s.Request("GET", GUILD_EMBED(guildID), nil)
  693. if err != nil {
  694. return
  695. }
  696. err = unmarshal(body, &st)
  697. return
  698. }
  699. // GuildEmbedEdit returns the embed for a Guild.
  700. // guildID : The ID of a Guild.
  701. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  702. data := GuildEmbed{enabled, channelID}
  703. _, err = s.Request("PATCH", GUILD_EMBED(guildID), data)
  704. return
  705. }
  706. // ------------------------------------------------------------------------------------------------
  707. // Functions specific to Discord Channels
  708. // ------------------------------------------------------------------------------------------------
  709. // Channel returns a Channel strucutre of a specific Channel.
  710. // channelID : The ID of the Channel you want returned.
  711. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  712. body, err := s.Request("GET", CHANNEL(channelID), nil)
  713. if err != nil {
  714. return
  715. }
  716. err = unmarshal(body, &st)
  717. return
  718. }
  719. // ChannelEdit edits the given channel
  720. // channelID : The ID of a Channel
  721. // name : The new name to assign the channel.
  722. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  723. data := struct {
  724. Name string `json:"name"`
  725. }{name}
  726. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  727. if err != nil {
  728. return
  729. }
  730. err = unmarshal(body, &st)
  731. return
  732. }
  733. // ChannelDelete deletes the given channel
  734. // channelID : The ID of a Channel
  735. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  736. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  737. if err != nil {
  738. return
  739. }
  740. err = unmarshal(body, &st)
  741. return
  742. }
  743. // ChannelTyping broadcasts to all members that authenticated user is typing in
  744. // the given channel.
  745. // channelID : The ID of a Channel
  746. func (s *Session) ChannelTyping(channelID string) (err error) {
  747. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  748. return
  749. }
  750. // ChannelMessages returns an array of Message structures for messages within
  751. // a given channel.
  752. // channelID : The ID of a Channel.
  753. // limit : The number messages that can be returned. (max 100)
  754. // beforeID : If provided all messages returned will be before given ID.
  755. // afterID : If provided all messages returned will be after given ID.
  756. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID string) (st []*Message, err error) {
  757. uri := CHANNEL_MESSAGES(channelID)
  758. v := url.Values{}
  759. if limit > 0 {
  760. v.Set("limit", strconv.Itoa(limit))
  761. }
  762. if afterID != "" {
  763. v.Set("after", afterID)
  764. }
  765. if beforeID != "" {
  766. v.Set("before", beforeID)
  767. }
  768. if len(v) > 0 {
  769. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  770. }
  771. body, err := s.Request("GET", uri, nil)
  772. if err != nil {
  773. return
  774. }
  775. err = unmarshal(body, &st)
  776. return
  777. }
  778. // ChannelMessageAck acknowledges and marks the given message as read
  779. // channeld : The ID of a Channel
  780. // messageID : the ID of a Message
  781. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  782. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  783. return
  784. }
  785. // channelMessageSend sends a message to the given channel.
  786. // channelID : The ID of a Channel.
  787. // content : The message to send.
  788. // tts : Whether to send the message with TTS.
  789. func (s *Session) channelMessageSend(channelID, content string, tts bool) (st *Message, err error) {
  790. // TODO: nonce string ?
  791. data := struct {
  792. Content string `json:"content"`
  793. TTS bool `json:"tts"`
  794. }{content, tts}
  795. // Send the message to the given channel
  796. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  797. if err != nil {
  798. return
  799. }
  800. err = unmarshal(response, &st)
  801. return
  802. }
  803. // ChannelMessageSend sends a message to the given channel.
  804. // channelID : The ID of a Channel.
  805. // content : The message to send.
  806. func (s *Session) ChannelMessageSend(channelID string, content string) (st *Message, err error) {
  807. return s.channelMessageSend(channelID, content, false)
  808. }
  809. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  810. // channelID : The ID of a Channel.
  811. // content : The message to send.
  812. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (st *Message, err error) {
  813. return s.channelMessageSend(channelID, content, true)
  814. }
  815. // ChannelMessageEdit edits an existing message, replacing it entirely with
  816. // the given content.
  817. // channeld : The ID of a Channel
  818. // messageID : the ID of a Message
  819. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st *Message, err error) {
  820. data := struct {
  821. Content string `json:"content"`
  822. }{content}
  823. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  824. if err != nil {
  825. return
  826. }
  827. err = unmarshal(response, &st)
  828. return
  829. }
  830. // ChannelMessageDelete deletes a message from the Channel.
  831. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  832. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  833. return
  834. }
  835. // ChannelFileSend sends a file to the given channel.
  836. // channelID : The ID of a Channel.
  837. // io.Reader : A reader for the file contents.
  838. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  839. body := &bytes.Buffer{}
  840. bodywriter := multipart.NewWriter(body)
  841. writer, err := bodywriter.CreateFormFile("file", name)
  842. if err != nil {
  843. return nil, err
  844. }
  845. _, err = io.Copy(writer, r)
  846. if err != nil {
  847. return
  848. }
  849. err = bodywriter.Close()
  850. if err != nil {
  851. return
  852. }
  853. response, err := s.request("POST", CHANNEL_MESSAGES(channelID), bodywriter.FormDataContentType(), body.Bytes())
  854. if err != nil {
  855. return
  856. }
  857. err = unmarshal(response, &st)
  858. return
  859. }
  860. // ChannelInvites returns an array of Invite structures for the given channel
  861. // channelID : The ID of a Channel
  862. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  863. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  864. if err != nil {
  865. return
  866. }
  867. err = unmarshal(body, &st)
  868. return
  869. }
  870. // ChannelInviteCreate creates a new invite for the given channel.
  871. // channelID : The ID of a Channel
  872. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  873. // and XkcdPass defined.
  874. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  875. data := struct {
  876. MaxAge int `json:"max_age"`
  877. MaxUses int `json:"max_uses"`
  878. Temporary bool `json:"temporary"`
  879. XKCDPass string `json:"xkcdpass"`
  880. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  881. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  882. if err != nil {
  883. return
  884. }
  885. err = unmarshal(body, &st)
  886. return
  887. }
  888. // ChannelPermissionSet creates a Permission Override for the given channel.
  889. // NOTE: This func name may changed. Using Set instead of Create because
  890. // you can both create a new override or update an override with this function.
  891. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  892. data := struct {
  893. ID string `json:"id"`
  894. Type string `json:"type"`
  895. Allow int `json:"allow"`
  896. Deny int `json:"deny"`
  897. }{targetID, targetType, allow, deny}
  898. _, err = s.Request("PUT", CHANNEL_PERMISSION(channelID, targetID), data)
  899. return
  900. }
  901. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  902. // NOTE: Name of this func may change.
  903. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  904. _, err = s.Request("DELETE", CHANNEL_PERMISSION(channelID, targetID), nil)
  905. return
  906. }
  907. // ------------------------------------------------------------------------------------------------
  908. // Functions specific to Discord Invites
  909. // ------------------------------------------------------------------------------------------------
  910. // Invite returns an Invite structure of the given invite
  911. // inviteID : The invite code (or maybe xkcdpass?)
  912. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  913. body, err := s.Request("GET", INVITE(inviteID), nil)
  914. if err != nil {
  915. return
  916. }
  917. err = unmarshal(body, &st)
  918. return
  919. }
  920. // InviteDelete deletes an existing invite
  921. // inviteID : the code (or maybe xkcdpass?) of an invite
  922. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  923. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  924. if err != nil {
  925. return
  926. }
  927. err = unmarshal(body, &st)
  928. return
  929. }
  930. // InviteAccept accepts an Invite to a Guild or Channel
  931. // inviteID : The invite code (or maybe xkcdpass?)
  932. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  933. body, err := s.Request("POST", INVITE(inviteID), nil)
  934. if err != nil {
  935. return
  936. }
  937. err = unmarshal(body, &st)
  938. return
  939. }
  940. // ------------------------------------------------------------------------------------------------
  941. // Functions specific to Discord Voice
  942. // ------------------------------------------------------------------------------------------------
  943. // VoiceRegions returns the voice server regions
  944. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  945. body, err := s.Request("GET", VOICE_REGIONS, nil)
  946. if err != nil {
  947. return
  948. }
  949. err = unmarshal(body, &st)
  950. return
  951. }
  952. // VoiceICE returns the voice server ICE information
  953. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  954. body, err := s.Request("GET", VOICE_ICE, nil)
  955. if err != nil {
  956. return
  957. }
  958. err = unmarshal(body, &st)
  959. return
  960. }
  961. // ------------------------------------------------------------------------------------------------
  962. // Functions specific to Discord Websockets
  963. // ------------------------------------------------------------------------------------------------
  964. // Gateway returns the a websocket Gateway address
  965. func (s *Session) Gateway() (gateway string, err error) {
  966. response, err := s.Request("GET", GATEWAY, nil)
  967. if err != nil {
  968. return
  969. }
  970. temp := struct {
  971. URL string `json:"url"`
  972. }{}
  973. err = unmarshal(response, &temp)
  974. if err != nil {
  975. return
  976. }
  977. gateway = temp.URL
  978. return
  979. }