-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
607 lines (508 loc) · 16.3 KB
/
context.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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package ken
import (
"github.com/bwmarrin/discordgo"
"github.com/rs/xid"
"github.com/zekrotja/safepool"
)
// ContextResponder defines the implementation of an
// interaction context with functionalities to respond
// to the interaction, to set the ephemeral state and
// to retrieve the nested session and event.
type ContextResponder interface {
// Respond to an interaction event with the given
// interaction response payload.
//
// When an interaction has already been responded to,
// the response will be edited instead on execution.
Respond(r *discordgo.InteractionResponse) (err error)
// RespondMessage is shorthand for Respond with a simple
// message as response content.
RespondMessage(message string) (err error)
// RespondEmbed is shorthand for Respond with an
// embed payload as passed.
RespondEmbed(emb *discordgo.MessageEmbed) (err error)
// RespondError is shorthand for RespondEmbed with an
// error embed as message with the passed content and
// title.
RespondError(content, title string) (err error)
// FollowUp creates a follow up message to the
// interaction event and returns a FollowUpMessage
// object containing the created message as well as
// an error instance, if an error occurred.
//
// This way it allows to be chained in one call with
// subsequent FollowUpMessage method calls.
FollowUp(wait bool, data *discordgo.WebhookParams) (fumb *FollowUpMessageBuilder)
// FollowUpEmbed is shorthand for FollowUp with a simple
// message as response content.
FollowUpMessage(message string) (fumb *FollowUpMessageBuilder)
// FollowUpEmbed is shorthand for FollowUp with an
// embed payload as passed.
FollowUpEmbed(emb *discordgo.MessageEmbed) (fumb *FollowUpMessageBuilder)
// FollowUpError is shorthand for FollowUpEmbed with an
// error embed as message with the passed content and
// title.
FollowUpError(content, title string) (fumb *FollowUpMessageBuilder)
// Defer is shorthand for Respond with an InteractionResponse
// of the type InteractionResponseDeferredChannelMessageWithSource.
//
// It should be used when the interaction response can not be
// instantly returned.
Defer() (err error)
// GetEphemeral returns the current emphemeral state
// of the command invokation.
GetEphemeral() bool
// SetEphemeral sets the emphemeral state of the command
// invokation.
//
// Ephemeral can be set to true which will
// send all subsequent command responses
// only to the user which invoked the command.
SetEphemeral(v bool)
// GetSession returns the current Discordgo session instance.
GetSession() *discordgo.Session
// GetEvent returns the InteractionCreate event instance which
// invoked the interaction command.
GetEvent() *discordgo.InteractionCreate
// User returns the User object of the executor either from
// the events User object or from the events Member object.
User() (u *discordgo.User)
}
// Context defines the implementation of an interaction
// command context passed to the command handler.
type Context interface {
ContextResponder
ObjectProvider
safepool.ResetState
// Channel tries to fetch the channel object from the contained
// channel ID using the specified state manager.
Channel() (*discordgo.Channel, error)
// Channel tries to fetch the guild object from the contained
// guild ID using the specified state manager.
Guild() (*discordgo.Guild, error)
// Options returns the application command data options
// with additional functionality methods.
Options() CommandOptions
// SlashCommand returns the contexts Command as a
// SlashCommand interface.
SlashCommand() (cmd SlashCommand, ok bool)
// UserCommand returns the contexts Command as a
// UserCommand interface.
UserCommand() (cmd UserCommand, ok bool)
// MessageCommand returns the contexts Command as a
// MessageCommand interface.
MessageCommand() (cmd MessageCommand, ok bool)
// HandleSubCommands takes a list of sub command handles.
// When the command is executed, the options are scanned
// for the sib command calls by their names. If one of
// the registered sub commands has been called, the specified
// handler function is executed.
//
// If the call occured, the passed handler function is
// getting passed the scoped sub command Ctx.
//
// The SubCommandCtx passed must not be stored or used
// after command execution.
HandleSubCommands(handler ...CommandHandler) (err error)
// GetKen returns the root instance of Ken.
GetKen() *Ken
// GetCommand returns the command instance called.
GetCommand() Command
}
// ctxResponder provides functionailities to respond
// to an interaction.
type ctxResponder struct {
responded bool
ken *Ken
session *discordgo.Session
event *discordgo.InteractionCreate
ephemeral bool
}
var _ ContextResponder = (*ctxResponder)(nil)
func (c *ctxResponder) Respond(r *discordgo.InteractionResponse) (err error) {
if r.Data == nil {
r.Data = new(discordgo.InteractionResponseData)
}
r.Data.Flags = c.messageFlags(r.Data.Flags)
if c.responded {
if r == nil || r.Data == nil {
return
}
_, err = c.GetSession().InteractionResponseEdit(c.event.Interaction, &discordgo.WebhookEdit{
Content: &r.Data.Content,
Embeds: &r.Data.Embeds,
Components: &r.Data.Components,
Files: r.Data.Files,
AllowedMentions: r.Data.AllowedMentions,
})
} else {
err = c.GetSession().InteractionRespond(c.event.Interaction, r)
c.responded = err == nil
}
return
}
func (c *ctxResponder) RespondMessage(message string) (err error) {
return c.Respond(&discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: message,
},
})
}
func (c *ctxResponder) RespondEmbed(emb *discordgo.MessageEmbed) (err error) {
if emb.Color <= 0 {
emb.Color = c.ken.opt.EmbedColors.Default
}
return c.Respond(&discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
emb,
},
},
})
}
func (c *ctxResponder) RespondError(content, title string) (err error) {
return c.RespondEmbed(&discordgo.MessageEmbed{
Description: content,
Title: title,
Color: c.ken.opt.EmbedColors.Error,
})
}
func (c *ctxResponder) FollowUp(wait bool, data *discordgo.WebhookParams) (fumb *FollowUpMessageBuilder) {
data.Flags = c.messageFlags(data.Flags)
return &FollowUpMessageBuilder{
ken: c.ken,
i: c.event.Interaction,
data: data,
wait: wait,
}
}
func (c *ctxResponder) FollowUpMessage(message string) (fumb *FollowUpMessageBuilder) {
return c.FollowUp(true, &discordgo.WebhookParams{
Content: message,
})
}
func (c *ctxResponder) FollowUpEmbed(emb *discordgo.MessageEmbed) (fumb *FollowUpMessageBuilder) {
if emb.Color <= 0 {
emb.Color = c.ken.opt.EmbedColors.Default
}
return c.FollowUp(true, &discordgo.WebhookParams{
Embeds: []*discordgo.MessageEmbed{
emb,
},
})
}
func (c *ctxResponder) FollowUpError(content, title string) (fumb *FollowUpMessageBuilder) {
return c.FollowUpEmbed(&discordgo.MessageEmbed{
Description: content,
Title: title,
Color: c.ken.opt.EmbedColors.Error,
})
}
func (c *ctxResponder) Defer() (err error) {
err = c.Respond(&discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
return
}
func (c *ctxResponder) GetEphemeral() bool {
return c.ephemeral
}
func (c *ctxResponder) SetEphemeral(v bool) {
c.ephemeral = v
}
func (c *ctxResponder) GetSession() *discordgo.Session {
return c.session
}
func (c *ctxResponder) GetEvent() *discordgo.InteractionCreate {
return c.event
}
func (c *ctxResponder) messageFlags(p discordgo.MessageFlags) (f discordgo.MessageFlags) {
f = p
if c.ephemeral {
f |= discordgo.MessageFlagsEphemeral
}
return
}
// User returns the User object of the executor either from
// the events User object or from the events Member object.
func (c *ctxResponder) User() (u *discordgo.User) {
u = c.event.User
if u == nil && c.event.Member != nil {
u = c.event.Member.User
}
return
}
// Ctx holds the invokation context of
// a command.
//
// The Ctx must not be stored or used
// after command execution.
type Ctx struct {
ObjectMap
ctxResponder
// Command provides the called command instance.
Command Command
}
var _ Context = (*Ctx)(nil)
var _ safepool.ResetState = (*Ctx)(nil)
func newCtx() *Ctx {
return &Ctx{
ObjectMap: make(simpleObjectMap),
}
}
// Get either returns an instance from the internal object map -
// if existent. Otherwise, the object is looked up in the specified
// dependency provider, if available. When no object was found in
// either of both maps, nil is returned.
func (c *Ctx) Get(key string) (v interface{}) {
if v = c.ObjectMap.Get(key); v == nil && c.ken.opt.DependencyProvider != nil {
v = c.ken.opt.DependencyProvider.Get(key)
}
return
}
// Channel tries to fetch the channel object from the contained
// channel ID using the specified state manager.
func (c *Ctx) Channel() (*discordgo.Channel, error) {
return c.ken.opt.State.Channel(c.session, c.event.ChannelID)
}
// Guild tries to fetch the guild object from the contained
// guild ID using the specified state manager.
func (c *Ctx) Guild() (*discordgo.Guild, error) {
return c.ken.opt.State.Guild(c.session, c.event.GuildID)
}
// Options returns the application command data options
// with additional functionality methods.
func (c *Ctx) Options() CommandOptions {
return c.event.ApplicationCommandData().Options
}
// SlashCommand returns the contexts Command as a
// SlashCommand interface.
func (c *Ctx) SlashCommand() (cmd SlashCommand, ok bool) {
cmd, ok = c.Command.(SlashCommand)
return
}
// UserCommand returns the contexts Command as a
// UserCommand interface.
func (c *Ctx) UserCommand() (cmd UserCommand, ok bool) {
cmd, ok = c.Command.(UserCommand)
return
}
// MessageCommand returns the contexts Command as a
// MessageCommand interface.
func (c *Ctx) MessageCommand() (cmd MessageCommand, ok bool) {
cmd, ok = c.Command.(MessageCommand)
return
}
func (c *Ctx) ResetState() {
c.Purge()
}
// CommandHandler defines either a SubCommandHandler
// or a SubCommandGroup.
type CommandHandler interface {
Type() discordgo.ApplicationCommandOptionType
OptionName() string
RunHandler(ctx SubCommandContext) error
}
// SubCommandHandler is the handler function used
// to handle sub command calls.
type SubCommandHandler struct {
Name string
Run func(ctx SubCommandContext) error
}
func (t SubCommandHandler) Type() discordgo.ApplicationCommandOptionType {
return discordgo.ApplicationCommandOptionSubCommand
}
func (t SubCommandHandler) OptionName() string {
return t.Name
}
func (t SubCommandHandler) RunHandler(ctx SubCommandContext) error {
return t.Run(ctx)
}
// SubCommandGroup is the handler used to group
// sub commands.
type SubCommandGroup struct {
Name string
SubHandler []CommandHandler
}
func (t SubCommandGroup) Type() discordgo.ApplicationCommandOptionType {
return discordgo.ApplicationCommandOptionSubCommandGroup
}
func (t SubCommandGroup) OptionName() string {
return t.Name
}
func (t SubCommandGroup) RunHandler(ctx SubCommandContext) error {
return ctx.HandleSubCommands(t.SubHandler...)
}
// SubCommandContext wraps the current command
// Context and with the called sub command name
// and scopes the command options to the
// options of the called sub command.
//
// The SubCommandCtx must not be stored or used
// after command execution.
type SubCommandContext interface {
Context
// GetSubCommandName returns the sub command
// name which has been invoked.
GetSubCommandName() string
}
type subCommandCtx struct {
Context
subCommandName string
}
var _ SubCommandContext = (*subCommandCtx)(nil)
// Options returns the options array of the called
// sub command.
func (c *subCommandCtx) Options() CommandOptions {
return c.Context.Options().GetByName(c.subCommandName).Options
}
func (c *subCommandCtx) GetSubCommandName() string {
return c.subCommandName
}
func (c *subCommandCtx) HandleSubCommands(handler ...CommandHandler) (err error) {
return handleSubCommands(c, handler)
}
// HandleSubCommands takes a list of sub command handles.
// When the command is executed, the options are scanned
// for the sib command calls by their names. If one of
// the registered sub commands has been called, the specified
// handler function is executed.
//
// If the call occured, the passed handler function is
// getting passed the scoped sub command Ctx.
//
// The SubCommandCtx passed must not be stored or used
// after command execution.
func (c *Ctx) HandleSubCommands(handler ...CommandHandler) (err error) {
return handleSubCommands(c, handler)
}
// GetKen returns the root instance of Ken.
func (c *Ctx) GetKen() *Ken {
return c.ken
}
// GetCommand returns the command instance called.
func (c *Ctx) GetCommand() Command {
return c.Command
}
// ComponentContext gives access to the underlying
// MessageComponentInteractionData and gives the
// ability to open a Modal afterwards.
type ComponentContext interface {
ContextResponder
// GetData returns the underlying
// MessageComponentInteractionData.
GetData() discordgo.MessageComponentInteractionData
// OpenModal opens a new modal with the given
// title, content and components built with the
// passed build function. A channel is returned
// which will receive a ModalContext when the user
// has interacted with the modal.
OpenModal(
title string,
content string,
build func(b ComponentAssembler),
) (<-chan ModalContext, error)
}
type componentCtx struct {
ctxResponder
Data discordgo.MessageComponentInteractionData
}
var _ ComponentContext = (*componentCtx)(nil)
func (c *componentCtx) GetData() discordgo.MessageComponentInteractionData {
return c.Data
}
func (c *componentCtx) OpenModal(
title string,
content string,
build func(b ComponentAssembler),
) (<-chan ModalContext, error) {
b := newComponentAssembler()
build(b)
modalId := xid.New().String()
err := c.Respond(&discordgo.InteractionResponse{
Type: discordgo.InteractionResponseModal,
Data: &discordgo.InteractionResponseData{
CustomID: modalId,
Title: title,
Content: content,
Components: b.components,
},
})
if err != nil {
return nil, err
}
cCtx := make(chan ModalContext, 1)
c.ken.componentHandler.registerModalHandler(modalId, func(ctx ModalContext) bool {
cCtx <- ctx
return true
})
return cCtx, nil
}
// ModalContext provides access to the underlying
// ModalSubmitInteractionData and some utility
// methods to access component data from the
// response.
type ModalContext interface {
ContextResponder
// GetData returns the underlying
// ModalSubmitInteractionData.
GetData() discordgo.ModalSubmitInteractionData
// GetComponentByID tries to find a message component
// by CustomID in the response data and returns it
// wrapped into MessageComponent.
//
// The returned MessageComponent will contain a nil
// value for the wrapped discordgo.MessageComponent
// if it could not be found in the response.
//
// Subsequent method calls to MessageComponent will
// not fail though to ensure the ability to chain
// method calls.
GetComponentByID(customId string) MessageComponent
}
type modalCtx struct {
ctxResponder
Data discordgo.ModalSubmitInteractionData
}
var _ ModalContext = (*modalCtx)(nil)
func (c modalCtx) GetData() discordgo.ModalSubmitInteractionData {
return c.Data
}
func (c modalCtx) GetComponentByID(customId string) MessageComponent {
return MessageComponent{getComponentByID(customId, c.GetData().Components)}
}
// -------------------------------------------------------------------------------------------------
func handleSubCommands(c Context, handler []CommandHandler) (err error) {
opt := c.Options().Get(0)
for _, h := range handler {
if opt.Type != h.Type() || opt.Name != h.OptionName() {
continue
}
ctx := c.GetKen().subCtxPool.Get()
ctx.Context = c
ctx.subCommandName = h.OptionName()
err = h.RunHandler(ctx)
c.GetKen().subCtxPool.Put(ctx)
break
}
return err
}
func getComponentByID(
customId string,
comps []discordgo.MessageComponent,
) discordgo.MessageComponent {
for _, comp := range comps {
if row, ok := comp.(*discordgo.ActionsRow); ok {
found := getComponentByID(customId, row.Components)
if found != nil {
return found
}
}
if customId == getCustomId(comp) {
return comp
}
}
return nil
}