restapi.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. "strconv"
  17. "time"
  18. )
  19. // Constants of known Discord API Endpoints
  20. // Please let me know if you know of any others.
  21. const (
  22. // Base URLS
  23. DISCORD = "http://discordapp.com"
  24. API = DISCORD + "/api"
  25. GUILDS = API + "/guilds" // Guilds()
  26. CHANNELS = API + "/channels" // Channels()
  27. USERS = API + "/users" // Users()
  28. LOGIN = API + "/auth/login" // Login()
  29. LOGOUT = API + "/auth/logout" // Logout()
  30. GATEWAY = API + "/gateway" // Gateway()
  31. // Authenticated User Info
  32. AU = USERS + "/@me"
  33. AU_SETTINGS = AU + "/settings" // Call Settings with @me
  34. AU_CHANNELS = AU + "/channels" // Call Channel with @me
  35. AU_GUILDS = AU + "/guilds" // Call Guilds with @me
  36. REGIONS = API + "/voice/regions" // VoiceRegions()
  37. ICE = API + "/voice/ice" // VoiceIce()
  38. // : guildId => `/guilds/${guildId}/channels`,
  39. // GUILD_CHANNELS: guildId => `/guilds/${guildId}/channels`,
  40. // TODO: Test below
  41. // AU_DEVICES = AU + "/devices"
  42. // AU_CONNECTIONS = AU + "/connections"
  43. // REGISTER = API + "/auth/register"
  44. // INVITE = API + "/invite"
  45. // TRACK = API + "/track"
  46. // SSO = API + "/sso"
  47. // VERIFY = API + "/auth/verify"
  48. // VERIFY_RESEND = API + "/auth/verify/resend"
  49. // FORGOT_PASSWORD = API + "/auth/forgot"
  50. // RESET_PASSWORD = API + "/auth/reset"
  51. // REPORT = API + "/report"
  52. // INTEGRATIONS = API + "/integrations"
  53. // Need a way to handle these here so the variables can be inserted.
  54. // Maybe defined as functions?
  55. /*
  56. INTEGRATIONS_JOIN: integrationId => `/integrations/${integrationId}/join`,
  57. AVATAR: (userId, hash) => `/users/${userId}/avatars/${hash}.jpg`,
  58. MESSAGES: channelId => `/channels/${channelId}/messages`,
  59. INSTANT_INVITES: channelId => `/channels/${channelId}/invites`,
  60. TYPING: channelId => `/channels/${channelId}/typing`,
  61. CHANNEL_PERMISSIONS: channelId => `/channels/${channelId}/permissions`,
  62. TUTORIAL: `/tutorial`,
  63. TUTORIAL_INDICATORS: `/tutorial/indicators`,
  64. USER_CHANNELS: userId => `/users/${userId}/channels`,
  65. GUILD_CHANNELS: guildId => `/guilds/${guildId}/channels`,
  66. GUILD_MEMBERS: guildId => `/guilds/${guildId}/members`,
  67. GUILD_INTEGRATIONS: guildId => `/guilds/${guildId}/integrations`,
  68. GUILD_BANS: guildId => `/guilds/${guildId}/bans`,
  69. GUILD_ROLES: guildId => `/guilds/${guildId}/roles`,
  70. GUILD_INSTANT_INVITES: guildId => `/guilds/${guildId}/invites`,
  71. GUILD_EMBED: guildId => `/guilds/${guildId}/embed`,
  72. GUILD_PRUNE: guildId => `/guilds/${guildId}/prune`,
  73. GUILD_ICON: (guildId, hash) => `/guilds/${guildId}/icons/${hash}.jpg`,
  74. */
  75. )
  76. // Almost like the constants above :) Dynamic Variables?
  77. var (
  78. GUILD_CHANNELS = func(i int) (s string) {
  79. s = GUILDS + "/" + strconv.Itoa(i) + "/channels"
  80. return
  81. }
  82. )
  83. // Request makes a (GET/POST/?) Requests to Discord REST API.
  84. // All the other functions in this file use this function.
  85. func (s *Session) Request(method, urlStr, body string) (response []byte, err error) {
  86. if s.Debug {
  87. fmt.Println("REQUEST :: " + method + " " + urlStr + "\n" + body)
  88. }
  89. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer([]byte(body)))
  90. if err != nil {
  91. return
  92. }
  93. // Not used on initial login..
  94. if s.Token != "" {
  95. req.Header.Set("authorization", s.Token)
  96. }
  97. req.Header.Set("Content-Type", "application/json")
  98. client := &http.Client{Timeout: (20 * time.Second)}
  99. resp, err := client.Do(req)
  100. if err != nil {
  101. return
  102. }
  103. response, err = ioutil.ReadAll(resp.Body)
  104. if err != nil {
  105. return
  106. }
  107. resp.Body.Close()
  108. if resp.StatusCode != 204 && resp.StatusCode != 200 {
  109. err = errors.New(fmt.Sprintf("StatusCode: %d, %s", resp.StatusCode, string(response)))
  110. return
  111. }
  112. if s.Debug {
  113. var prettyJSON bytes.Buffer
  114. error := json.Indent(&prettyJSON, response, "", "\t")
  115. if error != nil {
  116. fmt.Print("JSON parse error: ", error)
  117. return
  118. }
  119. fmt.Println("RESPONSE ::\n" + string(prettyJSON.Bytes()))
  120. }
  121. return
  122. }
  123. // Login asks the Discord server for an authentication token
  124. func (s *Session) Login(email string, password string) (token string, err error) {
  125. response, err := s.Request("POST", LOGIN, fmt.Sprintf(`{"email":"%s", "password":"%s"}`, email, password))
  126. var temp map[string]interface{}
  127. err = json.Unmarshal(response, &temp)
  128. token = temp["token"].(string)
  129. return
  130. }
  131. // Returns the user details of the given userId
  132. // session : An active session connection to Discord
  133. // user : A user Id or name
  134. func (s *Session) Users(userId string) (user User, err error) {
  135. body, err := s.Request("GET", fmt.Sprintf("%s/%s", USERS, userId), ``)
  136. err = json.Unmarshal(body, &user)
  137. return
  138. }
  139. func (s *Session) VoiceRegions() (vr []VoiceRegion, err error) {
  140. body, err := s.Request("GET", REGIONS, ``)
  141. err = json.Unmarshal(body, &vr)
  142. return
  143. }
  144. func (s *Session) VoiceIce() (ice VoiceIce, err error) {
  145. body, err := s.Request("GET", ICE, ``)
  146. err = json.Unmarshal(body, &ice)
  147. return
  148. }
  149. // Settings returns the settings for a given user
  150. // This seems to only return a result for "@me"
  151. func (s *Session) Settings(userId string) (settings Settings, err error) {
  152. body, err := s.Request("GET", fmt.Sprintf("%s/%s/settings", USERS, userId), ``)
  153. err = json.Unmarshal(body, &settings)
  154. return
  155. }
  156. // PrivateChannels returns an array of Channel structures for all private
  157. // channels for a user
  158. func (s *Session) PrivateChannels(userId string) (channels []Channel, err error) {
  159. body, err := s.Request("GET", fmt.Sprintf("%s/%s/channels", USERS, userId), ``)
  160. err = json.Unmarshal(body, &channels)
  161. return
  162. }
  163. // Guilds returns an array of Guild structures for all servers for a user
  164. func (s *Session) Guilds(userId string) (servers []Guild, err error) {
  165. body, err := s.Request("GET", fmt.Sprintf("%s/%s/guilds", USERS, userId), ``)
  166. err = json.Unmarshal(body, &servers)
  167. return
  168. }
  169. // add one to get specific server by ID, or enhance the above with an ID field.
  170. // GET http://discordapp.com/api/guilds/ID#
  171. // Members returns an array of Member structures for all members of a given
  172. // server.
  173. func (s *Session) Members(serverId int) (members []Member, err error) {
  174. body, err := s.Request("GET", fmt.Sprintf("%s/%d/members", GUILDS, serverId), ``)
  175. err = json.Unmarshal(body, &members)
  176. return
  177. }
  178. // Channels returns an array of Channel structures for all channels of a given
  179. // server.
  180. func (s *Session) Channels(Id int) (channels []Channel, err error) {
  181. // body, err := s.Request("GET", fmt.Sprintf("%s/%d/channels", GUILDS, serverId), ``)
  182. body, err := s.Request("GET", GUILD_CHANNELS(Id), ``)
  183. err = json.Unmarshal(body, &channels)
  184. return
  185. }
  186. // update above or add a way to get channel by ID. ChannelByName could be handy
  187. // too you know.
  188. // http://discordapp.com/api/channels/ID#
  189. // Messages returns an array of Message structures for messaages within a given
  190. // channel. limit, beforeId, and afterId can be used to control what messages
  191. // are returned.
  192. func (s *Session) Messages(channelId int, limit int, beforeId int, afterId int) (messages []Message, err error) {
  193. var urlStr string
  194. if limit > 0 {
  195. urlStr = fmt.Sprintf("%s/%d/messages?limit=%d", CHANNELS, channelId, limit)
  196. }
  197. if afterId > 0 {
  198. if urlStr != "" {
  199. urlStr = urlStr + fmt.Sprintf("&after=%d", afterId)
  200. } else {
  201. urlStr = fmt.Sprintf("%s/%d/messages?after=%d", CHANNELS, channelId, afterId)
  202. }
  203. }
  204. if beforeId > 0 {
  205. if urlStr != "" {
  206. urlStr = urlStr + fmt.Sprintf("&before=%d", beforeId)
  207. } else {
  208. urlStr = fmt.Sprintf("%s/%d/messages?after=%d", CHANNELS, channelId, beforeId)
  209. }
  210. }
  211. if urlStr == "" {
  212. urlStr = fmt.Sprintf("%s/%d/messages", CHANNELS, channelId)
  213. }
  214. body, err := s.Request("GET", urlStr, ``)
  215. err = json.Unmarshal(body, &messages)
  216. return
  217. }
  218. // SendMessage sends a message to the given channel.
  219. func (s *Session) SendMessage(channelId int, content string) (message Message, err error) {
  220. var urlStr string = fmt.Sprintf("%s/%d/messages", CHANNELS, channelId)
  221. response, err := s.Request("POST", urlStr, fmt.Sprintf(`{"content":"%s"}`, content))
  222. err = json.Unmarshal(response, &message)
  223. return
  224. }
  225. // Returns the a websocket Gateway address
  226. // session : An active session connection to Discord
  227. func (s *Session) Gateway() (gateway string, err error) {
  228. response, err := s.Request("GET", GATEWAY, ``)
  229. var temp map[string]interface{}
  230. err = json.Unmarshal(response, &temp)
  231. gateway = temp["url"].(string)
  232. return
  233. }
  234. // Close ends a session and logs out from the Discord REST API.
  235. // This does not seem to actually invalidate the token. So you can still
  236. // make API calls even after a Logout. So, it seems almost pointless to
  237. // even use.
  238. func (s *Session) Logout() (err error) {
  239. _, err = s.Request("POST", LOGOUT, fmt.Sprintf(`{"token": "%s"}`, s.Token))
  240. return
  241. }