-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdispatch.go
More file actions
305 lines (274 loc) · 8.08 KB
/
Copy pathdispatch.go
File metadata and controls
305 lines (274 loc) · 8.08 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package strut
import (
"context"
"errors"
"fmt"
"log/slog"
"reflect"
"runtime/debug"
"time"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/handler"
"github.com/disgoorg/snowflake/v2"
)
// dispatch runs one invocation end to end. fill injects context menu targets
// after decoding and before the command runs.
func (f *Framework[D]) dispatch(inv *invocation[D], ce *handler.CommandEvent, kind Kind, fill func(*Event[D], reflect.Value) error) {
ctx, cancel := tokenContext(ce.Ctx, ce.CreatedAt())
defer cancel()
e := &Event[D]{
data: f.opts.Data,
ctx: ctx,
client: ce.Client(),
log: f.log,
kind: kind,
meta: inv.meta,
fw: f,
cmd: ce,
src: interactionSource[*handler.CommandEvent]{ce},
res: commandResponder{ce},
opener: commandResponder{ce},
}
var data discord.SlashCommandInteractionData
if d, ok := ce.Data.(discord.SlashCommandInteractionData); ok {
data = d
}
if err := f.run(inv, e, data, fill); err != nil {
f.report(inv, err)
}
}
func (f *Framework[D]) run(inv *invocation[D], e *Event[D], data discord.SlashCommandInteractionData, fill func(*Event[D], reflect.Value) error) (retErr *Error[D]) {
if !f.live.begin() {
return &Error[D]{Kind: ErrShuttingDown, Event: e}
}
defer f.live.done()
if !f.opts.DisableRecover {
defer func() {
if r := recover(); r != nil {
retErr = &Error[D]{
Kind: ErrCommandPanic, Event: e,
Err: fmt.Errorf("%v", r), Stack: debug.Stack(),
}
}
}()
}
if err := f.check(inv, e); err != nil {
return err
}
key := CooldownKey{Command: inv.meta.Name, User: e.Author().ID, Channel: e.ChannelID()}
if id := e.GuildID(); id != nil {
key.Guild = *id
}
if !inv.meta.ManualCooldown {
if left, hot := f.cool.Remaining(inv.cd, key); hot {
return &Error[D]{Kind: ErrCooldown, Event: e, Remaining: left}
}
}
v, err := inv.dec.decode(inv.proto, data)
if err != nil {
var argErr *ArgumentError
wrapped := &Error[D]{Kind: ErrArgumentParse, Event: e, Err: err}
if errors.As(err, &argErr) {
wrapped.Field, wrapped.Input = argErr.Field, argErr.Input
}
return wrapped
}
if err := fill(e, v); err != nil {
return &Error[D]{Kind: ErrArgumentParse, Event: e, Err: err}
}
if err := f.validate(v); err != nil {
return &Error[D]{Kind: ErrValidation, Event: e, Err: err}
}
if !inv.meta.ManualCooldown {
f.cool.Use(inv.cd, key)
}
// BroadcastTyping means "this will take a moment"; for an interaction the
// equivalent is acknowledging before the three second deadline.
if inv.meta.BroadcastTyping {
_ = e.Defer()
} else if stop := f.autoDefer(e); stop != nil {
defer stop()
}
if f.opts.PreCommand != nil {
f.opts.PreCommand(e)
}
if err := f.chain(v.Interface().(Runner[D]).Run)(e); err != nil {
var already *Error[D]
if errors.As(err, &already) {
return already
}
return &Error[D]{Kind: ErrCommandFailed, Event: e, Err: err}
}
if f.opts.PostCommand != nil {
f.opts.PostCommand(e)
}
return nil
}
// interactionTokenTTL is how long Discord accepts a response for an
// interaction. Past it a reply is refused, so work that outlives it is wasted.
const interactionTokenTTL = 15 * time.Minute
// tokenContext bounds an invocation by the life of its interaction token, so
// a slow call fails rather than completing into a response that can no longer
// be sent.
func tokenContext(ctx context.Context, created time.Time) (context.Context, context.CancelFunc) {
if ctx == nil {
ctx = context.Background()
}
if created.IsZero() {
return context.WithCancel(ctx)
}
return context.WithDeadline(ctx, created.Add(interactionTokenTTL))
}
// autoDefer acknowledges the interaction if the command is still working when
// the deadline approaches. It returns a function that cancels the watchdog,
// or nil when auto-defer is off.
func (f *Framework[D]) autoDefer(e *Event[D]) func() {
if f.opts.AutoDefer <= 0 || e.opener == nil {
return nil
}
t := time.AfterFunc(f.opts.AutoDefer, func() {
if !e.answered() {
_ = e.Defer()
}
})
return func() { t.Stop() }
}
// validate runs the caller's checks over a decoded command or modal. Failing
// here costs no cooldown, since the command never ran.
func (f *Framework[D]) validate(v reflect.Value) error {
if f.opts.Validate != nil {
if err := f.opts.Validate(v.Interface()); err != nil {
return err
}
}
if c, ok := v.Interface().(Validator); ok {
return c.Validate()
}
return nil
}
// check applies every gate before a command runs.
func (f *Framework[D]) check(inv *invocation[D], e *Event[D]) *Error[D] {
m := inv.meta
owner := f.isOwner(e.Author().ID)
if m.OwnersOnly && !owner {
return &Error[D]{Kind: ErrNotOwner, Event: e}
}
if f.opts.SkipChecksForOwners && owner {
return nil
}
inGuild := e.GuildID() != nil
if inGuild && f.opts.RequireCacheForGuildCheck && f.client != nil {
_, cached := f.client.Caches.Guild(*e.GuildID())
inGuild = cached
}
switch {
case m.GuildOnly && !inGuild:
return &Error[D]{Kind: ErrGuildOnly, Event: e}
case m.DMOnly && inGuild:
return &Error[D]{Kind: ErrDMOnly, Event: e}
}
if m.NSFWOnly && !e.src.NSFW() {
return &Error[D]{Kind: ErrNSFWOnly, Event: e}
}
if m.UserPerms != discord.PermissionsNone {
if mem := e.Member(); mem == nil || !mem.Permissions.Has(m.UserPerms) {
return &Error[D]{Kind: ErrMissingUserPerms, Event: e, Missing: m.UserPerms}
}
}
if m.BotPerms != discord.PermissionsNone {
if have := e.src.AppPerms(); have == nil || !have.Has(m.BotPerms) {
return &Error[D]{Kind: ErrMissingBotPerms, Event: e, Missing: m.BotPerms}
}
}
for _, c := range []Check[D]{f.opts.GlobalCheck, allowCheck(inv.allow)} {
if c == nil {
continue
}
ok, err := c(e)
if err != nil {
return &Error[D]{Kind: ErrCheckFailed, Event: e, Err: err}
}
if !ok {
return &Error[D]{Kind: ErrCheckFailed, Event: e}
}
}
return nil
}
// userTargetOf pairs the target user with its member, which exists only in a
// guild.
func userTargetOf[D any](data discord.UserCommandInteractionData, e *Event[D]) UserTarget {
t := UserTarget{User: data.TargetUser()}
if e.GuildID() != nil {
m := data.TargetMember()
t.Member = &m
}
return t
}
func allowCheck[D any](a Allower[D]) Check[D] {
if a == nil {
return nil
}
return a.Allow
}
func (f *Framework[D]) isOwner(id snowflake.ID) bool {
f.ownerMu.RLock()
defer f.ownerMu.RUnlock()
_, ok := f.owners[id]
return ok
}
// report routes an error to the command's handler, then the framework's, then
// the default.
func (f *Framework[D]) report(inv *invocation[D], err *Error[D]) {
switch {
// inv is nil for component and modal handlers, which belong to no command.
case inv != nil && inv.onError != nil:
inv.onError.OnError(err)
case f.opts.OnError != nil:
f.opts.OnError(err)
default:
DefaultErrorHandler(err)
}
}
// DefaultErrorHandler replies to the user for failures they caused and logs
// the rest.
func DefaultErrorHandler[D any](err *Error[D]) {
e := err.Event
if e == nil {
return
}
var msg string
switch err.Kind {
case ErrCooldown:
msg = fmt.Sprintf("Slow down, try again in %s.", err.Remaining.Round(time.Second))
case ErrMissingUserPerms:
msg = "You do not have permission to do that."
case ErrMissingBotPerms:
msg = "I am missing permissions to do that."
case ErrNotOwner:
msg = "That command is owner only."
case ErrGuildOnly:
msg = "That command only works in a server."
case ErrDMOnly:
msg = "That command only works in DMs."
case ErrNSFWOnly:
msg = "That command only works in an NSFW channel."
case ErrArgumentParse, ErrValidation:
msg = fmt.Sprintf("Invalid input: %v", err.Err)
case ErrShuttingDown:
msg = "The bot is restarting, try again shortly."
case ErrCheckFailed:
msg = "You cannot use that command here."
default:
e.Logger().Error("command failed",
slog.String("command", err.Event.meta.Name),
slog.String("kind", err.Kind.String()),
slog.Any("err", err.Err))
if len(err.Stack) > 0 {
e.Logger().Error("panic stack", slog.String("stack", string(err.Stack)))
}
msg = "Something went wrong."
}
if replyErr := e.Reply(Content(msg).AsEphemeral()); replyErr != nil {
e.Logger().Error("failed to report error to user", slog.Any("err", replyErr))
}
}