restapi.go 38 KB

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