restapi.go 19 KB

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