restapi.go 10 KB

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