restapi.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. // ------------------------------------------------------------------------------------------------
  282. // Functions specific to Discord Channels
  283. // ------------------------------------------------------------------------------------------------
  284. // Channel returns a Channel strucutre of a specific Channel.
  285. // channelID : The ID of the Channel you want returend.
  286. func (s *Session) Channel(channelID string) (st Channel, err error) {
  287. body, err := s.Request("GET", CHANNEL(channelID), nil)
  288. err = json.Unmarshal(body, &st)
  289. return
  290. }
  291. // ChannelEdit edits the given channel
  292. // channelID : The ID of a Channel
  293. // name : The new name to assign the channel.
  294. func (s *Session) ChannelEdit(channelID, name string) (st Channel, err error) {
  295. data := struct {
  296. Name string `json:"name"`
  297. }{name}
  298. body, err := s.Request("PATCH", CHANNEL(channelID), data)
  299. err = json.Unmarshal(body, &st)
  300. return
  301. }
  302. // ChannelDelete deletes the given channel
  303. // channelID : The ID of a Channel
  304. func (s *Session) ChannelDelete(channelID string) (st Channel, err error) {
  305. body, err := s.Request("DELETE", CHANNEL(channelID), nil)
  306. err = json.Unmarshal(body, &st)
  307. return
  308. }
  309. // ChannelTyping broadcasts to all members that authenticated user is typing in
  310. // the given channel.
  311. // channelID : The ID of a Channel
  312. func (s *Session) ChannelTyping(channelID string) (err error) {
  313. _, err = s.Request("POST", CHANNEL_TYPING(channelID), nil)
  314. return
  315. }
  316. // ChannelMessages returns an array of Message structures for messaages within
  317. // a given channel.
  318. // channelID : The ID of a Channel.
  319. // limit : The number messages that can be returned.
  320. // beforeID : If provided all messages returned will be before given ID.
  321. // afterID : If provided all messages returned will be after given ID.
  322. func (s *Session) ChannelMessages(channelID string, limit int, beforeID int, afterID int) (st []Message, err error) {
  323. var urlStr string
  324. if limit > 0 {
  325. urlStr = fmt.Sprintf("?limit=%d", limit)
  326. }
  327. if afterID > 0 {
  328. if urlStr != "" {
  329. urlStr = urlStr + fmt.Sprintf("&after=%d", afterID)
  330. } else {
  331. urlStr = fmt.Sprintf("?after=%d", afterID)
  332. }
  333. }
  334. if beforeID > 0 {
  335. if urlStr != "" {
  336. urlStr = urlStr + fmt.Sprintf("&before=%d", beforeID)
  337. } else {
  338. urlStr = fmt.Sprintf("?before=%d", beforeID)
  339. }
  340. }
  341. body, err := s.Request("GET", CHANNEL_MESSAGES(channelID)+urlStr, nil)
  342. err = json.Unmarshal(body, &st)
  343. return
  344. }
  345. // ChannelMessageAck acknowledges and marks the given message as read
  346. // channeld : The ID of a Channel
  347. // messageID : the ID of a Message
  348. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  349. _, err = s.Request("POST", CHANNEL_MESSAGE_ACK(channelID, messageID), nil)
  350. return
  351. }
  352. // ChannelMessageSend sends a message to the given channel.
  353. // channelID : The ID of a Channel.
  354. // content : The message to send.
  355. // NOTE, mention and tts parameters may be added in 2.x branch.
  356. func (s *Session) ChannelMessageSend(channelID string, content string) (st Message, err error) {
  357. // TOD: nonce string ?
  358. data := struct {
  359. Content string `json:"content"`
  360. Mentions []string `json:"mentions"`
  361. TTS bool `json:"tts"`
  362. }{content, nil, false}
  363. // If true, search for <@ID> tags and add those IDs to mention list.
  364. if s.AutoMention {
  365. re := regexp.MustCompile(`<@(\d+)>`)
  366. match := re.FindAllStringSubmatch(content, -1)
  367. mentions := make([]string, len(match))
  368. for i, m := range match {
  369. mentions[i] = m[1]
  370. }
  371. data.Mentions = mentions
  372. }
  373. // Send the message to the given channel
  374. response, err := s.Request("POST", CHANNEL_MESSAGES(channelID), data)
  375. err = json.Unmarshal(response, &st)
  376. return
  377. }
  378. // ChannelMessageEdit edits an existing message, replacing it entirely with
  379. // the given content.
  380. // channeld : The ID of a Channel
  381. // messageID : the ID of a Message
  382. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st Message, err error) {
  383. data := struct {
  384. Content string `json:"content"`
  385. }{content}
  386. response, err := s.Request("PATCH", CHANNEL_MESSAGE(channelID, messageID), data)
  387. err = json.Unmarshal(response, &st)
  388. return
  389. }
  390. // ChannelMessageDelete deletes a message from the Channel.
  391. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  392. _, err = s.Request("DELETE", CHANNEL_MESSAGE(channelID, messageID), nil)
  393. return
  394. }
  395. // ChannelInvites returns an array of Invite structures for the given channel
  396. // channelID : The ID of a Channel
  397. func (s *Session) ChannelInvites(channelID string) (st []Invite, err error) {
  398. body, err := s.Request("GET", CHANNEL_INVITES(channelID), nil)
  399. err = json.Unmarshal(body, &st)
  400. return
  401. }
  402. // ChannelInviteCreate creates a new invite for the given channel.
  403. // channelID : The ID of a Channel
  404. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  405. // and XkcdPass defined.
  406. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st Invite, err error) {
  407. data := struct {
  408. MaxAge int `json:"max_age"`
  409. MaxUses int `json:"max_uses"`
  410. Temporary bool `json:"temporary"`
  411. XKCDPass bool `json:"xkcdpass"`
  412. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  413. body, err := s.Request("POST", CHANNEL_INVITES(channelID), data)
  414. err = json.Unmarshal(body, &st)
  415. return
  416. }
  417. // ------------------------------------------------------------------------------------------------
  418. // Functions specific to Discord Invites
  419. // ------------------------------------------------------------------------------------------------
  420. // Invite returns an Invite structure of the given invite
  421. // inviteID : The invite code (or maybe xkcdpass?)
  422. func (s *Session) Invite(inviteID string) (st Invite, err error) {
  423. body, err := s.Request("GET", INVITE(inviteID), nil)
  424. err = json.Unmarshal(body, &st)
  425. return
  426. }
  427. // InviteDelete deletes an existing invite
  428. // inviteID : the code (or maybe xkcdpass?) of an invite
  429. func (s *Session) InviteDelete(inviteID string) (st Invite, err error) {
  430. body, err := s.Request("DELETE", INVITE(inviteID), nil)
  431. err = json.Unmarshal(body, &st)
  432. return
  433. }
  434. // InviteAccept accepts an Invite to a Guild or Channel
  435. // inviteID : The invite code (or maybe xkcdpass?)
  436. func (s *Session) InviteAccept(inviteID string) (st Invite, err error) {
  437. body, err := s.Request("POST", INVITE(inviteID), nil)
  438. err = json.Unmarshal(body, &st)
  439. return
  440. }
  441. // ------------------------------------------------------------------------------------------------
  442. // Functions specific to Discord Voice
  443. // ------------------------------------------------------------------------------------------------
  444. // VoiceRegions returns the voice server regions
  445. func (s *Session) VoiceRegions() (st []VoiceRegion, err error) {
  446. body, err := s.Request("GET", VOICE_REGIONS, nil)
  447. err = json.Unmarshal(body, &st)
  448. return
  449. }
  450. // VoiceICE returns the voice server ICE information
  451. func (s *Session) VoiceICE() (st VoiceICE, err error) {
  452. body, err := s.Request("GET", VOICE_ICE, nil)
  453. err = json.Unmarshal(body, &st)
  454. return
  455. }
  456. // ------------------------------------------------------------------------------------------------
  457. // Functions specific to Discord Websockets
  458. // ------------------------------------------------------------------------------------------------
  459. // Gateway returns the a websocket Gateway address
  460. func (s *Session) Gateway() (gateway string, err error) {
  461. response, err := s.Request("GET", GATEWAY, nil)
  462. var temp map[string]interface{}
  463. err = json.Unmarshal(response, &temp)
  464. gateway = temp["url"].(string)
  465. return
  466. }