-
Notifications
You must be signed in to change notification settings - Fork 903
/
bot.go
1256 lines (1028 loc) · 37.8 KB
/
bot.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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package customcommands
import (
"bytes"
"context"
"fmt"
"math/rand"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/botlabs-gg/yagpdb/v2/analytics"
"github.com/botlabs-gg/yagpdb/v2/lib/template"
"github.com/botlabs-gg/yagpdb/v2/premium"
"github.com/botlabs-gg/yagpdb/v2/web"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"emperror.dev/errors"
"github.com/botlabs-gg/yagpdb/v2/bot"
"github.com/botlabs-gg/yagpdb/v2/bot/eventsystem"
"github.com/botlabs-gg/yagpdb/v2/commands"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/common/keylock"
"github.com/botlabs-gg/yagpdb/v2/common/multiratelimit"
"github.com/botlabs-gg/yagpdb/v2/common/pubsub"
"github.com/botlabs-gg/yagpdb/v2/common/scheduledevents2"
schEventsModels "github.com/botlabs-gg/yagpdb/v2/common/scheduledevents2/models"
"github.com/botlabs-gg/yagpdb/v2/common/templates"
"github.com/botlabs-gg/yagpdb/v2/customcommands/models"
"github.com/botlabs-gg/yagpdb/v2/lib/dcmd"
"github.com/botlabs-gg/yagpdb/v2/lib/discordgo"
"github.com/botlabs-gg/yagpdb/v2/lib/dstate"
"github.com/botlabs-gg/yagpdb/v2/stdcommands/util"
"github.com/sirupsen/logrus"
"github.com/vmihailenco/msgpack"
"github.com/volatiletech/null/v8"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
)
var (
CCExecLock = keylock.NewKeyLock()
DelayedCCRunLimit = multiratelimit.NewMultiRatelimiter(0.1, 10)
CCMaxDataLimit = 1000000 // 1 MB max
)
type DelayedRunLimitKey struct {
GuildID int64
ChannelID int64
}
type CCExecKey struct {
GuildID int64
CCID int64
}
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
commands.AddRootCommands(p, cmdListCommands, cmdFixCommands, cmdEvalCommand)
}
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLastLegacy(p, bot.ConcurrentEventHandler(HandleMessageCreate), eventsystem.EventMessageCreate)
eventsystem.AddHandlerAsyncLastLegacy(p, bot.ConcurrentEventHandler(HandleMessageUpdate), eventsystem.EventMessageUpdate)
eventsystem.AddHandlerAsyncLastLegacy(p, bot.ConcurrentEventHandler(handleMessageReactions), eventsystem.EventMessageReactionAdd, eventsystem.EventMessageReactionRemove)
pubsub.AddHandler("custom_commands_run_now", handleCustomCommandsRunNow, models.CustomCommand{})
scheduledevents2.RegisterHandler("cc_next_run", NextRunScheduledEvent{}, handleNextRunScheduledEVent)
scheduledevents2.RegisterHandler("cc_delayed_run", DelayedRunCCData{}, handleDelayedRunCC)
}
func handleCustomCommandsRunNow(event *pubsub.Event) {
dataCast := event.Data.(*models.CustomCommand)
f := logger.WithFields(logrus.Fields{
"guild_id": dataCast.GuildID,
"cmd_id": dataCast.LocalID,
})
gs := bot.State.GetGuild(dataCast.GuildID)
if gs == nil {
f.Error("failed fetching active guild from state")
return
}
cs := gs.GetChannel(dataCast.ContextChannel)
if cs == nil {
f.Error("failed finding channel to run cc in")
return
}
metricsExecutedCommands.With(prometheus.Labels{"trigger": "timed"}).Inc()
tmplCtx := templates.NewContext(gs, cs, nil)
ExecuteCustomCommand(dataCast, tmplCtx)
dataCast.LastRun = null.TimeFrom(time.Now())
err := UpdateCommandNextRunTime(dataCast, true, true)
if err != nil {
f.WithError(err).Error("failed updating custom command next run time")
}
}
type DelayedRunCCData struct {
ChannelID int64 `json:"channel_id"`
CmdID int64 `json:"cmd_id"`
UserData []byte `json:"data"`
Message *discordgo.Message
Member *dstate.MemberState
UserKey interface{} `json:"user_key"`
ExecutedFrom templates.ExecutedFromType `json:"executed_from"`
}
var cmdEvalCommand = &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "Evalcc",
Description: "executes custom command code (up to 1k characters)",
RequiredArgs: 1,
Arguments: []*dcmd.ArgDef{
{Name: "code", Type: dcmd.String},
},
SlashCommandEnabled: false,
DefaultEnabled: true,
RunFunc: func(data *dcmd.Data) (interface{}, error) {
hasCoreWriteRole := false
writeRoles := common.GetCoreServerConfCached(data.GuildData.GS.ID).AllowedWriteRoles
for _, r := range data.GuildData.MS.Member.Roles {
if common.ContainsInt64Slice(writeRoles, r) {
hasCoreWriteRole = true
break
}
}
adminOrPerms, err := bot.AdminOrPermMS(data.GuildData.GS.ID, data.GuildData.CS.ID, data.GuildData.MS, discordgo.PermissionManageServer)
if err != nil {
return nil, err
}
if !(adminOrPerms || hasCoreWriteRole) {
return "You need `Manage Server` permissions or control panel write access for this command", nil
}
// Disallow calling via exec / execAdmin
if data.Context().Value(commands.CtxKeyExecutedByCC) == true {
return "", nil
}
channel := data.GuildData.CS
ctx := templates.NewContext(data.GuildData.GS, channel, data.GuildData.MS)
ctx.ExecutedFrom = templates.ExecutedFromEvalCC
ctx.Msg = data.TraditionalTriggerData.Message
// use stripped message content instead of parsed arg data to avoid dcmd
// from misinterpreting backslashes and losing spaces in input; see
// https://github.com/botlabs-gg/yagpdb/pull/1547
code := common.ParseCodeblock(data.TraditionalTriggerData.MessageStrippedPrefix)
// Encourage only small code snippets being tested with this command
maxRunes := 1000
if utf8.RuneCountInString(code) > maxRunes {
return "Code is too long for in-place evaluation. Please use the control panel.", nil
}
if channel == nil {
return "Something weird happened... Contact the support server.", nil
}
out, err := ctx.Execute(code)
if err != nil {
return formatCustomCommandRunErr(code, err), err
}
return out, nil
},
}
var cmdListCommands = &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "CustomCommands",
Aliases: []string{"cc"},
Description: "Shows a custom command specified by id, trigger, or name, or lists them all",
ArgumentCombos: [][]int{{0}, {1}, {}},
Arguments: []*dcmd.ArgDef{
{Name: "ID", Type: dcmd.Int},
{Name: "Name-Or-Trigger", Type: dcmd.String},
},
SlashCommandEnabled: true,
DefaultEnabled: false,
ArgSwitches: []*dcmd.ArgDef{
{Name: "file", Help: "Send responses in file"},
{Name: "color", Help: "Use syntax highlighting (Go)"},
{Name: "raw", Help: "Force raw output"},
},
RunFunc: func(data *dcmd.Data) (interface{}, error) {
ccs, err := models.CustomCommands(qm.Where("guild_id = ?", data.GuildData.GS.ID), qm.OrderBy("local_id")).AllG(data.Context())
if err != nil {
return "Failed retrieving custom commands", err
}
groups, err := models.CustomCommandGroups(qm.Where("guild_id=?", data.GuildData.GS.ID)).AllG(data.Context())
if err != nil {
return "Failed retrieving custom command groups", err
}
groupMap := make(map[int64]string)
groupMap[0] = "Ungrouped"
for _, group := range groups {
groupMap[group.ID] = group.Name
}
foundCCS, provided := FindCommands(ccs, data)
if len(foundCCS) < 1 {
list := StringCommands(ccs, groupMap)
if len(list) == 0 {
return "This server has no custom commands, sry.", nil
}
if provided {
return "No command by that id, trigger or name found, here is a list of them all:\n" + list, nil
} else {
return "No id or trigger provided, here is a list of all server commands:\n" + list, nil
}
}
if len(foundCCS) > 1 {
return "More than 1 matched command\n" + StringCommands(foundCCS, groupMap), nil
}
cc := foundCCS[0]
highlight := "txt"
if data.Switches["color"].Value != nil {
highlight = "go"
}
var ccFile *discordgo.File
msg := &discordgo.MessageSend{Flags: discordgo.MessageFlagsSuppressEmbeds}
responses := fmt.Sprintf("```\n%s\n```", strings.Join(cc.Responses, "```\n```"))
if data.Switches["file"].Value != nil || len(responses) >= 2000 && data.Switches["raw"].Value == nil {
var buf bytes.Buffer
buf.WriteString(strings.Join(cc.Responses, "\nAdditional response:\n"))
ccFile = &discordgo.File{
Name: fmt.Sprintf("%s_CC_%d.%s", data.GuildData.GS.Name, cc.LocalID, highlight),
Reader: &buf,
}
}
ccIDMaybeWithLink := strconv.FormatInt(cc.LocalID, 10)
// Add public link to the CC if it is public
if cc.Public && cc.PublicID != "" {
ccIDMaybeWithLink = fmt.Sprintf("[%d](%s/cc/%s)", cc.LocalID, web.BaseURL(), cc.PublicID)
}
// Add link to the cc on dashboard if member has read access
var member *discordgo.Member
if data.TriggerType == dcmd.TriggerTypeSlashCommands {
member = data.SlashCommandTriggerData.Interaction.Member
} else {
member = data.TraditionalTriggerData.Message.Member
}
roles := member.Roles
perms, _ := data.GuildData.GS.GetMemberPermissions(data.ChannelID, data.Author.ID, roles)
gWithConnected := &common.GuildWithConnected{
UserGuild: &discordgo.UserGuild{
ID: data.GuildData.GS.ID,
Owner: data.Author.ID == data.GuildData.GS.OwnerID,
Permissions: perms,
},
Connected: true,
}
if hasRead, _ := web.GetUserAccessLevel(data.Author.ID, gWithConnected, common.GetCoreServerConfCached(data.GuildData.GS.ID), web.StaticRoleProvider(roles)); hasRead {
ccIDMaybeWithLink = fmt.Sprintf("[%[1]d](%[2]s/customcommands/commands/%[1]d/)", cc.LocalID, web.ManageServerURL(data.GuildData))
}
// Every text-based custom command trigger has a numerical value less than 5, so this is quite safe to do
if cc.TriggerType < 5 {
var header string
if cc.TextTrigger == "" {
cc.TextTrigger = ``
}
if cc.Name.Valid {
header = fmt.Sprintf("#%s - Trigger: `%s` - Type: `%s` - Name: `%s` - Case sensitive trigger: `%t` - Group: `%s` - Disabled: `%t` - onEdit: `%t` Public: `%t`",
ccIDMaybeWithLink, cc.TextTrigger, CommandTriggerType(cc.TriggerType), cc.Name.String, cc.TextTriggerCaseSensitive, groupMap[cc.GroupID.Int64], cc.Disabled, cc.TriggerOnEdit, cc.Public)
} else {
header = fmt.Sprintf("#%s - Trigger: `%s` - Type: `%s` - Case sensitive trigger: `%t` - Group: `%s` - Disabled: `%t` - onEdit: `%t` Public: `%t`",
ccIDMaybeWithLink, cc.TextTrigger, CommandTriggerType(cc.TriggerType), cc.TextTriggerCaseSensitive, groupMap[cc.GroupID.Int64], cc.Disabled, cc.TriggerOnEdit, cc.Public)
}
if ccFile != nil {
msg.Content = header
msg.Files = []*discordgo.File{ccFile}
return msg, nil
}
msg.Content = fmt.Sprintf("%s\n```%s\n%s\n```", header, highlight, strings.Join(cc.Responses, "```\n```"))
return msg, nil
}
if ccFile != nil {
var header string
if cc.Name.Valid {
header = fmt.Sprintf("#%s - Type: `%s` - Name: `%s` - Group: `%s` - Disabled: `%t` Public: `%t`", ccIDMaybeWithLink, CommandTriggerType(cc.TriggerType), cc.Name.String, groupMap[cc.GroupID.Int64], cc.Disabled, cc.Public)
} else {
header = fmt.Sprintf("#%s - Type: `%s` - Group: `%s` - Disabled: `%t` Public: `%t`", ccIDMaybeWithLink, CommandTriggerType(cc.TriggerType), groupMap[cc.GroupID.Int64], cc.Disabled, cc.Public)
}
msg.Content = header
msg.Files = []*discordgo.File{ccFile}
return msg, nil
}
if cc.Name.Valid {
msg.Content = fmt.Sprintf("#%s - Type: `%s` - Name: `%s` - Group: `%s` - Disabled: `%t` Public: `%t`\n```%s\n%s\n```",
ccIDMaybeWithLink, CommandTriggerType(cc.TriggerType), cc.Name.String, groupMap[cc.GroupID.Int64], cc.Disabled, cc.Public,
highlight, strings.Join(cc.Responses, "```\n```"))
} else {
msg.Content = fmt.Sprintf("#%s - Type: `%s` - Group: `%s` - Disabled: `%t` Public: `%t`\n```%s\n%s\n```",
ccIDMaybeWithLink, CommandTriggerType(cc.TriggerType), groupMap[cc.GroupID.Int64], cc.Disabled, cc.Public,
highlight, strings.Join(cc.Responses, "```\n```"))
}
return msg, nil
},
}
func FindCommands(ccs []*models.CustomCommand, data *dcmd.Data) (foundCCS []*models.CustomCommand, provided bool) {
foundCCS = make([]*models.CustomCommand, 0, len(ccs))
provided = true
if data.Args[0].Value != nil {
// Find by ID
id := data.Args[0].Int64()
for _, v := range ccs {
if v.LocalID == id {
foundCCS = append(foundCCS, v)
}
}
} else if data.Args[1].Value != nil {
// Find by trigger/name
nameOrTrigger := data.Args[1].Str()
for _, v := range ccs {
if strings.EqualFold(nameOrTrigger, v.TextTrigger) || (v.Name.Valid && strings.EqualFold(nameOrTrigger, v.Name.String)) {
foundCCS = append(foundCCS, v)
}
}
} else {
provided = false
}
return
}
func StringCommands(ccs []*models.CustomCommand, gMap map[int64]string) string {
out := ""
for _, cc := range ccs {
switch {
case cc.TriggerType >= 5:
if cc.Name.Valid {
out += fmt.Sprintf("`#%3d:` - Type: `%s` - Name: `%s` - Group: `%s` - Disabled: `%t` - Public: `%t`\n", cc.LocalID, CommandTriggerType(cc.TriggerType).String(), cc.Name.String, gMap[cc.GroupID.Int64], cc.Disabled, cc.Public)
} else {
out += fmt.Sprintf("`#%3d:` - Type: `%s` - Group: `%s` - Disabled: `%t` - Public: `%t`\n", cc.LocalID, CommandTriggerType(cc.TriggerType).String(), gMap[cc.GroupID.Int64], cc.Disabled, cc.Public)
}
default:
if cc.TextTrigger == "" {
cc.TextTrigger = ``
}
if cc.Name.Valid {
out += fmt.Sprintf("`#%3d:` - Trigger: `%s` - Type: `%s` - Name: `%s` - Group: `%s` - Disabled: `%t` - onEdit: `%t` - Public: `%t`\n", cc.LocalID, cc.TextTrigger, CommandTriggerType(cc.TriggerType).String(), cc.Name.String, gMap[cc.GroupID.Int64], cc.Disabled, cc.TriggerOnEdit, cc.Public)
} else {
out += fmt.Sprintf("`#%3d:` - Trigger: `%s` - Type: `%s` - Group: `%s` - Disabled: `%t` - onEdit: `%t` - Public: `%t`\n", cc.LocalID, cc.TextTrigger, CommandTriggerType(cc.TriggerType).String(), gMap[cc.GroupID.Int64], cc.Disabled, cc.TriggerOnEdit, cc.Public)
}
}
}
return out
}
func handleDelayedRunCC(evt *schEventsModels.ScheduledEvent, data interface{}) (retry bool, err error) {
dataCast := data.(*DelayedRunCCData)
cmd, err := models.CustomCommands(qm.Where("guild_id = ? AND local_id = ?", evt.GuildID, dataCast.CmdID)).OneG(context.Background())
if err != nil {
return false, errors.WrapIf(err, "find_command")
}
if cmd.Disabled {
return false, errors.New("custom command is disabled")
}
if !DelayedCCRunLimit.AllowN(DelayedRunLimitKey{GuildID: evt.GuildID, ChannelID: dataCast.ChannelID}, time.Now(), 1) {
logger.WithField("guild", cmd.GuildID).Warn("went above delayed cc run ratelimit")
return false, nil
}
gs := bot.State.GetGuild(evt.GuildID)
if gs == nil {
// in case the bot left in the meantime
if onGuild, err := common.BotIsOnGuild(evt.GuildID); !onGuild && err == nil {
return false, nil
} else if err != nil {
logger.WithError(err).Error("failed checking if bot is on guild")
}
return true, nil
}
cs := gs.GetChannelOrThread(dataCast.ChannelID)
if cs == nil {
// don't reschedule if channel is deleted, make sure its actually not there, and not just a discord downtime
if !gs.Available {
return true, nil
}
return false, nil
}
// attempt to get up to date member information
if dataCast.Member != nil {
updatedMS, _ := bot.GetMember(gs.ID, dataCast.Member.User.ID)
if updatedMS != nil {
dataCast.Member = updatedMS
}
}
tmplCtx := templates.NewContext(gs, cs, dataCast.Member)
if dataCast.Message != nil {
tmplCtx.Msg = dataCast.Message
tmplCtx.Data["Message"] = dataCast.Message
}
tmplCtx.ExecutedFrom = dataCast.ExecutedFrom
// decode userdata
if len(dataCast.UserData) > 0 {
var i interface{}
err := msgpack.Unmarshal(dataCast.UserData, &i)
if err != nil {
return false, err
}
tmplCtx.Data["ExecData"] = i
}
metricsExecutedCommands.With(prometheus.Labels{"trigger": "timed"}).Inc()
err = ExecuteCustomCommand(cmd, tmplCtx)
return false, err
}
func handleNextRunScheduledEVent(evt *schEventsModels.ScheduledEvent, data interface{}) (retry bool, err error) {
cmd, err := models.CustomCommands(qm.Where("guild_id = ? AND local_id = ?", evt.GuildID, (data.(*NextRunScheduledEvent)).CmdID)).OneG(context.Background())
if err != nil {
return false, errors.WrapIf(err, "find_command")
}
if cmd.Disabled {
return false, errors.New("custom command is disabled")
}
if time.Until(cmd.NextRun.Time) > time.Second*5 {
return false, nil // old scheduled event that wasn't removed, /shrug
}
gs := bot.State.GetGuild(evt.GuildID)
if gs == nil {
if onGuild, err := common.BotIsOnGuild(evt.GuildID); !onGuild && err == nil {
return false, nil
} else if err != nil {
logger.WithError(err).Error("failed checking if bot is on guild")
}
return true, nil
}
cs := gs.GetChannel(cmd.ContextChannel)
if cs == nil {
// don't reschedule if channel is deleted, make sure its actually not there, and not just a discord downtime
if !gs.Available {
return true, nil
}
return false, nil
}
metricsExecutedCommands.With(prometheus.Labels{"trigger": "timed"}).Inc()
tmplCtx := templates.NewContext(gs, cs, nil)
ExecuteCustomCommand(cmd, tmplCtx)
// schedule next runs
cmd.LastRun = cmd.NextRun
err = UpdateCommandNextRunTime(cmd, true, false)
if err != nil {
logger.WithError(err).Error("failed updating custom command next run time")
}
return false, nil
}
func shouldIgnoreChannel(msg *discordgo.Message, gs *dstate.GuildSet, cState *dstate.ChannelState) bool {
if msg.GuildID == 0 {
return true
}
if cState == nil {
logger.Warn("Channel not found in state")
return true
}
if !bot.IsNormalUserMessage(msg) {
return true
}
if msg.Author.Bot {
return true
}
if hasPerms, _ := bot.BotHasPermissionGS(gs, cState.ID, discordgo.PermissionSendMessages); !hasPerms {
return true
}
// Passed all checks, custom commands should not ignore this channel
return false
}
const (
CCMessageExecLimitNormal = 3
CCMessageExecLimitPremium = 5
)
func (p *Plugin) OnRemovedPremiumGuild(GuildID int64) error {
commands, err := models.CustomCommands(qm.Where("guild_id = ?", GuildID), qm.Offset(MaxCommands)).AllG(context.Background())
if err != nil {
return errors.WrapIf(err, "failed getting custom commands")
}
if len(commands) > 0 {
_, err = commands.UpdateAllG(context.Background(), models.M{"disabled": true})
if err != nil {
return errors.WrapIf(err, "failed disabling custom commands on premium removal")
}
}
_, err = models.CustomCommands(qm.Where("guild_id = ?", GuildID)).UpdateAllG(context.Background(), models.M{"trigger_on_edit": false})
if err != nil {
return errors.WrapIf(err, "Failed disabling trigger on edits on premium removal")
}
_, err = models.CustomCommands(qm.Where("guild_id = ? AND length(regexp_replace(array_to_string(responses, ''), E'\\r', '', 'g')) > ?", GuildID, MaxCCResponsesLength)).UpdateAllG(context.Background(), models.M{"disabled": true})
if err != nil {
return errors.WrapIf(err, "Failed disabling long customs commands on premium removal")
}
return nil
}
var metricsExecutedCommands = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "yagpdb_cc_triggered_total",
Help: "Number custom commands triggered",
}, []string{"trigger"})
func handleMessageReactions(evt *eventsystem.EventData) {
var reaction *discordgo.MessageReaction
var added bool
switch e := evt.EvtInterface.(type) {
case *discordgo.MessageReactionAdd:
added = true
reaction = e.MessageReaction
case *discordgo.MessageReactionRemove:
reaction = e.MessageReaction
}
if reaction.GuildID == 0 || reaction.UserID == common.BotUser.ID {
// ignore dm reactions and reactions from the bot
return
}
if !evt.HasFeatureFlag(featureFlagHasCommands) {
return
}
cState := evt.CSOrThread()
if cState == nil {
return
}
if hasPerms, _ := bot.BotHasPermissionGS(evt.GS, cState.ID, discordgo.PermissionSendMessages); !hasPerms {
// don't run in channel we don't have perms in
return
}
ms, triggeredCmds, err := findReactionTriggerCustomCommands(evt.Context(), cState, reaction.UserID, reaction, added)
if err != nil {
if common.IsDiscordErr(err, discordgo.ErrCodeUnknownMember) {
// example scenario: removing reactions of a user that's not on the server
// (reactions aren't cleared automatically when a user leaves)
return
}
logger.WithField("guild", evt.GS.ID).WithError(err).Error("failed finding reaction ccs")
return
}
if len(triggeredCmds) < 1 {
return
}
metricsExecutedCommands.With(prometheus.Labels{"trigger": "reaction"}).Inc()
rMessage, err := common.BotSession.ChannelMessage(cState.ID, reaction.MessageID)
if err != nil {
logger.WithField("guild", evt.GS.ID).WithError(err).Error("failed finding reaction ccs")
return
}
rMessage.GuildID = cState.GuildID
for _, matched := range triggeredCmds {
err = ExecuteCustomCommandFromReaction(matched.CC, evt.GS, ms, cState, reaction, added, rMessage)
if err != nil {
logger.WithField("guild", cState.GuildID).WithField("cc_id", matched.CC.LocalID).WithError(err).Error("Error executing custom command")
}
}
}
func ExecuteCustomCommandFromReaction(cc *models.CustomCommand, gs *dstate.GuildSet, ms *dstate.MemberState, cs *dstate.ChannelState, reaction *discordgo.MessageReaction, added bool, message *discordgo.Message) error {
tmplCtx := templates.NewContext(gs, cs, ms)
// to make sure the message is in the proper context of the user reacting we set the mssage context to a fake message
fakeMsg := *message
fakeMsg.Member = ms.DgoMember()
fakeMsg.Author = fakeMsg.Member.User
tmplCtx.Msg = &fakeMsg
tmplCtx.Data["Reaction"] = reaction
tmplCtx.Data["ReactionMessage"] = message
tmplCtx.Data["Message"] = message
tmplCtx.Data["ReactionAdded"] = added
return ExecuteCustomCommand(cc, tmplCtx)
}
func HandleMessageUpdate(evt *eventsystem.EventData) {
mu := evt.MessageUpdate()
cs := evt.CSOrThread()
if isPremium, _ := premium.IsGuildPremium(mu.GuildID); !isPremium {
return
}
if !evt.HasFeatureFlag(featureFlagHasCommands) {
return
}
if shouldIgnoreChannel(mu.Message, evt.GS, cs) {
return
}
member := dstate.MemberStateFromMember(mu.Member)
member.GuildID = evt.GS.ID
var matchedCustomCommands []*TriggeredCC
var err error
common.LogLongCallTime(time.Second, true, "Took longer than a second to fetch custom commands", logrus.Fields{"guild": evt.GS.ID}, func() {
matchedCustomCommands, err = findMessageTriggerCustomCommands(evt.Context(), cs, member, evt, mu.Message)
})
if err != nil {
logger.WithError(err).Error("Error matching custom commands")
return
}
if len(matchedCustomCommands) == 0 {
return
}
metricsExecutedCommands.With(prometheus.Labels{"trigger": "message"}).Inc()
for _, matched := range matchedCustomCommands {
if !matched.CC.TriggerOnEdit {
continue
}
err = ExecuteCustomCommandFromMessage(evt.GS, matched.CC, member, cs, matched.Args, matched.Stripped, mu.Message, true)
if err != nil {
logger.WithField("guild", mu.GuildID).WithField("cc_id", matched.CC.LocalID).WithError(err).Error("Error executing custom command")
}
}
}
func HandleMessageCreate(evt *eventsystem.EventData) {
mc := evt.MessageCreate()
cs := evt.CSOrThread()
if !evt.HasFeatureFlag(featureFlagHasCommands) {
return
}
if shouldIgnoreChannel(mc.Message, evt.GS, cs) {
return
}
member := dstate.MemberStateFromMember(mc.Member)
member.GuildID = evt.GS.ID
var matchedCustomCommands []*TriggeredCC
var err error
common.LogLongCallTime(time.Second, true, "Took longer than a second to fetch custom commands", logrus.Fields{"guild": evt.GS.ID}, func() {
matchedCustomCommands, err = findMessageTriggerCustomCommands(evt.Context(), cs, member, evt, mc.Message)
})
if err != nil {
logger.WithError(err).Error("Error matching custom commands")
return
}
if len(matchedCustomCommands) == 0 {
return
}
metricsExecutedCommands.With(prometheus.Labels{"trigger": "message"}).Inc()
for _, matched := range matchedCustomCommands {
err = ExecuteCustomCommandFromMessage(evt.GS, matched.CC, member, cs, matched.Args, matched.Stripped, mc.Message, false)
if err != nil {
logger.WithField("guild", mc.GuildID).WithField("cc_id", matched.CC.LocalID).WithError(err).Error("Error executing custom command")
}
}
}
type TriggeredCC struct {
CC *models.CustomCommand
Stripped string
Args []string
}
func findMessageTriggerCustomCommands(ctx context.Context, cs *dstate.ChannelState, ms *dstate.MemberState, evt *eventsystem.EventData, msg *discordgo.Message) (matches []*TriggeredCC, err error) {
cmds, err := BotCachedGetCommandsWithMessageTriggers(cs.GuildID, ctx)
if err != nil {
return nil, errors.WrapIf(err, "BotCachedGetCommandsWithMessageTriggers")
}
prefix, err := commands.GetCommandPrefixBotEvt(evt)
if err != nil {
return nil, errors.WrapIf(err, "GetCommandPrefix")
}
var matched []*TriggeredCC
for _, cmd := range cmds {
if cmd.Disabled || !CmdRunsInChannel(cmd, common.ChannelOrThreadParentID(cs)) || !CmdRunsForUser(cmd, ms) {
continue
}
if didMatch, stripped, args := CheckMatch(prefix, cmd, msg.Content); didMatch {
matched = append(matched, &TriggeredCC{
CC: cmd,
Args: args,
Stripped: stripped,
})
}
}
sortTriggeredCCs(matched)
limit := CCMessageExecLimitNormal
if isPremium, _ := premium.IsGuildPremium(msg.GuildID); isPremium {
limit = CCMessageExecLimitPremium
}
if len(matched) > limit {
matched = matched[:limit]
}
return matched, nil
}
func findReactionTriggerCustomCommands(ctx context.Context, cs *dstate.ChannelState, userID int64, reaction *discordgo.MessageReaction, add bool) (ms *dstate.MemberState, matches []*TriggeredCC, err error) {
cmds, err := BotCachedGetCommandsWithMessageTriggers(cs.GuildID, ctx)
if err != nil {
return nil, nil, errors.WrapIf(err, "BotCachedGetCommandsWithReactionTriggers")
}
var matched []*TriggeredCC
for _, cmd := range cmds {
if cmd.Disabled || !CmdRunsInChannel(cmd, common.ChannelOrThreadParentID(cs)) {
continue
}
if didMatch := CheckMatchReaction(cmd, reaction, add); didMatch {
matched = append(matched, &TriggeredCC{
CC: cmd,
})
}
}
if len(matched) < 1 {
// no matches
return nil, matched, nil
}
ms, err = bot.GetMember(cs.GuildID, userID)
if err != nil {
return nil, nil, errors.WithStackIf(err)
}
if ms.User.Bot {
return nil, nil, nil
}
// filter by roles
filtered := make([]*TriggeredCC, 0, len(matched))
for _, v := range matched {
if !CmdRunsForUser(v.CC, ms) {
continue
}
filtered = append(filtered, v)
}
sortTriggeredCCs(filtered)
limit := CCMessageExecLimitNormal
if isPremium, _ := premium.IsGuildPremium(cs.GuildID); isPremium {
limit = CCMessageExecLimitPremium
}
if len(filtered) > limit {
filtered = filtered[:limit]
}
return ms, filtered, nil
}
func sortTriggeredCCs(ccs []*TriggeredCC) {
sort.Slice(ccs, func(i, j int) bool {
a := ccs[i]
b := ccs[j]
if a.CC.TriggerType == b.CC.TriggerType {
return a.CC.LocalID < b.CC.LocalID
}
if a.CC.TriggerType == int(CommandTriggerRegex) {
return false
}
if b.CC.TriggerType == int(CommandTriggerRegex) {
return true
}
return a.CC.LocalID < b.CC.LocalID
})
}
func ExecuteCustomCommandFromMessage(gs *dstate.GuildSet, cmd *models.CustomCommand, member *dstate.MemberState, cs *dstate.ChannelState, cmdArgs []string, stripped string, m *discordgo.Message, isEdit bool) error {
tmplCtx := templates.NewContext(gs, cs, member)
tmplCtx.Msg = m
// preapre message specific data
args := dcmd.SplitArgs(m.Content)
argsStr := make([]string, len(args))
for k, v := range args {
argsStr[k] = v.Str
}
tmplCtx.Data["Args"] = argsStr
tmplCtx.Data["StrippedMsg"] = stripped
tmplCtx.Data["Cmd"] = cmdArgs[0]
if len(cmdArgs) > 1 {
tmplCtx.Data["CmdArgs"] = cmdArgs[1:]
} else {
tmplCtx.Data["CmdArgs"] = []string{}
}
tmplCtx.Data["IsMessageEdit"] = isEdit
tmplCtx.Data["Message"] = m
return ExecuteCustomCommand(cmd, tmplCtx)
}
// func ExecuteCustomCommand(cmd *models.CustomCommand, cmdArgs []string, stripped string, s *discordgo.Session, m *discordgo.MessageCreate) (resp string, tmplCtx *templates.Context, err error) {
func ExecuteCustomCommand(cmd *models.CustomCommand, tmplCtx *templates.Context) error {
defer func() {
if err := recover(); err != nil {
actualErr := ""
switch t := err.(type) {
case error:
actualErr = t.Error()
case string:
actualErr = t
}
onExecPanic(cmd, errors.New(actualErr), tmplCtx, true)
}
}()
tmplCtx.Name = "CC #" + strconv.Itoa(int(cmd.LocalID))
tmplCtx.Data["CCID"] = cmd.LocalID
tmplCtx.Data["CCRunCount"] = cmd.RunCount + 1
tmplCtx.Data["CCTrigger"] = cmd.TextTrigger
csCop := tmplCtx.CurrentFrame.CS
f := logger.WithFields(logrus.Fields{
"trigger": cmd.TextTrigger,
"trigger_type": CommandTriggerType(cmd.TriggerType).String(),
"guild": csCop.GuildID,
"channel_name": csCop.Name,
})
// do not allow concurrent executions of the same custom command, to prevent most common kinds of abuse
lockKey := CCExecKey{
GuildID: cmd.GuildID,
CCID: cmd.LocalID,
}
lockHandle := CCExecLock.Lock(lockKey, time.Minute, time.Minute*10)
if lockHandle == -1 {
f.Warn("Exceeded max lock attempts for cc")
if cmd.ShowErrors {
common.BotSession.ChannelMessageSend(tmplCtx.CurrentFrame.CS.ID, fmt.Sprintf("Gave up trying to execute custom command #%d after 1 minute because there is already one or more instances of it being executed.", cmd.LocalID))
}
updatePostCommandRan(cmd, errors.New("Gave up trying to execute, already an existing instance executing"))
return nil
}
defer CCExecLock.Unlock(lockKey, lockHandle)
go analytics.RecordActiveUnit(cmd.GuildID, &Plugin{}, "executed_cc")
// pick a response and execute it
f.Debug("Custom command triggered")
chanMsg := cmd.Responses[rand.Intn(len(cmd.Responses))]
out, err := tmplCtx.Execute(chanMsg)
// trim whitespace for accurate character count
out = strings.TrimSpace(out)
if utf8.RuneCountInString(out) > 2000 {
out = "Custom command (#" + discordgo.StrID(cmd.LocalID) + ") response was longer than 2k (contact an admin on the server...)"
}
go updatePostCommandRan(cmd, err)
// deal with the results
if err != nil {
logger.WithField("guild", tmplCtx.GS.ID).WithError(err).Error("Error executing custom command")
if cmd.ShowErrors {
out += "\nAn error caused the execution of the custom command template to stop:\n"
out += formatCustomCommandRunErr(chanMsg, err)
}
}
_, err = tmplCtx.SendResponse(out)
if err != nil {
return errors.WithStackIf(err)
}
return nil
}
func formatCustomCommandRunErr(src string, err error) string {
// check if we can retrieve the original ExecError
cause := errors.Cause(err)
if eerr, ok := cause.(template.ExecError); ok {
data := parseExecError(eerr)
// couldn't parse error, fall back to the original error message
if data == nil {
return "`" + err.Error() + "`"
}
out := fmt.Sprintf("`Failed executing CC #%d, line %d, row %d: %s`", data.CCID, data.Line, data.Row, data.Msg)
lines := strings.Split(src, "\n")
if len(lines) < int(data.Line) {
return out
}
out += "\n```"
out += getSurroundingLines(lines, int(data.Line-1)) // data.Line is 1-based, convert to 0-based.
out += "\n```"
return out
}
// otherwise, fall back to the normal error message
return "`" + err.Error() + "`"
}
// getSurroundingLines returns a string representing the lines close to a given
// line number with common leading whitespace removed. Each line is formatted like
// `<line number> <line content>`.
func getSurroundingLines(lines []string, lineIndex int) string {
var lineNums []int
var res []string