restapi.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /******************************************************************************
  2. * A Discord API for Golang.
  3. * See discord.go for more information.
  4. *
  5. * This file contains functions for interacting with the Discord HTTP REST API
  6. * at the lowest level.
  7. */
  8. package discordgo
  9. import (
  10. "bytes"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io/ioutil"
  15. "net/http"
  16. "time"
  17. )
  18. // Constants of all known Discord API Endpoints
  19. // Please let me know if you know of any others.
  20. const (
  21. DISCORD = "http://discordapp.com"
  22. API = DISCORD + "/api/"
  23. GUILDS = API + "guilds/"
  24. CHANNELS = API + "channels/"
  25. USERS = API + "users/"
  26. GATEWAY = API + "gateway"
  27. AUTH = API + "auth/"
  28. LOGIN = AUTH + "login"
  29. LOGOUT = AUTH + "logout"
  30. VERIFY = AUTH + "verify"
  31. VERIFY_RESEND = AUTH + "verify/resend"
  32. FORGOT_PASSWORD = AUTH + "forgot"
  33. RESET_PASSWORD = AUTH + "reset"
  34. REGISTER = AUTH + "register"
  35. VOICE = API + "/voice/"
  36. REGIONS = VOICE + "regions"
  37. ICE = VOICE + "ice"
  38. TUTORIAL = API + "tutorial/"
  39. TUTORIAL_INDICATORS = TUTORIAL + "indicators"
  40. INVITE = API + "invite"
  41. TRACK = API + "track"
  42. SSO = API + "sso"
  43. REPORT = API + "report"
  44. INTEGRATIONS = API + "integrations"
  45. )
  46. // Almost like the constants above :) Except can't be constants
  47. var (
  48. USER = func(userId string) string { return USERS + userId }
  49. USER_AVATAR = func(userId, hash string) string { return USERS + userId + "/avatars/" + hash + ".jpg" }
  50. USER_SETTINGS = func(userId string) string { return USERS + userId + "/settings" }
  51. USER_GUILDS = func(userId string) string { return USERS + userId + "/guilds" }
  52. USER_CHANNELS = func(userId string) string { return USERS + userId + "/channels" }
  53. USER_DEVICES = func(userId string) string { return USERS + userId + "/devices" }
  54. USER_CONNECTIONS = func(userId string) string { return USERS + userId + "/connections" }
  55. GUILD = func(guildId string) string { return GUILDS + guildId }
  56. GUILD_CHANNELS = func(guildId string) string { return GUILDS + guildId + "/channels" }
  57. GUILD_MEMBERS = func(guildId string) string { return GUILDS + guildId + "/members" }
  58. GUILD_INTEGRATIONS = func(guildId string) string { return GUILDS + guildId + "/integrations" }
  59. GUILD_BANS = func(guildId string) string { return GUILDS + guildId + "/bans" }
  60. GUILD_ROLES = func(guildId string) string { return GUILDS + guildId + "/roles" }
  61. GUILD_INVITES = func(guildId string) string { return GUILDS + guildId + "/invites" }
  62. GUILD_EMBED = func(guildId string) string { return GUILDS + guildId + "/embed" }
  63. GUILD_PRUNE = func(guildId string) string { return GUILDS + guildId + "/prune" }
  64. GUILD_ICON = func(guildId, hash string) string { return GUILDS + guildId + "/icons/" + hash + ".jpg" }
  65. CHANNEL = func(channelId string) string { return CHANNELS + channelId }
  66. CHANNEL_MESSAGES = func(channelId string) string { return CHANNELS + channelId + "/messages" }
  67. CHANNEL_PERMISSIONS = func(channelId string) string { return CHANNELS + channelId + "/permissions" }
  68. CHANNEL_INVITES = func(channelId string) string { return CHANNELS + channelId + "/invites" }
  69. CHANNEL_TYPING = func(channelId string) string { return CHANNELS + channelId + "/typing" }
  70. INTEGRATIONS_JOIN = func(intId string) string { return API + "integrations/" + intId + "/join" }
  71. )
  72. // Request makes a (GET/POST/?) Requests to Discord REST API.
  73. // All the other Discord REST Calls in this file use this function.
  74. func (s *Session) Request(method, urlStr, body string) (response []byte, err error) {
  75. if s.Debug {
  76. fmt.Println("REQUEST :: " + method + " " + urlStr + "\n" + body)
  77. }
  78. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer([]byte(body)))
  79. if err != nil {
  80. return
  81. }
  82. // Not used on initial login..
  83. if s.Token != "" {
  84. req.Header.Set("authorization", s.Token)
  85. }
  86. req.Header.Set("Content-Type", "application/json")
  87. client := &http.Client{Timeout: (20 * time.Second)}
  88. resp, err := client.Do(req)
  89. if err != nil {
  90. return
  91. }
  92. response, err = ioutil.ReadAll(resp.Body)
  93. if err != nil {
  94. return
  95. }
  96. resp.Body.Close()
  97. if resp.StatusCode != 204 && resp.StatusCode != 200 {
  98. err = errors.New(fmt.Sprintf("StatusCode: %d, %s", resp.StatusCode, string(response)))
  99. return
  100. }
  101. if s.Debug {
  102. printJSON(response)
  103. }
  104. return
  105. }
  106. /***************************************************************************************************
  107. * Functions specific to this session.
  108. */
  109. // Login asks the Discord server for an authentication token
  110. func (s *Session) Login(email string, password string) (token string, err error) {
  111. response, err := s.Request("POST", LOGIN, fmt.Sprintf(`{"email":"%s", "password":"%s"}`, email, password))
  112. var temp map[string]interface{}
  113. err = json.Unmarshal(response, &temp)
  114. token = temp["token"].(string)
  115. return
  116. }
  117. // Logout sends a logout request to Discord.
  118. // This does not seem to actually invalidate the token. So you can still
  119. // make API calls even after a Logout. So, it seems almost pointless to
  120. // even use.
  121. func (s *Session) Logout() (err error) {
  122. _, err = s.Request("POST", LOGOUT, fmt.Sprintf(`{"token": "%s"}`, s.Token))
  123. return
  124. }
  125. // Gateway returns the a websocket Gateway address
  126. func (s *Session) Gateway() (gateway string, err error) {
  127. response, err := s.Request("GET", GATEWAY, ``)
  128. var temp map[string]interface{}
  129. err = json.Unmarshal(response, &temp)
  130. gateway = temp["url"].(string)
  131. return
  132. }
  133. // VoiceRegions returns the voice server regions
  134. func (s *Session) VoiceRegions() (st []VoiceRegion, err error) {
  135. body, err := s.Request("GET", REGIONS, ``)
  136. err = json.Unmarshal(body, &st)
  137. return
  138. }
  139. // VoiceIce returns the voice server ICE information
  140. func (s *Session) VoiceIce() (st VoiceIce, err error) {
  141. body, err := s.Request("GET", ICE, ``)
  142. err = json.Unmarshal(body, &st)
  143. return
  144. }
  145. /***************************************************************************************************
  146. * Functions related to a specific user
  147. */
  148. // User returns the user details of the given userId
  149. // userId : A user Id or "@me" which is a shortcut of current user ID
  150. func (s *Session) User(userId string) (st User, err error) {
  151. body, err := s.Request("GET", USER(userId), ``)
  152. err = json.Unmarshal(body, &st)
  153. return
  154. }
  155. // UserSettings returns the settings for a given user
  156. // userId : A user Id or "@me" which is a shortcut of current user ID
  157. // This seems to only return a result for "@me"
  158. func (s *Session) UserSettings(userId string) (st Settings, err error) {
  159. body, err := s.Request("GET", USER_SETTINGS(userId), ``)
  160. err = json.Unmarshal(body, &st)
  161. return
  162. }
  163. // UserChannels returns an array of Channel structures for all private
  164. // channels for a user
  165. // userId : A user Id or "@me" which is a shortcut of current user ID
  166. func (s *Session) UserChannels(userId string) (st []Channel, err error) {
  167. body, err := s.Request("GET", USER_CHANNELS(userId), ``)
  168. err = json.Unmarshal(body, &st)
  169. return
  170. }
  171. // UserGuilds returns an array of Guild structures for all guilds for a given user
  172. // userId : A user Id or "@me" which is a shortcut of current user ID
  173. func (s *Session) UserGuilds(userId string) (st []Guild, err error) {
  174. body, err := s.Request("GET", USER_GUILDS(userId), ``)
  175. err = json.Unmarshal(body, &st)
  176. return
  177. }
  178. /***************************************************************************************************
  179. * Functions related to a specific guild
  180. */
  181. // Guild returns a Guild structure of a specific Guild.
  182. // guildId : The ID of the Guild you want returend.
  183. func (s *Session) Guild(guildId string) (st []Guild, err error) {
  184. body, err := s.Request("GET", GUILD(guildId), ``)
  185. err = json.Unmarshal(body, &st)
  186. return
  187. }
  188. // GuildMembers returns an array of Member structures for all members of a
  189. // given guild.
  190. // guildId : The ID of a Guild.
  191. func (s *Session) GuildMembers(guildId string) (st []Member, err error) {
  192. body, err := s.Request("GET", GUILD_MEMBERS(guildId), ``)
  193. err = json.Unmarshal(body, &st)
  194. return
  195. }
  196. // GuildChannels returns an array of Channel structures for all channels of a
  197. // given guild.
  198. // guildId : The ID of a Guild.
  199. func (s *Session) GuildChannels(guildId string) (st []Channel, err error) {
  200. body, err := s.Request("GET", GUILD_CHANNELS(guildId), ``)
  201. err = json.Unmarshal(body, &st)
  202. return
  203. }
  204. /***************************************************************************************************
  205. * Functions related to a specific channel
  206. */
  207. // Channel returns a Channel strucutre of a specific Channel.
  208. // channelId : The ID of the Channel you want returend.
  209. func (s *Session) Channel(channelId string) (st Channel, err error) {
  210. body, err := s.Request("GET", CHANNEL(channelId), ``)
  211. err = json.Unmarshal(body, &st)
  212. return
  213. }
  214. // ChannelMessages returns an array of Message structures for messaages within
  215. // a given channel.
  216. // channelId : The ID of a Channel.
  217. // limit : The number messages that can be returned.
  218. // beforeId : If provided all messages returned will be before given ID.
  219. // afterId : If provided all messages returned will be after given ID.
  220. func (s *Session) ChannelMessages(channelId string, limit int, beforeId int, afterId int) (st []Message, err error) {
  221. var urlStr string = ""
  222. if limit > 0 {
  223. urlStr = fmt.Sprintf("?limit=%d", limit)
  224. }
  225. if afterId > 0 {
  226. if urlStr != "" {
  227. urlStr = urlStr + fmt.Sprintf("&after=%d", afterId)
  228. } else {
  229. urlStr = fmt.Sprintf("?after=%d", afterId)
  230. }
  231. }
  232. if beforeId > 0 {
  233. if urlStr != "" {
  234. urlStr = urlStr + fmt.Sprintf("&before=%d", beforeId)
  235. } else {
  236. urlStr = fmt.Sprintf("?before=%d", beforeId)
  237. }
  238. }
  239. body, err := s.Request("GET", CHANNEL_MESSAGES(channelId)+urlStr, ``)
  240. err = json.Unmarshal(body, &st)
  241. return
  242. }
  243. // ChannelMessageSend sends a message to the given channel.
  244. // channelId : The ID of a Channel.
  245. // content : The message to send.
  246. func (s *Session) ChannelMessageSend(channelId string, content string) (st Message, err error) {
  247. response, err := s.Request("POST", CHANNEL_MESSAGES(channelId), fmt.Sprintf(`{"content":"%s"}`, content))
  248. err = json.Unmarshal(response, &st)
  249. return
  250. }