161 lines
4.6 KiB
Go
161 lines
4.6 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
// Discord is a minimal REST client. The bot polls the channel instead of
|
|
// holding a gateway websocket: no library, no public endpoint, and a few
|
|
// seconds of delay nobody notices in a one-person channel.
|
|
type Discord struct {
|
|
Token string
|
|
BaseURL string // overridden in tests
|
|
HTTP *http.Client
|
|
}
|
|
|
|
type Message struct {
|
|
ID string `json:"id"`
|
|
Content string `json:"content"`
|
|
Author struct {
|
|
ID string `json:"id"`
|
|
Bot bool `json:"bot"`
|
|
} `json:"author"`
|
|
Attachments []Attachment `json:"attachments"`
|
|
}
|
|
|
|
type Attachment struct {
|
|
URL string `json:"url"`
|
|
Filename string `json:"filename"`
|
|
Size int64 `json:"size"`
|
|
ContentType string `json:"content_type"`
|
|
}
|
|
|
|
func newDiscord(token string) *Discord {
|
|
return &Discord{Token: token, BaseURL: "https://discord.com/api/v10", HTTP: &http.Client{Timeout: 30 * time.Second}}
|
|
}
|
|
|
|
// do sends one request, waiting out a rate limit once. out may be nil.
|
|
func (d *Discord) do(ctx context.Context, method, path, contentType string, body []byte, out any) error {
|
|
for attempt := range 2 {
|
|
req, err := http.NewRequestWithContext(ctx, method, d.BaseURL+path, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Authorization", "Bot "+d.Token)
|
|
req.Header.Set("User-Agent", "DiscordBot (https://git.54l1m.io, 0.1) jobhunt")
|
|
if contentType != "" {
|
|
req.Header.Set("Content-Type", contentType)
|
|
}
|
|
resp, err := d.HTTP.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
data, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
|
resp.Body.Close()
|
|
|
|
if resp.StatusCode == http.StatusTooManyRequests && attempt == 0 {
|
|
var rl struct {
|
|
RetryAfter float64 `json:"retry_after"`
|
|
}
|
|
_ = json.Unmarshal(data, &rl)
|
|
wait := time.Duration(max(rl.RetryAfter, 1) * float64(time.Second))
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-time.After(min(wait, 30*time.Second)):
|
|
}
|
|
continue
|
|
}
|
|
if resp.StatusCode >= 300 {
|
|
return fmt.Errorf("discord %s %s: HTTP %d: %s", method, path, resp.StatusCode, truncate(string(data), 200))
|
|
}
|
|
if out != nil {
|
|
return json.Unmarshal(data, out)
|
|
}
|
|
return nil
|
|
}
|
|
return fmt.Errorf("discord %s %s: still rate limited", method, path)
|
|
}
|
|
|
|
func snowflake(id string) uint64 {
|
|
n, _ := strconv.ParseUint(id, 10, 64)
|
|
return n
|
|
}
|
|
|
|
// MessagesAfter returns messages newer than the given ID, oldest first. An
|
|
// empty ID returns only the newest message, which is how the bot finds its
|
|
// starting point without replaying the channel's history.
|
|
func (d *Discord) MessagesAfter(ctx context.Context, channel, after string) ([]Message, error) {
|
|
q := url.Values{"limit": {"1"}}
|
|
if after != "" {
|
|
q = url.Values{"limit": {"50"}, "after": {after}}
|
|
}
|
|
var msgs []Message
|
|
if err := d.do(ctx, http.MethodGet, "/channels/"+channel+"/messages?"+q.Encode(), "", nil, &msgs); err != nil {
|
|
return nil, err
|
|
}
|
|
sort.Slice(msgs, func(i, j int) bool { return snowflake(msgs[i].ID) < snowflake(msgs[j].ID) })
|
|
return msgs, nil
|
|
}
|
|
|
|
// Reply posts a message answering replyTo, optionally with one file attached.
|
|
// Mentions are disabled so nothing in a posting can ping anyone.
|
|
func (d *Discord) Reply(ctx context.Context, channel, replyTo, content, fileName string, file []byte) error {
|
|
payload := map[string]any{
|
|
"content": truncateRunes(content, 1990),
|
|
"allowed_mentions": map[string]any{"parse": []string{}},
|
|
}
|
|
if replyTo != "" {
|
|
payload["message_reference"] = map[string]any{"message_id": replyTo, "fail_if_not_exists": false}
|
|
}
|
|
js, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
path := "/channels/" + channel + "/messages"
|
|
if fileName == "" {
|
|
return d.do(ctx, http.MethodPost, path, "application/json", js, nil)
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
mw := multipart.NewWriter(&buf)
|
|
if err := mw.WriteField("payload_json", string(js)); err != nil {
|
|
return err
|
|
}
|
|
part, err := mw.CreateFormFile("files[0]", fileName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := part.Write(file); err != nil {
|
|
return err
|
|
}
|
|
if err := mw.Close(); err != nil {
|
|
return err
|
|
}
|
|
return d.do(ctx, http.MethodPost, path, mw.FormDataContentType(), buf.Bytes(), nil)
|
|
}
|
|
|
|
// React adds an emoji reaction as a cheap progress signal.
|
|
func (d *Discord) React(ctx context.Context, channel, message, emoji string) error {
|
|
path := "/channels/" + channel + "/messages/" + message + "/reactions/" + url.PathEscape(emoji) + "/@me"
|
|
return d.do(ctx, http.MethodPut, path, "", nil, nil)
|
|
}
|
|
|
|
func truncateRunes(s string, n int) string {
|
|
r := []rune(s)
|
|
if len(r) <= n {
|
|
return s
|
|
}
|
|
return string(r[:n-1]) + "…"
|
|
}
|