restapi.go 6.1 KB

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