restapi.go 20 KB

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