restapi.go 17 KB

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