client.go 5.4 KB

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