restapi.go 17 KB

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