restapi.go 33 KB

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