restapi.go 33 KB

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