restapi.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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.Println("REQUEST :: " + method + " " + urlStr + "\n" + string(body))
  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. client := &http.Client{Timeout: (20 * time.Second)}
  41. resp, err := client.Do(req)
  42. if err != nil {
  43. return
  44. }
  45. response, err = ioutil.ReadAll(resp.Body)
  46. if err != nil {
  47. return
  48. }
  49. resp.Body.Close()
  50. // TODO check for 401 response, invalidate token if we get one.
  51. if resp.StatusCode != 204 && resp.StatusCode != 200 {
  52. err = fmt.Errorf("StatusCode: %d, %s", resp.StatusCode, string(response))
  53. return
  54. }
  55. if s.Debug {
  56. printJSON(response)
  57. }
  58. return
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. // Functions specific to Discord Sessions
  62. // ------------------------------------------------------------------------------------------------
  63. // Login asks the Discord server for an authentication token
  64. func (s *Session) Login(email string, password string) (token string, err error) {
  65. data := struct {
  66. Email string `json:"email"`
  67. Password string `json:"password"`
  68. }{email, password}
  69. response, err := s.Request("POST", LOGIN, data)
  70. var temp map[string]interface{}
  71. err = json.Unmarshal(response, &temp)
  72. token = temp["token"].(string)
  73. return
  74. }
  75. // Logout sends a logout request to Discord.
  76. // This does not seem to actually invalidate the token. So you can still
  77. // make API calls even after a Logout. So, it seems almost pointless to
  78. // even use.
  79. func (s *Session) Logout() (err error) {
  80. // _, err = s.Request("POST", LOGOUT, fmt.Sprintf(`{"token": "%s"}`, s.Token))
  81. return
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Functions specific to Discord Users
  85. // ------------------------------------------------------------------------------------------------
  86. // User returns the user details of the given userID
  87. // userID : A user ID or "@me" which is a shortcut of current user ID
  88. func (s *Session) User(userID string) (st User, err error) {
  89. body, err := s.Request("GET", USER(userID), nil)
  90. err = json.Unmarshal(body, &st)
  91. return
  92. }
  93. // UserAvatar returns a ?? of a users Avatar
  94. // userID : A user ID or "@me" which is a shortcut of current user ID
  95. func (s *Session) UserAvatar(userID string) (st User, err error) {
  96. u, err := s.User(userID)
  97. _, err = s.Request("GET", USER_AVATAR(userID, u.Avatar), nil)
  98. // TODO need to figure out how to handle returning a file
  99. return
  100. }
  101. // UserSettings returns the settings for a given user
  102. // userID : A user ID or "@me" which is a shortcut of current user ID
  103. // This seems to only return a result for "@me"
  104. func (s *Session) UserSettings(userID string) (st Settings, err error) {
  105. body, err := s.Request("GET", USER_SETTINGS(userID), nil)
  106. err = json.Unmarshal(body, &st)
  107. return
  108. }
  109. // UserChannels returns an array of Channel structures for all private
  110. // channels for a user
  111. // userID : A user ID or "@me" which is a shortcut of current user ID
  112. func (s *Session) UserChannels(userID string) (st []Channel, err error) {
  113. body, err := s.Request("GET", USER_CHANNELS(userID), nil)
  114. err = json.Unmarshal(body, &st)
  115. return
  116. }
  117. // UserChannelCreate creates a new User (Private) Channel with another User
  118. // userID : A user ID or "@me" which is a shortcut of current user ID
  119. // recipientID : A user ID for the user to which this channel is opened with.
  120. func (s *Session) UserChannelCreate(userID, recipientID string) (st Channel, err error) {
  121. data := struct {
  122. RecipientID string `json:"recipient_id"`
  123. }{recipientID}
  124. body, err := s.Request(
  125. "POST",
  126. USER_CHANNELS(userID),
  127. data)
  128. err = json.Unmarshal(body, &st)
  129. return
  130. }
  131. // UserGuilds returns an array of Guild structures for all guilds for a given user
  132. // userID : A user ID or "@me" which is a shortcut of current user ID
  133. func (s *Session) UserGuilds(userID string) (st []Guild, err error) {
  134. body, err := s.Request("GET", USER_GUILDS(userID), nil)
  135. err = json.Unmarshal(body, &st)
  136. return
  137. }
  138. // ------------------------------------------------------------------------------------------------
  139. // Functions specific to Discord Guilds
  140. // ------------------------------------------------------------------------------------------------
  141. // Guild returns a Guild structure of a specific Guild.
  142. // guildID : The ID of a Guild
  143. func (s *Session) Guild(guildID string) (st Guild, err error) {
  144. body, err := s.Request("GET", GUILD(guildID), nil)
  145. err = json.Unmarshal(body, &st)
  146. return
  147. }
  148. // GuildCreate creates a new Guild
  149. // name : A name for the Guild (2-100 characters)
  150. func (s *Session) GuildCreate(name string) (st Guild, err error) {
  151. data := struct {
  152. Name string `json:"name"`
  153. }{name}
  154. body, err := s.Request("POST", GUILDS, data)
  155. err = json.Unmarshal(body, &st)
  156. return
  157. }
  158. // GuildEdit edits a new Guild
  159. // guildID : The ID of a Guild
  160. // name : A name for the Guild (2-100 characters)
  161. func (s *Session) GuildEdit(guildID, name string) (st Guild, err error) {
  162. data := struct {
  163. Name string `json:"name"`
  164. }{name}
  165. body, err := s.Request("POST", GUILD(guildID), data)
  166. err = json.Unmarshal(body, &st)
  167. return
  168. }
  169. // GuildDelete deletes or leaves a Guild.
  170. // guildID : The ID of a Guild
  171. func (s *Session) GuildDelete(guildID string) (st Guild, err error) {
  172. body, err := s.Request("DELETE", GUILD(guildID), nil)
  173. err = json.Unmarshal(body, &st)
  174. return
  175. }
  176. // GuildBans returns an array of User structures for all bans of a
  177. // given guild.
  178. // guildID : The ID of a Guild.
  179. func (s *Session) GuildBans(guildID string) (st []User, err error) {
  180. body, err := s.Request("GET", GUILD_BANS(guildID), nil)
  181. err = json.Unmarshal(body, &st)
  182. return
  183. }
  184. // GuildBanAdd bans the given user from the given guild.
  185. // guildID : The ID of a Guild.
  186. // userID : The ID of a User
  187. func (s *Session) GuildBanAdd(guildID, userID string) (err error) {
  188. _, err = s.Request("PUT", GUILD_BAN(guildID, userID), nil)
  189. return
  190. }
  191. // GuildBanDelete removes the given user from the guild bans
  192. // guildID : The ID of a Guild.
  193. // userID : The ID of a User
  194. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  195. _, err = s.Request("DELETE", GUILD_BAN(guildID, userID), nil)
  196. return
  197. }
  198. // GuildMemberDelete removes the given user from the given guild.
  199. // guildID : The ID of a Guild.
  200. // userID : The ID of a User
  201. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  202. _, err = s.Request("DELETE", GUILD_MEMBER_DEL(guildID, userID), nil)
  203. return
  204. }
  205. // GuildChannels returns an array of Channel structures for all channels of a
  206. // given guild.
  207. // guildID : The ID of a Guild.
  208. func (s *Session) GuildChannels(guildID string) (st []Channel, err error) {
  209. body, err := s.Request("GET", GUILD_CHANNELS(guildID), nil)
  210. err = json.Unmarshal(body, &st)
  211. return
  212. }
  213. // GuildChannelCreate creates a new channel in the given guild
  214. // guildID : The ID of a Guild.
  215. // name : Name of the channel (2-100 chars length)
  216. // ctype : Tpye of the channel (voice or text)
  217. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st Channel, err error) {
  218. data := struct {
  219. Name string `json:"name"`
  220. Type string `json:"type"`
  221. }{name, ctype}
  222. body, err := s.Request("POST", GUILD_CHANNELS(guildID), data)
  223. err = json.Unmarshal(body, &st)
  224. return
  225. }
  226. // GuildInvites returns an array of Invite structures for the given guild
  227. // guildID : The ID of a Guild.
  228. func (s *Session) GuildInvites(guildID string) (st []Invite, err error) {
  229. body, err := s.Request("GET", GUILD_INVITES(guildID), nil)
  230. err = json.Unmarshal(body, &st)
  231. return
  232. }
  233. // GuildInviteCreate creates a new invite for the given guild.
  234. // guildID : The ID of a Guild.
  235. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  236. // and XkcdPass defined.
  237. func (s *Session) GuildInviteCreate(guildID string, i Invite) (st Invite, err error) {
  238. data := struct {
  239. MaxAge int `json:"max_age"`
  240. MaxUses int `json:"max_uses"`
  241. Temporary bool `json:"temporary"`
  242. XKCDPass bool `json:"xkcdpass"`
  243. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  244. body, err := s.Request("POST", GUILD_INVITES(guildID), data)
  245. err = json.Unmarshal(body, &st)
  246. return
  247. }
  248. // ------------------------------------------------------------------------------------------------
  249. // Functions specific to Discord Channels
  250. // ------------------------------------------------------------------------------------------------
  251. // Channel returns a Channel strucutre of a specific Channel.
  252. // channelID : The ID of the Channel you want returend.
  253. func (s *Session) Channel(channelID string) (st Channel, err error) {
  254. body, err := s.Request("GET", CHANNEL(channelID), nil)
  255. err = json.Unmarshal(body, &st)
  256. return
  257. }
  258. // ChannelEdit edits the given channel
  259. // channelID : The ID of a Channel
  260. // name : The new name to assign the channel.
  261. func (s *Session) ChannelEdit(channelID, name string) (st Channel, err error) {
  262. data := struct {
  263. Name string `json:"name"`
  264. }{name}
  265. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  266. err = json.Unmarshal(body, &st)
  267. return
  268. }
  269. // ChannelDelete deletes the given channel
  270. // channelID : The ID of a Channel
  271. func (s *Session) ChannelDelete(channelID string) (st Channel, err error) {
  272. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  273. err = json.Unmarshal(body, &st)
  274. return
  275. }
  276. // ChannelTyping broadcasts to all members that authenticated user is typing in
  277. // the given channel.
  278. // channelID : The ID of a Channel
  279. func (s *Session) ChannelTyping(channelID string) (err error) {
  280. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  281. return
  282. }
  283. // ChannelMessages returns an array of Message structures for messaages within
  284. // a given channel.
  285. // channelID : The ID of a Channel.
  286. // limit : The number messages that can be returned.
  287. // beforeID : If provided all messages returned will be before given ID.
  288. // afterID : If provided all messages returned will be after given ID.
  289. func (s *Session) ChannelMessages(channelID string, limit int, beforeID int, afterID int) (st []Message, err error) {
  290. var urlStr string
  291. if limit > 0 {
  292. urlStr = fmt.Sprintf("?limit=%d", limit)
  293. }
  294. if afterID > 0 {
  295. if urlStr != "" {
  296. urlStr = urlStr + fmt.Sprintf("&after=%d", afterID)
  297. } else {
  298. urlStr = fmt.Sprintf("?after=%d", afterID)
  299. }
  300. }
  301. if beforeID > 0 {
  302. if urlStr != "" {
  303. urlStr = urlStr + fmt.Sprintf("&before=%d", beforeID)
  304. } else {
  305. urlStr = fmt.Sprintf("?before=%d", beforeID)
  306. }
  307. }
  308. body, err := s.Request("GET", CHANNEL_MESSAGES(channelID)+urlStr, nil)
  309. err = json.Unmarshal(body, &st)
  310. return
  311. }
  312. // ChannelMessageAck acknowledges and marks the given message as read
  313. // channeld : The ID of a Channel
  314. // messageID : the ID of a Message
  315. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  316. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  317. return
  318. }
  319. // ChannelMessageSend sends a message to the given channel.
  320. // channelID : The ID of a Channel.
  321. // content : The message to send.
  322. // NOTE, mention and tts parameters may be added in 2.x branch.
  323. func (s *Session) ChannelMessageSend(channelID string, content string) (st Message, err error) {
  324. // TOD: nonce string ?
  325. data := struct {
  326. Content string `json:"content"`
  327. Mentions []string `json:"mentions"`
  328. TTS bool `json:"tts"`
  329. }{content, nil, false}
  330. // If true, search for <@ID> tags and add those IDs to mention list.
  331. if s.AutoMention {
  332. re := regexp.MustCompile(`<@(\d+)>`)
  333. match := re.FindAllStringSubmatch(content, -1)
  334. mentions := make([]string, len(match))
  335. for i, m := range match {
  336. mentions[i] = m[1]
  337. }
  338. data.Mentions = mentions
  339. }
  340. // Send the message to the given channel
  341. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  342. err = json.Unmarshal(response, &st)
  343. return
  344. }
  345. // ChannelMessageEdit edits an existing message, replacing it entirely with
  346. // the given content.
  347. // channeld : The ID of a Channel
  348. // messageID : the ID of a Message
  349. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st Message, err error) {
  350. data := struct {
  351. Content string `json:"content"`
  352. }{content}
  353. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  354. err = json.Unmarshal(response, &st)
  355. return
  356. }
  357. // ChannelMessageDelete deletes a message from the Channel.
  358. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  359. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  360. return
  361. }
  362. // ChannelInvites returns an array of Invite structures for the given channel
  363. // channelID : The ID of a Channel
  364. func (s *Session) ChannelInvites(channelID string) (st []Invite, err error) {
  365. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  366. err = json.Unmarshal(body, &st)
  367. return
  368. }
  369. // ChannelInviteCreate creates a new invite for the given channel.
  370. // channelID : The ID of a Channel
  371. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  372. // and XkcdPass defined.
  373. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st Invite, err error) {
  374. data := struct {
  375. MaxAge int `json:"max_age"`
  376. MaxUses int `json:"max_uses"`
  377. Temporary bool `json:"temporary"`
  378. XKCDPass bool `json:"xkcdpass"`
  379. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  380. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  381. err = json.Unmarshal(body, &st)
  382. return
  383. }
  384. // ------------------------------------------------------------------------------------------------
  385. // Functions specific to Discord Invites
  386. // ------------------------------------------------------------------------------------------------
  387. // Invite returns an Invite structure of the given invite
  388. // inviteID : The invite code (or maybe xkcdpass?)
  389. func (s *Session) Invite(inviteID string) (st Invite, err error) {
  390. body, err := s.Request("GET", INVITE(inviteID), nil)
  391. err = json.Unmarshal(body, &st)
  392. return
  393. }
  394. // InviteDelete deletes an existing invite
  395. // inviteID : the code (or maybe xkcdpass?) of an invite
  396. func (s *Session) InviteDelete(inviteID string) (st Invite, err error) {
  397. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  398. err = json.Unmarshal(body, &st)
  399. return
  400. }
  401. // InviteAccept accepts an Invite to a Guild or Channel
  402. // inviteID : The invite code (or maybe xkcdpass?)
  403. func (s *Session) InviteAccept(inviteID string) (st Invite, err error) {
  404. body, err := s.Request("POST", INVITE(inviteID), nil)
  405. err = json.Unmarshal(body, &st)
  406. return
  407. }
  408. // ------------------------------------------------------------------------------------------------
  409. // Functions specific to Discord Voice
  410. // ------------------------------------------------------------------------------------------------
  411. // VoiceRegions returns the voice server regions
  412. func (s *Session) VoiceRegions() (st []VoiceRegion, err error) {
  413. body, err := s.Request("GET", VOICE_REGIONS, nil)
  414. err = json.Unmarshal(body, &st)
  415. return
  416. }
  417. // VoiceICE returns the voice server ICE information
  418. func (s *Session) VoiceICE() (st VoiceICE, err error) {
  419. body, err := s.Request("GET", VOICE_ICE, nil)
  420. err = json.Unmarshal(body, &st)
  421. return
  422. }
  423. // ------------------------------------------------------------------------------------------------
  424. // Functions specific to Discord Websockets
  425. // ------------------------------------------------------------------------------------------------
  426. // Gateway returns the a websocket Gateway address
  427. func (s *Session) Gateway() (gateway string, err error) {
  428. response, err := s.Request("GET", GATEWAY, nil)
  429. var temp map[string]interface{}
  430. err = json.Unmarshal(response, &temp)
  431. gateway = temp["url"].(string)
  432. return
  433. }