restapi.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015 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. "fmt"
  13. "io/ioutil"
  14. "net/http"
  15. "net/url"
  16. "strconv"
  17. "time"
  18. )
  19. // Request makes a (GET/POST/...) Requests to Discord REST API.
  20. // All the other Discord REST Calls in this file use this function.
  21. func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
  22. if s.Debug {
  23. fmt.Printf("API REQUEST %8s :: %s\n", method, urlStr)
  24. fmt.Println("API REQUEST PAYLOAD :: [" + fmt.Sprintf("%+v", data) + "]")
  25. }
  26. body, err := json.Marshal(data)
  27. if err != nil {
  28. return
  29. }
  30. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(body))
  31. if err != nil {
  32. return
  33. }
  34. // Not used on initial login..
  35. // TODO: Verify if a login, otherwise complain about no-token
  36. if s.Token != "" {
  37. req.Header.Set("authorization", s.Token)
  38. }
  39. req.Header.Set("Content-Type", "application/json")
  40. // TODO: Make a configurable static variable.
  41. req.Header.Set("User-Agent", fmt.Sprintf("DiscordBot (https://github.com/bwmarrin/discordgo, v%s)", VERSION))
  42. if s.Debug {
  43. for k, v := range req.Header {
  44. fmt.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
  45. }
  46. }
  47. client := &http.Client{Timeout: (20 * time.Second)}
  48. resp, err := client.Do(req)
  49. if err != nil {
  50. return
  51. }
  52. response, err = ioutil.ReadAll(resp.Body)
  53. if err != nil {
  54. return
  55. }
  56. resp.Body.Close()
  57. if s.Debug {
  58. fmt.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
  59. for k, v := range resp.Header {
  60. fmt.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
  61. }
  62. fmt.Printf("API RESPONSE BODY :: [%s]\n", response)
  63. }
  64. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  65. switch resp.StatusCode {
  66. case 200: // OK
  67. case 204: // No Content
  68. // TODO check for 401 response, invalidate token if we get one.
  69. // TODO check for 429 response, rate-limit when we get one.
  70. default: // Error condition
  71. err = fmt.Errorf("HTTP %d", resp.StatusCode)
  72. return
  73. }
  74. return
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Functions specific to Discord Sessions
  78. // ------------------------------------------------------------------------------------------------
  79. // Login asks the Discord server for an authentication token
  80. func (s *Session) Login(email string, password string) (token string, err error) {
  81. data := struct {
  82. Email string `json:"email"`
  83. Password string `json:"password"`
  84. }{email, password}
  85. response, err := s.Request("POST", LOGIN, data)
  86. var temp map[string]interface{}
  87. err = json.Unmarshal(response, &temp)
  88. token = temp["token"].(string)
  89. return
  90. }
  91. // Logout sends a logout request to Discord.
  92. // This does not seem to actually invalidate the token. So you can still
  93. // make API calls even after a Logout. So, it seems almost pointless to
  94. // even use.
  95. func (s *Session) Logout() (err error) {
  96. // _, err = s.Request("POST", LOGOUT, fmt.Sprintf(`{"token": "%s"}`, s.Token))
  97. return
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Functions specific to Discord Users
  101. // ------------------------------------------------------------------------------------------------
  102. // User returns the user details of the given userID
  103. // userID : A user ID or "@me" which is a shortcut of current user ID
  104. func (s *Session) User(userID string) (st User, err error) {
  105. body, err := s.Request("GET", USER(userID), nil)
  106. err = json.Unmarshal(body, &st)
  107. return
  108. }
  109. // UserUpdate updates a users settings.
  110. // userID : A user ID or "@me" which is a shortcut of current user ID
  111. func (s *Session) UserUpdate(userID, email, password, username, avatar, newPassword string) (st User, err error) {
  112. // NOTE: Avatar must be either the hash/id of existing Avatar or
  113. // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
  114. // to set a new avatar.
  115. // If left blank, avatar will be set to null/blank
  116. data := struct {
  117. Email string `json:"email"`
  118. Password string `json:"password"`
  119. Username string `json:"username"`
  120. Avatar string `json:"avatar,omitempty"`
  121. NewPassword json.Token `json:"new_password,omitempty"`
  122. }{email, password, username, avatar, newPassword}
  123. body, err := s.Request("PATCH", USER(userID), data)
  124. err = json.Unmarshal(body, &st)
  125. return
  126. }
  127. // UserAvatar returns a ?? of a users Avatar
  128. // userID : A user ID or "@me" which is a shortcut of current user ID
  129. func (s *Session) UserAvatar(userID string) (st User, err error) {
  130. u, err := s.User(userID)
  131. _, err = s.Request("GET", USER_AVATAR(userID, u.Avatar), nil)
  132. // TODO need to figure out how to handle returning a file
  133. return
  134. }
  135. // UserSettings returns the settings for a given user
  136. // userID : A user ID or "@me" which is a shortcut of current user ID
  137. // This seems to only return a result for "@me"
  138. func (s *Session) UserSettings(userID string) (st Settings, err error) {
  139. body, err := s.Request("GET", USER_SETTINGS(userID), nil)
  140. err = json.Unmarshal(body, &st)
  141. return
  142. }
  143. // UserChannels returns an array of Channel structures for all private
  144. // channels for a user
  145. // userID : A user ID or "@me" which is a shortcut of current user ID
  146. func (s *Session) UserChannels(userID string) (st []Channel, err error) {
  147. body, err := s.Request("GET", USER_CHANNELS(userID), nil)
  148. err = json.Unmarshal(body, &st)
  149. return
  150. }
  151. // UserChannelCreate creates a new User (Private) Channel with another User
  152. // userID : A user ID or "@me" which is a shortcut of current user ID
  153. // recipientID : A user ID for the user to which this channel is opened with.
  154. func (s *Session) UserChannelCreate(userID, recipientID string) (st Channel, err error) {
  155. data := struct {
  156. RecipientID string `json:"recipient_id"`
  157. }{recipientID}
  158. body, err := s.Request(
  159. "POST",
  160. USER_CHANNELS(userID),
  161. data)
  162. err = json.Unmarshal(body, &st)
  163. return
  164. }
  165. // UserGuilds returns an array of Guild structures for all guilds for a given user
  166. // userID : A user ID or "@me" which is a shortcut of current user ID
  167. func (s *Session) UserGuilds(userID string) (st []Guild, err error) {
  168. body, err := s.Request("GET", USER_GUILDS(userID), nil)
  169. err = json.Unmarshal(body, &st)
  170. return
  171. }
  172. // ------------------------------------------------------------------------------------------------
  173. // Functions specific to Discord Guilds
  174. // ------------------------------------------------------------------------------------------------
  175. // Guild returns a Guild structure of a specific Guild.
  176. // guildID : The ID of a Guild
  177. func (s *Session) Guild(guildID string) (st Guild, err error) {
  178. body, err := s.Request("GET", GUILD(guildID), nil)
  179. err = json.Unmarshal(body, &st)
  180. return
  181. }
  182. // GuildCreate creates a new Guild
  183. // name : A name for the Guild (2-100 characters)
  184. func (s *Session) GuildCreate(name string) (st Guild, err error) {
  185. data := struct {
  186. Name string `json:"name"`
  187. }{name}
  188. body, err := s.Request("POST", GUILDS, data)
  189. err = json.Unmarshal(body, &st)
  190. return
  191. }
  192. // GuildEdit edits a new Guild
  193. // guildID : The ID of a Guild
  194. // name : A name for the Guild (2-100 characters)
  195. func (s *Session) GuildEdit(guildID, name string) (st Guild, err error) {
  196. data := struct {
  197. Name string `json:"name"`
  198. }{name}
  199. body, err := s.Request("POST", GUILD(guildID), data)
  200. err = json.Unmarshal(body, &st)
  201. return
  202. }
  203. // GuildDelete deletes or leaves a Guild.
  204. // guildID : The ID of a Guild
  205. func (s *Session) GuildDelete(guildID string) (st Guild, err error) {
  206. body, err := s.Request("DELETE", GUILD(guildID), nil)
  207. err = json.Unmarshal(body, &st)
  208. return
  209. }
  210. // GuildBans returns an array of User structures for all bans of a
  211. // given guild.
  212. // guildID : The ID of a Guild.
  213. func (s *Session) GuildBans(guildID string) (st []User, err error) {
  214. body, err := s.Request("GET", GUILD_BANS(guildID), nil)
  215. err = json.Unmarshal(body, &st)
  216. return
  217. }
  218. // GuildBanCreate bans the given user from the given guild.
  219. // guildID : The ID of a Guild.
  220. // userID : The ID of a User
  221. // days : The number of days of previous comments to delete.
  222. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  223. uri := GUILD_BAN(guildID, userID)
  224. if days > 0 {
  225. uri = fmt.Sprintf("%s?delete-message-days=%d", uri, days)
  226. }
  227. _, err = s.Request("PUT", uri, nil)
  228. return
  229. }
  230. // GuildBanDelete removes the given user from the guild bans
  231. // guildID : The ID of a Guild.
  232. // userID : The ID of a User
  233. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  234. _, err = s.Request("DELETE", GUILD_BAN(guildID, userID), nil)
  235. return
  236. }
  237. // GuildMemberDelete removes the given user from the given guild.
  238. // guildID : The ID of a Guild.
  239. // userID : The ID of a User
  240. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  241. _, err = s.Request("DELETE", GUILD_MEMBER_DEL(guildID, userID), nil)
  242. return
  243. }
  244. // GuildChannels returns an array of Channel structures for all channels of a
  245. // given guild.
  246. // guildID : The ID of a Guild.
  247. func (s *Session) GuildChannels(guildID string) (st []Channel, err error) {
  248. body, err := s.Request("GET", GUILD_CHANNELS(guildID), nil)
  249. err = json.Unmarshal(body, &st)
  250. return
  251. }
  252. // GuildChannelCreate creates a new channel in the given guild
  253. // guildID : The ID of a Guild.
  254. // name : Name of the channel (2-100 chars length)
  255. // ctype : Tpye of the channel (voice or text)
  256. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st Channel, err error) {
  257. data := struct {
  258. Name string `json:"name"`
  259. Type string `json:"type"`
  260. }{name, ctype}
  261. body, err := s.Request("POST", GUILD_CHANNELS(guildID), data)
  262. err = json.Unmarshal(body, &st)
  263. return
  264. }
  265. // GuildInvites returns an array of Invite structures for the given guild
  266. // guildID : The ID of a Guild.
  267. func (s *Session) GuildInvites(guildID string) (st []Invite, err error) {
  268. body, err := s.Request("GET", GUILD_INVITES(guildID), nil)
  269. err = json.Unmarshal(body, &st)
  270. return
  271. }
  272. // GuildInviteCreate creates a new invite for the given guild.
  273. // guildID : The ID of a Guild.
  274. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  275. // and XkcdPass defined.
  276. func (s *Session) GuildInviteCreate(guildID string, i Invite) (st Invite, err error) {
  277. data := struct {
  278. MaxAge int `json:"max_age"`
  279. MaxUses int `json:"max_uses"`
  280. Temporary bool `json:"temporary"`
  281. XKCDPass bool `json:"xkcdpass"`
  282. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  283. body, err := s.Request("POST", GUILD_INVITES(guildID), data)
  284. err = json.Unmarshal(body, &st)
  285. return
  286. }
  287. // GuildRoles returns all roles for a given guild.
  288. func (s *Session) GuildRoles(guildID string) (st []Role, err error) {
  289. body, err := s.Request("GET", GUILD_ROLES(guildID), nil)
  290. err = json.Unmarshal(body, &st)
  291. return // TODO return pointer
  292. }
  293. // GuildRoleCreate returns a new Guild Role
  294. func (s *Session) GuildRoleCreate(guildID string) (st Role, err error) {
  295. body, err := s.Request("POST", GUILD_ROLES(guildID), nil)
  296. err = json.Unmarshal(body, &st)
  297. return
  298. }
  299. // GuildRoleEdit updates an existing Guild Role with new values
  300. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int) (st Role, err error) {
  301. data := struct {
  302. Name string `json:"name"` // The color the role should have (as a decimal, not hex)
  303. Color int `json:"color"` // Whether to display the role's users separately
  304. Hoist bool `json:"hoist"` // The role's name (overwrites existing)
  305. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  306. }{name, color, hoist, perm}
  307. body, err := s.Request("PATCH", GUILD_ROLE(guildID, roleID), data)
  308. err = json.Unmarshal(body, &st)
  309. return
  310. }
  311. // GuildRoleReorder reoders guild roles
  312. func (s *Session) GuildRoleReorder(guildID string, roles []Role) (st []Role, err error) {
  313. body, err := s.Request("PATCH", GUILD_ROLES(guildID), roles)
  314. err = json.Unmarshal(body, &st)
  315. return
  316. }
  317. // GuildRoleDelete deletes an existing role.
  318. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  319. _, err = s.Request("DELETE", GUILD_ROLE(guildID, roleID), nil)
  320. return
  321. }
  322. // ------------------------------------------------------------------------------------------------
  323. // Functions specific to Discord Channels
  324. // ------------------------------------------------------------------------------------------------
  325. // Channel returns a Channel strucutre of a specific Channel.
  326. // channelID : The ID of the Channel you want returend.
  327. func (s *Session) Channel(channelID string) (st Channel, err error) {
  328. body, err := s.Request("GET", CHANNEL(channelID), nil)
  329. err = json.Unmarshal(body, &st)
  330. return
  331. }
  332. // ChannelEdit edits the given channel
  333. // channelID : The ID of a Channel
  334. // name : The new name to assign the channel.
  335. func (s *Session) ChannelEdit(channelID, name string) (st Channel, err error) {
  336. data := struct {
  337. Name string `json:"name"`
  338. }{name}
  339. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  340. err = json.Unmarshal(body, &st)
  341. return
  342. }
  343. // ChannelDelete deletes the given channel
  344. // channelID : The ID of a Channel
  345. func (s *Session) ChannelDelete(channelID string) (st Channel, err error) {
  346. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  347. err = json.Unmarshal(body, &st)
  348. return
  349. }
  350. // ChannelTyping broadcasts to all members that authenticated user is typing in
  351. // the given channel.
  352. // channelID : The ID of a Channel
  353. func (s *Session) ChannelTyping(channelID string) (err error) {
  354. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  355. return
  356. }
  357. // ChannelMessages returns an array of Message structures for messaages within
  358. // a given channel.
  359. // channelID : The ID of a Channel.
  360. // limit : The number messages that can be returned.
  361. // beforeID : If provided all messages returned will be before given ID.
  362. // afterID : If provided all messages returned will be after given ID.
  363. func (s *Session) ChannelMessages(channelID string, limit int, beforeID int, afterID int) (st []Message, err error) {
  364. uri := CHANNEL_MESSAGES(channelID)
  365. v := url.Values{}
  366. if limit > 0 {
  367. v.Set("limit", strconv.Itoa(limit))
  368. }
  369. if afterID > 0 {
  370. v.Set("after", strconv.Itoa(afterID))
  371. }
  372. if beforeID > 0 {
  373. v.Set("before", strconv.Itoa(beforeID))
  374. }
  375. if len(v) > 0 {
  376. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  377. }
  378. body, err := s.Request("GET", uri, nil)
  379. if err != nil {
  380. return
  381. }
  382. err = json.Unmarshal(body, &st)
  383. return
  384. }
  385. // ChannelMessageAck acknowledges and marks the given message as read
  386. // channeld : The ID of a Channel
  387. // messageID : the ID of a Message
  388. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  389. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  390. return
  391. }
  392. // ChannelMessageSend sends a message to the given channel.
  393. // channelID : The ID of a Channel.
  394. // content : The message to send.
  395. // NOTE, mention and tts parameters may be added in 2.x branch.
  396. func (s *Session) ChannelMessageSend(channelID string, content string) (st Message, err error) {
  397. // TODO: nonce string ?
  398. data := struct {
  399. Content string `json:"content"`
  400. TTS bool `json:"tts"`
  401. }{content, false}
  402. // Send the message to the given channel
  403. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  404. err = json.Unmarshal(response, &st)
  405. return
  406. }
  407. // ChannelMessageEdit edits an existing message, replacing it entirely with
  408. // the given content.
  409. // channeld : The ID of a Channel
  410. // messageID : the ID of a Message
  411. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st Message, err error) {
  412. data := struct {
  413. Content string `json:"content"`
  414. }{content}
  415. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  416. err = json.Unmarshal(response, &st)
  417. return
  418. }
  419. // ChannelMessageDelete deletes a message from the Channel.
  420. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  421. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  422. return
  423. }
  424. // ChannelInvites returns an array of Invite structures for the given channel
  425. // channelID : The ID of a Channel
  426. func (s *Session) ChannelInvites(channelID string) (st []Invite, err error) {
  427. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  428. err = json.Unmarshal(body, &st)
  429. return
  430. }
  431. // ChannelInviteCreate creates a new invite for the given channel.
  432. // channelID : The ID of a Channel
  433. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  434. // and XkcdPass defined.
  435. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st Invite, err error) {
  436. data := struct {
  437. MaxAge int `json:"max_age"`
  438. MaxUses int `json:"max_uses"`
  439. Temporary bool `json:"temporary"`
  440. XKCDPass bool `json:"xkcdpass"`
  441. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  442. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  443. err = json.Unmarshal(body, &st)
  444. return
  445. }
  446. // ------------------------------------------------------------------------------------------------
  447. // Functions specific to Discord Invites
  448. // ------------------------------------------------------------------------------------------------
  449. // Invite returns an Invite structure of the given invite
  450. // inviteID : The invite code (or maybe xkcdpass?)
  451. func (s *Session) Invite(inviteID string) (st Invite, err error) {
  452. body, err := s.Request("GET", INVITE(inviteID), nil)
  453. err = json.Unmarshal(body, &st)
  454. return
  455. }
  456. // InviteDelete deletes an existing invite
  457. // inviteID : the code (or maybe xkcdpass?) of an invite
  458. func (s *Session) InviteDelete(inviteID string) (st Invite, err error) {
  459. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  460. err = json.Unmarshal(body, &st)
  461. return
  462. }
  463. // InviteAccept accepts an Invite to a Guild or Channel
  464. // inviteID : The invite code (or maybe xkcdpass?)
  465. func (s *Session) InviteAccept(inviteID string) (st Invite, err error) {
  466. body, err := s.Request("POST", INVITE(inviteID), nil)
  467. err = json.Unmarshal(body, &st)
  468. return
  469. }
  470. // ------------------------------------------------------------------------------------------------
  471. // Functions specific to Discord Voice
  472. // ------------------------------------------------------------------------------------------------
  473. // VoiceRegions returns the voice server regions
  474. func (s *Session) VoiceRegions() (st []VoiceRegion, err error) {
  475. body, err := s.Request("GET", VOICE_REGIONS, nil)
  476. err = json.Unmarshal(body, &st)
  477. return
  478. }
  479. // VoiceICE returns the voice server ICE information
  480. func (s *Session) VoiceICE() (st VoiceICE, err error) {
  481. body, err := s.Request("GET", VOICE_ICE, nil)
  482. err = json.Unmarshal(body, &st)
  483. return
  484. }
  485. // ------------------------------------------------------------------------------------------------
  486. // Functions specific to Discord Websockets
  487. // ------------------------------------------------------------------------------------------------
  488. // Gateway returns the a websocket Gateway address
  489. func (s *Session) Gateway() (gateway string, err error) {
  490. response, err := s.Request("GET", GATEWAY, nil)
  491. var temp map[string]interface{}
  492. err = json.Unmarshal(response, &temp)
  493. gateway = temp["url"].(string)
  494. return
  495. }