restapi.go 32 KB

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