-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
70 lines (58 loc) · 2.13 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package bot
import (
"encoding/json"
"net/http"
"time"
"github.com/andersfylling/disgord"
)
// This file contains some disgord helpers.
// MsgQueryBuilder returns a message query builder for the given message.
func MsgQueryBuilder(s disgord.Session, msg *disgord.Message) disgord.MessageQueryBuilder {
return s.Channel(msg.ChannelID).Message(msg.ID)
}
// SuppressEmbeds suppresses all embeds on the given message.
func SuppressEmbeds(session disgord.Session, msg *disgord.Message) (*disgord.Message, error) {
return MsgQueryBuilder(session, msg).Update().
Set("flags", msg.Flags|disgord.MessageFlagSupressEmbeds).Execute()
}
// UnsuppressEmbeds unsuppresses all embeds on the given message.
func UnsuppressEmbeds(session disgord.Session, msg *disgord.Message) (*disgord.Message, error) {
return MsgQueryBuilder(session, msg).Update().
Set("flags", msg.Flags&^disgord.MessageFlagSupressEmbeds).Execute()
}
// A disgord.HandlerCtrl that can be killed manually.
type manualCtrl struct {
dead bool
}
func (m *manualCtrl) kill() {
m.dead = true
}
func (m *manualCtrl) IsDead() bool { return m.dead }
func (m *manualCtrl) OnInsert(s disgord.Session) error { return nil }
func (m *manualCtrl) OnRemove(s disgord.Session) error { return nil }
func (m *manualCtrl) Update() {}
var _ disgord.HandlerCtrl = (*manualCtrl)(nil)
// https://discord.com/developers/docs/topics/rate-limits#exceeding-a-rate-limit-rate-limit-response-structure
type rateLimitResponse struct {
RetryAfter float64 `json:"retry_after"`
}
// Runs the given function and retries once if the returned error is caused by exceeding Discord's
// rate limit.
func retryOnRateLimit(do func() error) error {
err := do()
if err == nil {
return nil
}
errRest, ok := err.(*disgord.ErrRest)
if !ok || errRest.HTTPCode != http.StatusTooManyRequests {
return err
}
var r rateLimitResponse
// Depends on the response body being present as errRest.Suggestion
if json.Unmarshal([]byte(errRest.Suggestion), &r) != nil || r.RetryAfter <= 0 {
return err
}
wait := time.Duration(r.RetryAfter * float64(time.Second))
time.Sleep(wait)
return do()
}