2020-01-15 04:56:50 +00:00
|
|
|
// Package api provides an interface to interact with the Discord REST API. It
|
|
|
|
// handles rate limiting, as well as authorizing and more.
|
2020-01-02 05:39:52 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2020-01-08 18:43:15 +00:00
|
|
|
"github.com/diamondburned/arikawa/api/rate"
|
2020-04-09 02:28:40 +00:00
|
|
|
"github.com/diamondburned/arikawa/utils/httputil"
|
2020-04-19 21:53:53 +00:00
|
|
|
"github.com/diamondburned/arikawa/utils/httputil/httpdriver"
|
2020-01-02 05:39:52 +00:00
|
|
|
)
|
|
|
|
|
2020-04-19 16:30:12 +00:00
|
|
|
var (
|
2020-02-09 20:54:16 +00:00
|
|
|
BaseEndpoint = "https://discordapp.com"
|
2020-01-02 05:39:52 +00:00
|
|
|
APIVersion = "6"
|
2020-02-09 20:54:16 +00:00
|
|
|
APIPath = "/api/v" + APIVersion
|
2020-01-02 05:39:52 +00:00
|
|
|
|
2020-02-09 20:54:16 +00:00
|
|
|
Endpoint = BaseEndpoint + APIPath + "/"
|
2020-01-02 05:39:52 +00:00
|
|
|
EndpointGateway = Endpoint + "gateway"
|
|
|
|
EndpointGatewayBot = EndpointGateway + "/bot"
|
|
|
|
)
|
|
|
|
|
|
|
|
var UserAgent = "DiscordBot (https://github.com/diamondburned/arikawa, v0.0.1)"
|
|
|
|
|
|
|
|
type Client struct {
|
2020-04-19 21:53:53 +00:00
|
|
|
*httputil.Client
|
2020-01-08 18:43:15 +00:00
|
|
|
Limiter *rate.Limiter
|
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
Token string
|
|
|
|
UserAgent string
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewClient(token string) *Client {
|
2020-04-19 21:53:53 +00:00
|
|
|
return NewCustomClient(token, httputil.NewClient())
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCustomClient(token string, httpClient *httputil.Client) *Client {
|
2020-01-02 05:39:52 +00:00
|
|
|
cli := &Client{
|
2020-04-19 21:53:53 +00:00
|
|
|
Client: httpClient,
|
|
|
|
Limiter: rate.NewLimiter(APIPath),
|
|
|
|
Token: token,
|
|
|
|
UserAgent: UserAgent,
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
cli.DefaultOptions = []httputil.RequestOption{
|
|
|
|
func(r httpdriver.Request) error {
|
|
|
|
r.AddHeader(http.Header{
|
|
|
|
"Authorization": {cli.Token},
|
|
|
|
"User-Agent": {cli.UserAgent},
|
|
|
|
"X-RateLimit-Precision": {"millisecond"},
|
|
|
|
})
|
|
|
|
|
|
|
|
// Rate limit stuff
|
|
|
|
return cli.Limiter.Acquire(r.GetContext(), r.GetPath())
|
|
|
|
},
|
2020-01-08 18:43:15 +00:00
|
|
|
}
|
2020-04-19 21:53:53 +00:00
|
|
|
cli.OnResponse = func(r httpdriver.Request, resp httpdriver.Response) error {
|
|
|
|
return cli.Limiter.Release(r.GetPath(), httpdriver.OptHeader(resp))
|
2020-01-02 05:39:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return cli
|
|
|
|
}
|