restapi.go 37 KB

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