restapi.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. // GuildMembers returns an array of Member structures for all members of a
  199. // given guild.
  200. // guildID : The ID of a Guild.
  201. func (s *Session) GuildMembers(guildID string) (st []Member, err error) {
  202. body, err := s.Request("GET", GUILD_MEMBERS(guildID), nil)
  203. err = json.Unmarshal(body, &st)
  204. return
  205. }
  206. // GuildMemberDelete removes the given user from the given guild.
  207. // guildID : The ID of a Guild.
  208. // userID : The ID of a User
  209. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  210. _, err = s.Request("DELETE", GUILD_MEMBER_DEL(guildID, userID), nil)
  211. return
  212. }
  213. // GuildChannels returns an array of Channel structures for all channels of a
  214. // given guild.
  215. // guildID : The ID of a Guild.
  216. func (s *Session) GuildChannels(guildID string) (st []Channel, err error) {
  217. body, err := s.Request("GET", GUILD_CHANNELS(guildID), nil)
  218. err = json.Unmarshal(body, &st)
  219. return
  220. }
  221. // GuildChannelCreate creates a new channel in the given guild
  222. // guildID : The ID of a Guild.
  223. // name : Name of the channel (2-100 chars length)
  224. // ctype : Tpye of the channel (voice or text)
  225. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st Channel, err error) {
  226. data := struct {
  227. Name string `json:"name"`
  228. Type string `json:"type"`
  229. }{name, ctype}
  230. body, err := s.Request("POST", GUILD_CHANNELS(guildID), data)
  231. err = json.Unmarshal(body, &st)
  232. return
  233. }
  234. // GuildInvites returns an array of Invite structures for the given guild
  235. // guildID : The ID of a Guild.
  236. func (s *Session) GuildInvites(guildID string) (st []Invite, err error) {
  237. body, err := s.Request("GET", GUILD_INVITES(guildID), nil)
  238. err = json.Unmarshal(body, &st)
  239. return
  240. }
  241. // GuildInviteCreate creates a new invite for the given guild.
  242. // guildID : The ID of a Guild.
  243. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  244. // and XkcdPass defined.
  245. func (s *Session) GuildInviteCreate(guildID string, i Invite) (st Invite, err error) {
  246. data := struct {
  247. MaxAge int `json:"max_age"`
  248. MaxUses int `json:"max_uses"`
  249. Temporary bool `json:"temporary"`
  250. XKCDPass bool `json:"xkcdpass"`
  251. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  252. body, err := s.Request("POST", GUILD_INVITES(guildID), data)
  253. err = json.Unmarshal(body, &st)
  254. return
  255. }
  256. // ------------------------------------------------------------------------------------------------
  257. // Functions specific to Discord Channels
  258. // ------------------------------------------------------------------------------------------------
  259. // Channel returns a Channel strucutre of a specific Channel.
  260. // channelID : The ID of the Channel you want returend.
  261. func (s *Session) Channel(channelID string) (st Channel, err error) {
  262. body, err := s.Request("GET", CHANNEL(channelID), nil)
  263. err = json.Unmarshal(body, &st)
  264. return
  265. }
  266. // ChannelEdit edits the given channel
  267. // channelID : The ID of a Channel
  268. // name : The new name to assign the channel.
  269. func (s *Session) ChannelEdit(channelID, name string) (st Channel, err error) {
  270. data := struct {
  271. Name string `json:"name"`
  272. }{name}
  273. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  274. err = json.Unmarshal(body, &st)
  275. return
  276. }
  277. // ChannelDelete deletes the given channel
  278. // channelID : The ID of a Channel
  279. func (s *Session) ChannelDelete(channelID string) (st Channel, err error) {
  280. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  281. err = json.Unmarshal(body, &st)
  282. return
  283. }
  284. // ChannelTyping broadcasts to all members that authenticated user is typing in
  285. // the given channel.
  286. // channelID : The ID of a Channel
  287. func (s *Session) ChannelTyping(channelID string) (err error) {
  288. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  289. return
  290. }
  291. // ChannelMessages returns an array of Message structures for messaages within
  292. // a given channel.
  293. // channelID : The ID of a Channel.
  294. // limit : The number messages that can be returned.
  295. // beforeID : If provided all messages returned will be before given ID.
  296. // afterID : If provided all messages returned will be after given ID.
  297. func (s *Session) ChannelMessages(channelID string, limit int, beforeID int, afterID int) (st []Message, err error) {
  298. var urlStr string
  299. if limit > 0 {
  300. urlStr = fmt.Sprintf("?limit=%d", limit)
  301. }
  302. if afterID > 0 {
  303. if urlStr != "" {
  304. urlStr = urlStr + fmt.Sprintf("&after=%d", afterID)
  305. } else {
  306. urlStr = fmt.Sprintf("?after=%d", afterID)
  307. }
  308. }
  309. if beforeID > 0 {
  310. if urlStr != "" {
  311. urlStr = urlStr + fmt.Sprintf("&before=%d", beforeID)
  312. } else {
  313. urlStr = fmt.Sprintf("?before=%d", beforeID)
  314. }
  315. }
  316. body, err := s.Request("GET", CHANNEL_MESSAGES(channelID)+urlStr, nil)
  317. err = json.Unmarshal(body, &st)
  318. return
  319. }
  320. // ChannelMessageAck acknowledges and marks the given message as read
  321. // channeld : The ID of a Channel
  322. // messageID : the ID of a Message
  323. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  324. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  325. return
  326. }
  327. // ChannelMessageSend sends a message to the given channel.
  328. // channelID : The ID of a Channel.
  329. // content : The message to send.
  330. // NOTE, mention and tts parameters may be added in 2.x branch.
  331. func (s *Session) ChannelMessageSend(channelID string, content string) (st Message, err error) {
  332. // TOD: nonce string ?
  333. data := struct {
  334. Content string `json:"content"`
  335. Mentions []string `json:"mentions"`
  336. TTS bool `json:"tts"`
  337. }{content, nil, false}
  338. // If true, search for <@ID> tags and add those IDs to mention list.
  339. if s.AutoMention {
  340. re := regexp.MustCompile(`<@(\d+)>`)
  341. match := re.FindAllStringSubmatch(content, -1)
  342. mentions := make([]string, len(match))
  343. for i, m := range match {
  344. mentions[i] = m[1]
  345. }
  346. data.Mentions = mentions
  347. }
  348. // Send the message to the given channel
  349. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  350. err = json.Unmarshal(response, &st)
  351. return
  352. }
  353. // ChannelMessageEdit edits an existing message, replacing it entirely with
  354. // the given content.
  355. // channeld : The ID of a Channel
  356. // messageID : the ID of a Message
  357. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st Message, err error) {
  358. data := struct {
  359. Content string `json:"content"`
  360. }{content}
  361. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  362. err = json.Unmarshal(response, &st)
  363. return
  364. }
  365. // ChannelMessageDelete deletes a message from the Channel.
  366. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  367. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  368. return
  369. }
  370. // ChannelInvites returns an array of Invite structures for the given channel
  371. // channelID : The ID of a Channel
  372. func (s *Session) ChannelInvites(channelID string) (st []Invite, err error) {
  373. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  374. err = json.Unmarshal(body, &st)
  375. return
  376. }
  377. // ChannelInviteCreate creates a new invite for the given channel.
  378. // channelID : The ID of a Channel
  379. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  380. // and XkcdPass defined.
  381. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st Invite, err error) {
  382. data := struct {
  383. MaxAge int `json:"max_age"`
  384. MaxUses int `json:"max_uses"`
  385. Temporary bool `json:"temporary"`
  386. XKCDPass bool `json:"xkcdpass"`
  387. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  388. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  389. err = json.Unmarshal(body, &st)
  390. return
  391. }
  392. // ------------------------------------------------------------------------------------------------
  393. // Functions specific to Discord Invites
  394. // ------------------------------------------------------------------------------------------------
  395. // Invite returns an Invite structure of the given invite
  396. // inviteID : The invite code (or maybe xkcdpass?)
  397. func (s *Session) Invite(inviteID string) (st Invite, err error) {
  398. body, err := s.Request("GET", INVITE(inviteID), nil)
  399. err = json.Unmarshal(body, &st)
  400. return
  401. }
  402. // InviteDelete deletes an existing invite
  403. // inviteID : the code (or maybe xkcdpass?) of an invite
  404. func (s *Session) InviteDelete(inviteID string) (st Invite, err error) {
  405. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  406. err = json.Unmarshal(body, &st)
  407. return
  408. }
  409. // InviteAccept accepts an Invite to a Guild or Channel
  410. // inviteID : The invite code (or maybe xkcdpass?)
  411. func (s *Session) InviteAccept(inviteID string) (st Invite, err error) {
  412. body, err := s.Request("POST", INVITE(inviteID), nil)
  413. err = json.Unmarshal(body, &st)
  414. return
  415. }
  416. // ------------------------------------------------------------------------------------------------
  417. // Functions specific to Discord Voice
  418. // ------------------------------------------------------------------------------------------------
  419. // VoiceRegions returns the voice server regions
  420. func (s *Session) VoiceRegions() (st []VoiceRegion, err error) {
  421. body, err := s.Request("GET", VOICE_REGIONS, nil)
  422. err = json.Unmarshal(body, &st)
  423. return
  424. }
  425. // VoiceICE returns the voice server ICE information
  426. func (s *Session) VoiceICE() (st VoiceICE, err error) {
  427. body, err := s.Request("GET", VOICE_ICE, nil)
  428. err = json.Unmarshal(body, &st)
  429. return
  430. }
  431. // ------------------------------------------------------------------------------------------------
  432. // Functions specific to Discord Websockets
  433. // ------------------------------------------------------------------------------------------------
  434. // Gateway returns the a websocket Gateway address
  435. func (s *Session) Gateway() (gateway string, err error) {
  436. response, err := s.Request("GET", GATEWAY, nil)
  437. var temp map[string]interface{}
  438. err = json.Unmarshal(response, &temp)
  439. gateway = temp["url"].(string)
  440. return
  441. }