restapi.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. 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)
  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. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int, err error) {
  302. channel, err := s.State.Channel(channelID)
  303. if err != nil || channel == nil {
  304. channel, err = s.Channel(channelID)
  305. if err != nil {
  306. return
  307. }
  308. }
  309. guild, err := s.State.Guild(channel.GuildID)
  310. if err != nil || guild == nil {
  311. guild, err = s.Guild(channel.GuildID)
  312. if err != nil {
  313. return
  314. }
  315. }
  316. if userID == guild.OwnerID {
  317. apermissions = PermissionAll
  318. return
  319. }
  320. member, err := s.State.Member(guild.ID, userID)
  321. if err != nil || member == nil {
  322. member, err = s.GuildMember(guild.ID, userID)
  323. if err != nil {
  324. return
  325. }
  326. }
  327. for _, role := range guild.Roles {
  328. for _, roleID := range member.Roles {
  329. if role.ID == roleID {
  330. apermissions |= role.Permissions
  331. break
  332. }
  333. }
  334. }
  335. if apermissions&PermissionManageRoles > 0 {
  336. apermissions |= PermissionAll
  337. }
  338. // Member overwrites can override role overrides, so do two passes
  339. for _, overwrite := range channel.PermissionOverwrites {
  340. for _, roleID := range member.Roles {
  341. if overwrite.Type == "role" && roleID == overwrite.ID {
  342. apermissions &= ^overwrite.Deny
  343. apermissions |= overwrite.Allow
  344. break
  345. }
  346. }
  347. }
  348. for _, overwrite := range channel.PermissionOverwrites {
  349. if overwrite.Type == "member" && overwrite.ID == userID {
  350. apermissions &= ^overwrite.Deny
  351. apermissions |= overwrite.Allow
  352. break
  353. }
  354. }
  355. if apermissions&PermissionManageRoles > 0 {
  356. apermissions |= PermissionAllChannel
  357. }
  358. return
  359. }
  360. // ------------------------------------------------------------------------------------------------
  361. // Functions specific to Discord Guilds
  362. // ------------------------------------------------------------------------------------------------
  363. // Guild returns a Guild structure of a specific Guild.
  364. // guildID : The ID of a Guild
  365. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  366. if s.StateEnabled {
  367. // Attempt to grab the guild from State first.
  368. st, err = s.State.Guild(guildID)
  369. if err == nil {
  370. return
  371. }
  372. }
  373. body, err := s.Request("GET", EndpointGuild(guildID), nil)
  374. if err != nil {
  375. return
  376. }
  377. err = unmarshal(body, &st)
  378. return
  379. }
  380. // GuildCreate creates a new Guild
  381. // name : A name for the Guild (2-100 characters)
  382. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  383. data := struct {
  384. Name string `json:"name"`
  385. }{name}
  386. body, err := s.Request("POST", EndpointGuilds, data)
  387. if err != nil {
  388. return
  389. }
  390. err = unmarshal(body, &st)
  391. return
  392. }
  393. // GuildEdit edits a new Guild
  394. // guildID : The ID of a Guild
  395. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  396. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  397. // Bounds checking for VerificationLevel, interval: [0, 3]
  398. if g.VerificationLevel != nil {
  399. val := *g.VerificationLevel
  400. if val < 0 || val > 3 {
  401. err = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  402. return
  403. }
  404. }
  405. //Bounds checking for regions
  406. if g.Region != "" {
  407. isValid := false
  408. regions, _ := s.VoiceRegions()
  409. for _, r := range regions {
  410. if g.Region == r.ID {
  411. isValid = true
  412. }
  413. }
  414. if !isValid {
  415. var valid []string
  416. for _, r := range regions {
  417. valid = append(valid, r.ID)
  418. }
  419. err = fmt.Errorf("Region not a valid region (%q)", valid)
  420. return
  421. }
  422. }
  423. data := struct {
  424. Name string `json:"name,omitempty"`
  425. Region string `json:"region,omitempty"`
  426. VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
  427. }{g.Name, g.Region, g.VerificationLevel}
  428. body, err := s.Request("PATCH", EndpointGuild(guildID), data)
  429. if err != nil {
  430. return
  431. }
  432. err = unmarshal(body, &st)
  433. return
  434. }
  435. // GuildDelete deletes a Guild.
  436. // guildID : The ID of a Guild
  437. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  438. body, err := s.Request("DELETE", EndpointGuild(guildID), nil)
  439. if err != nil {
  440. return
  441. }
  442. err = unmarshal(body, &st)
  443. return
  444. }
  445. // GuildLeave leaves a Guild.
  446. // guildID : The ID of a Guild
  447. func (s *Session) GuildLeave(guildID string) (err error) {
  448. _, err = s.Request("DELETE", EndpointUserGuild("@me", guildID), nil)
  449. return
  450. }
  451. // GuildBans returns an array of User structures for all bans of a
  452. // given guild.
  453. // guildID : The ID of a Guild.
  454. func (s *Session) GuildBans(guildID string) (st []*User, err error) {
  455. body, err := s.Request("GET", EndpointGuildBans(guildID), nil)
  456. if err != nil {
  457. return
  458. }
  459. err = unmarshal(body, &st)
  460. return
  461. }
  462. // GuildBanCreate bans the given user from the given guild.
  463. // guildID : The ID of a Guild.
  464. // userID : The ID of a User
  465. // days : The number of days of previous comments to delete.
  466. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  467. uri := EndpointGuildBan(guildID, userID)
  468. if days > 0 {
  469. uri = fmt.Sprintf("%s?delete-message-days=%d", uri, days)
  470. }
  471. _, err = s.Request("PUT", uri, nil)
  472. return
  473. }
  474. // GuildBanDelete removes the given user from the guild bans
  475. // guildID : The ID of a Guild.
  476. // userID : The ID of a User
  477. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  478. _, err = s.Request("DELETE", EndpointGuildBan(guildID, userID), nil)
  479. return
  480. }
  481. // GuildMembers returns a list of members for a guild.
  482. // guildID : The ID of a Guild.
  483. // offset : A number of members to skip
  484. // limit : max number of members to return (max 1000)
  485. func (s *Session) GuildMembers(guildID string, offset, limit int) (st []*Member, err error) {
  486. uri := EndpointGuildMembers(guildID)
  487. v := url.Values{}
  488. if offset > 0 {
  489. v.Set("offset", strconv.Itoa(offset))
  490. }
  491. if limit > 0 {
  492. v.Set("limit", strconv.Itoa(limit))
  493. }
  494. if len(v) > 0 {
  495. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  496. }
  497. body, err := s.Request("GET", uri, nil)
  498. if err != nil {
  499. return
  500. }
  501. err = unmarshal(body, &st)
  502. return
  503. }
  504. // GuildMember returns a member of a guild.
  505. // guildID : The ID of a Guild.
  506. // userID : The ID of a User
  507. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  508. body, err := s.Request("GET", EndpointGuildMember(guildID, userID), nil)
  509. if err != nil {
  510. return
  511. }
  512. err = unmarshal(body, &st)
  513. return
  514. }
  515. // GuildMemberDelete removes the given user from the given guild.
  516. // guildID : The ID of a Guild.
  517. // userID : The ID of a User
  518. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  519. _, err = s.Request("DELETE", EndpointGuildMember(guildID, userID), nil)
  520. return
  521. }
  522. // GuildMemberEdit edits the roles of a member.
  523. // guildID : The ID of a Guild.
  524. // userID : The ID of a User.
  525. // roles : A list of role ID's to set on the member.
  526. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  527. data := struct {
  528. Roles []string `json:"roles"`
  529. }{roles}
  530. _, err = s.Request("PATCH", EndpointGuildMember(guildID, userID), data)
  531. if err != nil {
  532. return
  533. }
  534. return
  535. }
  536. // GuildMemberMove moves a guild member from one voice channel to another/none
  537. // guildID : The ID of a Guild.
  538. // userID : The ID of a User.
  539. // channelID : The ID of a channel to move user to, or null?
  540. // NOTE : I am not entirely set on the name of this function and it may change
  541. // prior to the final 1.0.0 release of Discordgo
  542. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  543. data := struct {
  544. ChannelID string `json:"channel_id"`
  545. }{channelID}
  546. _, err = s.Request("PATCH", EndpointGuildMember(guildID, userID), data)
  547. if err != nil {
  548. return
  549. }
  550. return
  551. }
  552. // GuildMemberNickname updates the nickname of a guild member
  553. // guildID : The ID of a guild
  554. // userID : The ID of a user
  555. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  556. data := struct {
  557. Nick string `json:"nick"`
  558. }{nickname}
  559. _, err = s.Request("PATCH", EndpointGuildMember(guildID, userID), data)
  560. return
  561. }
  562. // GuildChannels returns an array of Channel structures for all channels of a
  563. // given guild.
  564. // guildID : The ID of a Guild.
  565. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  566. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil)
  567. if err != nil {
  568. return
  569. }
  570. err = unmarshal(body, &st)
  571. return
  572. }
  573. // GuildChannelCreate creates a new channel in the given guild
  574. // guildID : The ID of a Guild.
  575. // name : Name of the channel (2-100 chars length)
  576. // ctype : Tpye of the channel (voice or text)
  577. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st *Channel, err error) {
  578. data := struct {
  579. Name string `json:"name"`
  580. Type string `json:"type"`
  581. }{name, ctype}
  582. body, err := s.Request("POST", EndpointGuildChannels(guildID), data)
  583. if err != nil {
  584. return
  585. }
  586. err = unmarshal(body, &st)
  587. return
  588. }
  589. // GuildChannelsReorder updates the order of channels in a guild
  590. // guildID : The ID of a Guild.
  591. // channels : Updated channels.
  592. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  593. _, err = s.Request("PATCH", EndpointGuildChannels(guildID), channels)
  594. return
  595. }
  596. // GuildInvites returns an array of Invite structures for the given guild
  597. // guildID : The ID of a Guild.
  598. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  599. body, err := s.Request("GET", EndpointGuildInvites(guildID), nil)
  600. if err != nil {
  601. return
  602. }
  603. err = unmarshal(body, &st)
  604. return
  605. }
  606. // GuildRoles returns all roles for a given guild.
  607. // guildID : The ID of a Guild.
  608. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  609. body, err := s.Request("GET", EndpointGuildRoles(guildID), nil)
  610. if err != nil {
  611. return
  612. }
  613. err = unmarshal(body, &st)
  614. return // TODO return pointer
  615. }
  616. // GuildRoleCreate returns a new Guild Role.
  617. // guildID: The ID of a Guild.
  618. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  619. body, err := s.Request("POST", EndpointGuildRoles(guildID), nil)
  620. if err != nil {
  621. return
  622. }
  623. err = unmarshal(body, &st)
  624. return
  625. }
  626. // GuildRoleEdit updates an existing Guild Role with new values
  627. // guildID : The ID of a Guild.
  628. // roleID : The ID of a Role.
  629. // name : The name of the Role.
  630. // color : The color of the role (decimal, not hex).
  631. // hoist : Whether to display the role's users separately.
  632. // perm : The permissions for the role.
  633. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int) (st *Role, err error) {
  634. // Prevent sending a color int that is too big.
  635. if color > 0xFFFFFF {
  636. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  637. }
  638. data := struct {
  639. Name string `json:"name"` // The color the role should have (as a decimal, not hex)
  640. Color int `json:"color"` // Whether to display the role's users separately
  641. Hoist bool `json:"hoist"` // The role's name (overwrites existing)
  642. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  643. }{name, color, hoist, perm}
  644. body, err := s.Request("PATCH", EndpointGuildRole(guildID, roleID), data)
  645. if err != nil {
  646. return
  647. }
  648. err = unmarshal(body, &st)
  649. return
  650. }
  651. // GuildRoleReorder reoders guild roles
  652. // guildID : The ID of a Guild.
  653. // roles : A list of ordered roles.
  654. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  655. body, err := s.Request("PATCH", EndpointGuildRoles(guildID), roles)
  656. if err != nil {
  657. return
  658. }
  659. err = unmarshal(body, &st)
  660. return
  661. }
  662. // GuildRoleDelete deletes an existing role.
  663. // guildID : The ID of a Guild.
  664. // roleID : The ID of a Role.
  665. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  666. _, err = s.Request("DELETE", EndpointGuildRole(guildID, roleID), nil)
  667. return
  668. }
  669. // GuildIntegrations returns an array of Integrations for a guild.
  670. // guildID : The ID of a Guild.
  671. func (s *Session) GuildIntegrations(guildID string) (st []*GuildIntegration, err error) {
  672. body, err := s.Request("GET", EndpointGuildIntegrations(guildID), nil)
  673. if err != nil {
  674. return
  675. }
  676. err = unmarshal(body, &st)
  677. return
  678. }
  679. // GuildIntegrationCreate creates a Guild Integration.
  680. // guildID : The ID of a Guild.
  681. // integrationType : The Integration type.
  682. // integrationID : The ID of an integration.
  683. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  684. data := struct {
  685. Type string `json:"type"`
  686. ID string `json:"id"`
  687. }{integrationType, integrationID}
  688. _, err = s.Request("POST", EndpointGuildIntegrations(guildID), data)
  689. return
  690. }
  691. // GuildIntegrationEdit edits a Guild Integration.
  692. // guildID : The ID of a Guild.
  693. // integrationType : The Integration type.
  694. // integrationID : The ID of an integration.
  695. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  696. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  697. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  698. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  699. data := struct {
  700. ExpireBehavior int `json:"expire_behavior"`
  701. ExpireGracePeriod int `json:"expire_grace_period"`
  702. EnableEmoticons bool `json:"enable_emoticons"`
  703. }{expireBehavior, expireGracePeriod, enableEmoticons}
  704. _, err = s.Request("PATCH", EndpointGuildIntegration(guildID, integrationID), data)
  705. return
  706. }
  707. // GuildIntegrationDelete removes the given integration from the Guild.
  708. // guildID : The ID of a Guild.
  709. // integrationID : The ID of an integration.
  710. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  711. _, err = s.Request("DELETE", EndpointGuildIntegration(guildID, integrationID), nil)
  712. return
  713. }
  714. // GuildIntegrationSync syncs an integration.
  715. // guildID : The ID of a Guild.
  716. // integrationID : The ID of an integration.
  717. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  718. _, err = s.Request("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil)
  719. return
  720. }
  721. // GuildIcon returns an image.Image of a guild icon.
  722. // guildID : The ID of a Guild.
  723. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  724. g, err := s.Guild(guildID)
  725. if err != nil {
  726. return
  727. }
  728. if g.Icon == "" {
  729. err = errors.New("Guild does not have an icon set.")
  730. return
  731. }
  732. body, err := s.Request("GET", EndpointGuildIcon(guildID, g.Icon), nil)
  733. if err != nil {
  734. return
  735. }
  736. img, _, err = image.Decode(bytes.NewReader(body))
  737. return
  738. }
  739. // GuildSplash returns an image.Image of a guild splash image.
  740. // guildID : The ID of a Guild.
  741. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  742. g, err := s.Guild(guildID)
  743. if err != nil {
  744. return
  745. }
  746. if g.Splash == "" {
  747. err = errors.New("Guild does not have a splash set.")
  748. return
  749. }
  750. body, err := s.Request("GET", EndpointGuildSplash(guildID, g.Splash), nil)
  751. if err != nil {
  752. return
  753. }
  754. img, _, err = image.Decode(bytes.NewReader(body))
  755. return
  756. }
  757. // GuildEmbed returns the embed for a Guild.
  758. // guildID : The ID of a Guild.
  759. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  760. body, err := s.Request("GET", EndpointGuildEmbed(guildID), nil)
  761. if err != nil {
  762. return
  763. }
  764. err = unmarshal(body, &st)
  765. return
  766. }
  767. // GuildEmbedEdit returns the embed for a Guild.
  768. // guildID : The ID of a Guild.
  769. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  770. data := GuildEmbed{enabled, channelID}
  771. _, err = s.Request("PATCH", EndpointGuildEmbed(guildID), data)
  772. return
  773. }
  774. // ------------------------------------------------------------------------------------------------
  775. // Functions specific to Discord Channels
  776. // ------------------------------------------------------------------------------------------------
  777. // Channel returns a Channel strucutre of a specific Channel.
  778. // channelID : The ID of the Channel you want returned.
  779. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  780. body, err := s.Request("GET", EndpointChannel(channelID), nil)
  781. if err != nil {
  782. return
  783. }
  784. err = unmarshal(body, &st)
  785. return
  786. }
  787. // ChannelEdit edits the given channel
  788. // channelID : The ID of a Channel
  789. // name : The new name to assign the channel.
  790. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  791. data := struct {
  792. Name string `json:"name"`
  793. }{name}
  794. body, err := s.Request("PATCH", EndpointChannel(channelID), data)
  795. if err != nil {
  796. return
  797. }
  798. err = unmarshal(body, &st)
  799. return
  800. }
  801. // ChannelDelete deletes the given channel
  802. // channelID : The ID of a Channel
  803. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  804. body, err := s.Request("DELETE", EndpointChannel(channelID), nil)
  805. if err != nil {
  806. return
  807. }
  808. err = unmarshal(body, &st)
  809. return
  810. }
  811. // ChannelTyping broadcasts to all members that authenticated user is typing in
  812. // the given channel.
  813. // channelID : The ID of a Channel
  814. func (s *Session) ChannelTyping(channelID string) (err error) {
  815. _, err = s.Request("POST", EndpointChannelTyping(channelID), nil)
  816. return
  817. }
  818. // ChannelMessages returns an array of Message structures for messages within
  819. // a given channel.
  820. // channelID : The ID of a Channel.
  821. // limit : The number messages that can be returned. (max 100)
  822. // beforeID : If provided all messages returned will be before given ID.
  823. // afterID : If provided all messages returned will be after given ID.
  824. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID string) (st []*Message, err error) {
  825. uri := EndpointChannelMessages(channelID)
  826. v := url.Values{}
  827. if limit > 0 {
  828. v.Set("limit", strconv.Itoa(limit))
  829. }
  830. if afterID != "" {
  831. v.Set("after", afterID)
  832. }
  833. if beforeID != "" {
  834. v.Set("before", beforeID)
  835. }
  836. if len(v) > 0 {
  837. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  838. }
  839. body, err := s.Request("GET", uri, nil)
  840. if err != nil {
  841. return
  842. }
  843. err = unmarshal(body, &st)
  844. return
  845. }
  846. // ChannelMessage gets a single message by ID from a given channel.
  847. // channeld : The ID of a Channel
  848. // messageID : the ID of a Message
  849. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  850. response, err := s.Request("GET", EndpointChannelMessage(channelID, messageID), nil)
  851. if err != nil {
  852. return
  853. }
  854. err = unmarshal(response, &st)
  855. return
  856. }
  857. // ChannelMessageAck acknowledges and marks the given message as read
  858. // channeld : The ID of a Channel
  859. // messageID : the ID of a Message
  860. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  861. _, err = s.request("POST", EndpointChannelMessageAck(channelID, messageID), "", nil)
  862. return
  863. }
  864. // channelMessageSend sends a message to the given channel.
  865. // channelID : The ID of a Channel.
  866. // content : The message to send.
  867. // tts : Whether to send the message with TTS.
  868. func (s *Session) channelMessageSend(channelID, content string, tts bool) (st *Message, err error) {
  869. // TODO: nonce string ?
  870. data := struct {
  871. Content string `json:"content"`
  872. TTS bool `json:"tts"`
  873. }{content, tts}
  874. // Send the message to the given channel
  875. response, err := s.Request("POST", EndpointChannelMessages(channelID), data)
  876. if err != nil {
  877. return
  878. }
  879. err = unmarshal(response, &st)
  880. return
  881. }
  882. // ChannelMessageSend sends a message to the given channel.
  883. // channelID : The ID of a Channel.
  884. // content : The message to send.
  885. func (s *Session) ChannelMessageSend(channelID string, content string) (st *Message, err error) {
  886. return s.channelMessageSend(channelID, content, false)
  887. }
  888. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  889. // channelID : The ID of a Channel.
  890. // content : The message to send.
  891. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (st *Message, err error) {
  892. return s.channelMessageSend(channelID, content, true)
  893. }
  894. // ChannelMessageEdit edits an existing message, replacing it entirely with
  895. // the given content.
  896. // channeld : The ID of a Channel
  897. // messageID : the ID of a Message
  898. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st *Message, err error) {
  899. data := struct {
  900. Content string `json:"content"`
  901. }{content}
  902. response, err := s.Request("PATCH", EndpointChannelMessage(channelID, messageID), data)
  903. if err != nil {
  904. return
  905. }
  906. err = unmarshal(response, &st)
  907. return
  908. }
  909. // ChannelMessageDelete deletes a message from the Channel.
  910. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  911. _, err = s.Request("DELETE", EndpointChannelMessage(channelID, messageID), nil)
  912. return
  913. }
  914. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  915. // If only one messageID is in the slice call channelMessageDelete funciton.
  916. // If the slice is empty do nothing.
  917. // channelID : The ID of the channel for the messages to delete.
  918. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  919. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  920. if len(messages) == 0 {
  921. return
  922. }
  923. if len(messages) == 1 {
  924. err = s.ChannelMessageDelete(channelID, messages[0])
  925. return
  926. }
  927. if len(messages) > 100 {
  928. messages = messages[:100]
  929. }
  930. data := struct {
  931. Messages []string `json:"messages"`
  932. }{messages}
  933. _, err = s.Request("POST", EndpointChannelMessagesBulkDelete(channelID), data)
  934. return
  935. }
  936. // ChannelMessagePin pins a message within a given channel.
  937. // channelID: The ID of a channel.
  938. // messageID: The ID of a message.
  939. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  940. _, err = s.Request("PUT", EndpointChannelMessagePin(channelID, messageID), nil)
  941. return
  942. }
  943. // ChannelMessageUnpin unpins a message within a given channel.
  944. // channelID: The ID of a channel.
  945. // messageID: The ID of a message.
  946. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  947. _, err = s.Request("DELETE", EndpointChannelMessagePin(channelID, messageID), nil)
  948. return
  949. }
  950. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  951. // within a given channel
  952. // channelID : The ID of a Channel.
  953. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  954. body, err := s.Request("GET", EndpointChannelMessagesPins(channelID), nil)
  955. if err != nil {
  956. return
  957. }
  958. err = unmarshal(body, &st)
  959. return
  960. }
  961. // ChannelFileSend sends a file to the given channel.
  962. // channelID : The ID of a Channel.
  963. // io.Reader : A reader for the file contents.
  964. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  965. body := &bytes.Buffer{}
  966. bodywriter := multipart.NewWriter(body)
  967. writer, err := bodywriter.CreateFormFile("file", name)
  968. if err != nil {
  969. return nil, err
  970. }
  971. _, err = io.Copy(writer, r)
  972. if err != nil {
  973. return
  974. }
  975. err = bodywriter.Close()
  976. if err != nil {
  977. return
  978. }
  979. response, err := s.request("POST", EndpointChannelMessages(channelID), bodywriter.FormDataContentType(), body.Bytes())
  980. if err != nil {
  981. return
  982. }
  983. err = unmarshal(response, &st)
  984. return
  985. }
  986. // ChannelInvites returns an array of Invite structures for the given channel
  987. // channelID : The ID of a Channel
  988. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  989. body, err := s.Request("GET", EndpointChannelInvites(channelID), nil)
  990. if err != nil {
  991. return
  992. }
  993. err = unmarshal(body, &st)
  994. return
  995. }
  996. // ChannelInviteCreate creates a new invite for the given channel.
  997. // channelID : The ID of a Channel
  998. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  999. // and XkcdPass defined.
  1000. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1001. data := struct {
  1002. MaxAge int `json:"max_age"`
  1003. MaxUses int `json:"max_uses"`
  1004. Temporary bool `json:"temporary"`
  1005. XKCDPass string `json:"xkcdpass"`
  1006. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  1007. body, err := s.Request("POST", EndpointChannelInvites(channelID), data)
  1008. if err != nil {
  1009. return
  1010. }
  1011. err = unmarshal(body, &st)
  1012. return
  1013. }
  1014. // ChannelPermissionSet creates a Permission Override for the given channel.
  1015. // NOTE: This func name may changed. Using Set instead of Create because
  1016. // you can both create a new override or update an override with this function.
  1017. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1018. data := struct {
  1019. ID string `json:"id"`
  1020. Type string `json:"type"`
  1021. Allow int `json:"allow"`
  1022. Deny int `json:"deny"`
  1023. }{targetID, targetType, allow, deny}
  1024. _, err = s.Request("PUT", EndpointChannelPermission(channelID, targetID), data)
  1025. return
  1026. }
  1027. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1028. // NOTE: Name of this func may change.
  1029. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1030. _, err = s.Request("DELETE", EndpointChannelPermission(channelID, targetID), nil)
  1031. return
  1032. }
  1033. // ------------------------------------------------------------------------------------------------
  1034. // Functions specific to Discord Invites
  1035. // ------------------------------------------------------------------------------------------------
  1036. // Invite returns an Invite structure of the given invite
  1037. // inviteID : The invite code (or maybe xkcdpass?)
  1038. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1039. body, err := s.Request("GET", EndpointInvite(inviteID), nil)
  1040. if err != nil {
  1041. return
  1042. }
  1043. err = unmarshal(body, &st)
  1044. return
  1045. }
  1046. // InviteDelete deletes an existing invite
  1047. // inviteID : the code (or maybe xkcdpass?) of an invite
  1048. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1049. body, err := s.Request("DELETE", EndpointInvite(inviteID), nil)
  1050. if err != nil {
  1051. return
  1052. }
  1053. err = unmarshal(body, &st)
  1054. return
  1055. }
  1056. // InviteAccept accepts an Invite to a Guild or Channel
  1057. // inviteID : The invite code (or maybe xkcdpass?)
  1058. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1059. body, err := s.Request("POST", EndpointInvite(inviteID), nil)
  1060. if err != nil {
  1061. return
  1062. }
  1063. err = unmarshal(body, &st)
  1064. return
  1065. }
  1066. // ------------------------------------------------------------------------------------------------
  1067. // Functions specific to Discord Voice
  1068. // ------------------------------------------------------------------------------------------------
  1069. // VoiceRegions returns the voice server regions
  1070. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1071. body, err := s.Request("GET", EndpointVoiceRegions, nil)
  1072. if err != nil {
  1073. return
  1074. }
  1075. err = unmarshal(body, &st)
  1076. return
  1077. }
  1078. // VoiceICE returns the voice server ICE information
  1079. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1080. body, err := s.Request("GET", EndpointVoiceIce, nil)
  1081. if err != nil {
  1082. return
  1083. }
  1084. err = unmarshal(body, &st)
  1085. return
  1086. }
  1087. // ------------------------------------------------------------------------------------------------
  1088. // Functions specific to Discord Websockets
  1089. // ------------------------------------------------------------------------------------------------
  1090. // Gateway returns the a websocket Gateway address
  1091. func (s *Session) Gateway() (gateway string, err error) {
  1092. response, err := s.Request("GET", EndpointGateway, nil)
  1093. if err != nil {
  1094. return
  1095. }
  1096. temp := struct {
  1097. URL string `json:"url"`
  1098. }{}
  1099. err = unmarshal(response, &temp)
  1100. if err != nil {
  1101. return
  1102. }
  1103. gateway = temp.URL
  1104. return
  1105. }