restapi.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /******************************************************************************
  2. * Discordgo by Bruce Marriner <bruce@sqls.net>
  3. * A Discord API for Golang.
  4. * See discord.go for more information.
  5. *
  6. * This file contains functions for interacting with the Discord HTTP REST API
  7. * at the lowest level.
  8. */
  9. package discordgo
  10. import (
  11. "bytes"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io/ioutil"
  16. "net/http"
  17. "time"
  18. )
  19. // Request makes a (GET/POST/?) Requests to Discord REST API.
  20. // All the other functions in this file use this function.
  21. func Request(session *Session, method, urlStr, body string) (response []byte, err error) {
  22. if session.Debug {
  23. fmt.Println("REQUEST :: " + method + " " + urlStr + "\n" + body)
  24. }
  25. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer([]byte(body)))
  26. if err != nil {
  27. return
  28. }
  29. // Not used on initial login..
  30. if session.Token != "" {
  31. req.Header.Set("authorization", session.Token)
  32. }
  33. req.Header.Set("Content-Type", "application/json")
  34. client := &http.Client{Timeout: (20 * time.Second)}
  35. resp, err := client.Do(req)
  36. if err != nil {
  37. return
  38. }
  39. response, err = ioutil.ReadAll(resp.Body)
  40. if err != nil {
  41. return
  42. }
  43. resp.Body.Close()
  44. if resp.StatusCode != 204 && resp.StatusCode != 200 {
  45. err = errors.New(fmt.Sprintf("StatusCode: %d, %s", resp.StatusCode, string(response)))
  46. return
  47. }
  48. if session.Debug {
  49. var prettyJSON bytes.Buffer
  50. error := json.Indent(&prettyJSON, response, "", "\t")
  51. if error != nil {
  52. fmt.Print("JSON parse error: ", error)
  53. return
  54. }
  55. fmt.Println("RESPONSE ::\n" + string(prettyJSON.Bytes()))
  56. }
  57. return
  58. }
  59. // Login asks the Discord server for an authentication token
  60. func Login(session *Session, email string, password string) (token string, err error) {
  61. var urlStr string = fmt.Sprintf("%s/%s", discordApi, "auth/login")
  62. response, err := Request(session, "POST", urlStr, fmt.Sprintf(`{"email":"%s", "password":"%s"}`, email, password))
  63. var temp map[string]interface{}
  64. err = json.Unmarshal(response, &temp)
  65. token = temp["token"].(string)
  66. return
  67. }
  68. // Returns the user details of the given userId
  69. // session : An active session connection to Discord
  70. // user : A user Id or name
  71. func Users(session *Session, userId string) (user User, err error) {
  72. body, err := Request(session, "GET", fmt.Sprintf("%s/users/%s", discordApi, userId), ``)
  73. err = json.Unmarshal(body, &user)
  74. return
  75. }
  76. // USERS could pull users channels, servers, settings and so forth too?
  77. // you know, pull all the data for the user. update the user strut
  78. // to house that data. Seems reasonable.
  79. // PrivateChannels returns an array of Channel structures for all private
  80. // channels for a user
  81. func PrivateChannels(session *Session, userId string) (channels []Channel, err error) {
  82. body, err := Request(session, "GET", fmt.Sprintf("%s/users/%s/channels", discordApi, userId), ``)
  83. err = json.Unmarshal(body, &channels)
  84. return
  85. }
  86. // Servers returns an array of Server structures for all servers for a user
  87. func Servers(session *Session, userId string) (servers []Server, err error) {
  88. body, err := Request(session, "GET", fmt.Sprintf("%s/users/%s/guilds", discordApi, userId), ``)
  89. err = json.Unmarshal(body, &servers)
  90. return
  91. }
  92. // add one to get specific server by ID, or enhance the above with an ID field.
  93. // GET http://discordapp.com/api/guilds/ID#
  94. // Members returns an array of Member structures for all members of a given
  95. // server.
  96. func Members(session *Session, serverId int) (members []Member, err error) {
  97. body, err := Request(session, "GET", fmt.Sprintf("%s/guilds/%d/members", discordApi, serverId), ``)
  98. err = json.Unmarshal(body, &members)
  99. return
  100. }
  101. // Channels returns an array of Channel structures for all channels of a given
  102. // server.
  103. func Channels(session *Session, serverId int) (channels []Channel, err error) {
  104. body, err := Request(session, "GET", fmt.Sprintf("%s/guilds/%d/channels", discordApi, serverId), ``)
  105. err = json.Unmarshal(body, &channels)
  106. return
  107. }
  108. // update above or add a way to get channel by ID. ChannelByName could be handy
  109. // too you know.
  110. // http://discordapp.com/api/channels/ID#
  111. // Messages returns an array of Message structures for messaages within a given
  112. // channel. limit, beforeId, and afterId can be used to control what messages
  113. // are returned.
  114. func Messages(session *Session, channelId int, limit int, beforeId int, afterId int) (messages []Message, err error) {
  115. var urlStr string
  116. if limit > 0 {
  117. urlStr = fmt.Sprintf("%s/channels/%d/messages?limit=%d", discordApi, channelId, limit)
  118. }
  119. if afterId > 0 {
  120. if urlStr != "" {
  121. urlStr = urlStr + fmt.Sprintf("&after=%d", afterId)
  122. } else {
  123. urlStr = fmt.Sprintf("%s/channels/%d/messages?after=%d", discordApi, channelId, afterId)
  124. }
  125. }
  126. if beforeId > 0 {
  127. if urlStr != "" {
  128. urlStr = urlStr + fmt.Sprintf("&before=%d", beforeId)
  129. } else {
  130. urlStr = fmt.Sprintf("%s/channels/%d/messages?after=%d", discordApi, channelId, beforeId)
  131. }
  132. }
  133. if urlStr == "" {
  134. urlStr = fmt.Sprintf("%s/channels/%d/messages", discordApi, channelId)
  135. }
  136. body, err := Request(session, "GET", urlStr, ``)
  137. err = json.Unmarshal(body, &messages)
  138. return
  139. }
  140. // SendMessage sends a message to the given channel.
  141. func SendMessage(session *Session, channelId int, content string) (message Message, err error) {
  142. var urlStr string = fmt.Sprintf("%s/channels/%d/messages", discordApi, channelId)
  143. response, err := Request(session, "POST", urlStr, fmt.Sprintf(`{"content":"%s"}`, content))
  144. err = json.Unmarshal(response, &message)
  145. return
  146. }
  147. // Returns the a websocket Gateway address
  148. // session : An active session connection to Discord
  149. func Gateway(session *Session) (gateway string, err error) {
  150. response, err := Request(session, "GET", fmt.Sprintf("%s/gateway", discordApi), ``)
  151. var temp map[string]interface{}
  152. err = json.Unmarshal(response, &temp)
  153. gateway = temp["url"].(string)
  154. return
  155. }
  156. // Close ends a session and logs out from the Discord REST API.
  157. // This does not seem to actually invalidate the token. So you can still
  158. // make API calls even after a Logout. So, it seems almost pointless to
  159. // even use.
  160. func Logout(session *Session) (err error) {
  161. urlStr := fmt.Sprintf("%s/auth/logout", discordApi)
  162. _, err = Request(session, "POST", urlStr, fmt.Sprintf(`{"token": "%s"}`, session.Token))
  163. return
  164. }