-
Notifications
You must be signed in to change notification settings - Fork 926
/
automod_bot.go
539 lines (429 loc) · 13.7 KB
/
automod_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
package automod
import (
"context"
"encoding/json"
"errors"
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate"
"github.com/jonas747/yagpdb/automod/models"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/bot/eventsystem"
"github.com/jonas747/yagpdb/commands"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/pubsub"
"github.com/sirupsen/logrus"
"github.com/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
"sort"
)
const PubSubEvtCleaCache = "automod_2_clear_guild_cache"
func (p *Plugin) BotInit() {
commands.MessageFilterFuncs = append(commands.MessageFilterFuncs, p.checkMessage)
eventsystem.AddHandler(p.handleGuildMemberUpdate, eventsystem.EventGuildMemberUpdate)
eventsystem.AddHandler(p.handleMsgUpdate, eventsystem.EventMessageUpdate)
eventsystem.AddHandler(p.handleGuildMemberJoin, eventsystem.EventGuildMemberAdd)
pubsub.AddHandler(PubSubEvtCleaCache, func(evt *pubsub.Event) {
gs := bot.State.Guild(true, evt.TargetGuildInt)
if gs == nil {
return
}
gs.UserCacheDel(true, CacheKeyRulesets)
gs.UserCacheDel(true, CacheKeyLists)
logrus.Println("cleared automod cache for ", gs.ID)
}, nil)
}
func (p *Plugin) handleMsgUpdate(evt *eventsystem.EventData) {
p.checkMessage(evt.MessageUpdate().Message)
}
func (p *Plugin) checkMessage(msg *discordgo.Message) bool {
if msg.Author == nil || msg.Author.ID == common.BotUser.ID {
return false // Pls no panicerinos or banerinos self
}
cs := bot.State.Channel(true, msg.ChannelID)
if cs == nil || cs.Guild == nil {
return true
}
ms, err := bot.GetMember(msg.GuildID, msg.Author.ID)
if err != nil {
logrus.WithError(err).Debug("automod failed fetching member")
return true
}
stripped := ""
return !p.CheckTriggers(nil, ms, msg, cs, func(trig *ParsedPart) (activated bool, err error) {
if stripped == "" {
stripped = PrepareMessageForWordCheck(msg.Content)
}
cast, ok := trig.Part.(MessageTrigger)
if !ok {
return
}
return cast.CheckMessage(ms, cs, msg, stripped, trig.ParsedSettings)
})
}
func (p *Plugin) checkViolationTriggers(ctxData *TriggeredRuleData, violationName string) {
// reset context data
ctxData.ActivatedTriggers = nil
ctxData.CurrentRule = nil
ctxData.TriggeredRules = nil
if ctxData.RecursionCounter > 2 {
logrus.WithField("guild", ctxData.GS.ID).Warn("automod stopped infinite recursion")
return
}
rulesets, err := p.FetchGuildRulesets(ctxData.GS)
if err != nil {
logrus.WithError(err).WithField("guild", ctxData.GS.ID).Error("failed fetching guild rulesets")
return
}
if len(rulesets) < 1 {
return
}
// retrieve users violations
userViolations, err := models.AutomodViolations(qm.Where("guild_id = ? AND user_id = ? AND name = ?", ctxData.GS.ID, ctxData.MS.ID, violationName)).AllG(context.Background())
if err != nil {
logrus.WithError(err).Error("automod failed retrieving user violations")
return
}
for _, rs := range rulesets {
if !rs.RSModel.Enabled {
continue
}
// Check for triggered rules in this ruleset
ctxData.Ruleset = rs
if !p.CheckConditions(ctxData, rs.ParsedConditions) {
continue
}
var activatedTriggers []*ParsedPart
for _, rule := range rs.Rules {
ctxData.CurrentRule = rule
// Check conditions
if !p.CheckConditions(ctxData, rule.Conditions) {
continue
}
// check if one of the triggers should be activated
for _, trig := range rule.Triggers {
violationTrigger, ok := trig.Part.(ViolationListener)
if !ok {
continue
}
tDataCast := trig.ParsedSettings.(*ViolationsTriggerData)
if tDataCast.Name != violationName {
continue
}
matched, err := violationTrigger.CheckUser(ctxData, userViolations, trig.ParsedSettings, false)
if err != nil {
logrus.WithError(err).WithField("part_id", trig.RuleModel.ID).Error("failed checking violations trigger")
continue
}
if matched {
activatedTriggers = append(activatedTriggers, trig)
break
}
}
}
if len(activatedTriggers) < 1 {
// no matches :(
continue
}
// sort them in order from highest to lowest threshold
sort.Slice(activatedTriggers, func(i, j int) bool {
d1 := activatedTriggers[i].ParsedSettings.(*ViolationsTriggerData)
d2 := activatedTriggers[j].ParsedSettings.(*ViolationsTriggerData)
return d1.Treshold > d2.Treshold
})
// do a second pass with the triggers sorted, incase only the highest should be triggered
finalActivatedTriggers := make([]*ParsedPart, 0, len(activatedTriggers))
finalTriggeredRules := make([]*ParsedRule, 0, len(activatedTriggers))
triggeredOne := false
for _, t := range activatedTriggers {
ctxData.CurrentRule = t.ParentRule
violationTrigger := t.Part.(ViolationListener)
matched, err := violationTrigger.CheckUser(ctxData, userViolations, t.ParsedSettings, triggeredOne)
if err != nil {
logrus.WithError(err).WithField("part_id", t.RuleModel.ID).Error("failed checking violations trigger")
continue
}
if matched {
finalActivatedTriggers = append(finalActivatedTriggers, t)
finalTriggeredRules = append(finalTriggeredRules, t.ParentRule)
triggeredOne = true
}
}
cClone := ctxData.Clone()
cClone.Ruleset = rs
cClone.TriggeredRules = finalTriggeredRules
cClone.ActivatedTriggers = finalActivatedTriggers
cClone.CurrentRule = nil
go p.RulesetRulesTriggered(cClone, true)
logrus.WithField("guild", ctxData.GS.ID).Info("automod triggered ", len(finalTriggeredRules), " violation rules")
}
}
func (p *Plugin) handleGuildMemberUpdate(evt *eventsystem.EventData) {
evtData := evt.GuildMemberUpdate()
ms, err := bot.GetMember(evtData.GuildID, evtData.User.ID)
if err != nil || ms == nil {
return
}
if ms.Nick == "" {
return
}
p.checkNickname(ms)
}
func (p *Plugin) handleGuildMemberJoin(evt *eventsystem.EventData) {
evtData := evt.GuildMemberAdd()
gs := bot.State.Guild(true, evtData.GuildID)
ms := dstate.MSFromDGoMember(gs, evtData.Member)
p.checkUsername(ms)
}
func (p *Plugin) checkNickname(ms *dstate.MemberState) {
p.CheckTriggers(nil, ms, nil, nil, func(trig *ParsedPart) (activated bool, err error) {
cast, ok := trig.Part.(NicknameListener)
if !ok {
return false, nil
}
return cast.CheckNickname(ms, trig.ParsedSettings)
})
}
func (p *Plugin) checkUsername(ms *dstate.MemberState) {
p.CheckTriggers(nil, ms, nil, nil, func(trig *ParsedPart) (activated bool, err error) {
cast, ok := trig.Part.(UsernameListener)
if !ok {
return false, nil
}
return cast.CheckUsername(ms, trig.ParsedSettings)
})
}
func (p *Plugin) CheckTriggers(rulesets []*ParsedRuleset, ms *dstate.MemberState, msg *discordgo.Message, cs *dstate.ChannelState, checkF func(trp *ParsedPart) (activated bool, err error)) bool {
if rulesets == nil {
var err error
rulesets, err = p.FetchGuildRulesets(ms.Guild)
if err != nil {
logrus.WithError(err).WithField("guild", ms.Guild.ID).Error("automod: failed fetching triggers")
return false
}
if len(rulesets) < 1 {
return false
}
}
activatededRules := false
for _, rs := range rulesets {
if !rs.RSModel.Enabled {
continue
}
ctxData := &TriggeredRuleData{
MS: ms,
CS: cs,
GS: ms.Guild,
Plugin: p,
Ruleset: rs,
Message: msg,
}
// check if we match all conditions, starting with the ruleset conditions
if !p.CheckConditions(ctxData, rs.ParsedConditions) {
continue
}
// Check for triggered rules in this ruleset
var triggeredRules []*ParsedRule
var activatedTriggers []*ParsedPart
OUTER:
for _, rule := range rs.Rules {
// Check the rule conditions
ctxData.CurrentRule = rule
if !p.CheckConditions(ctxData, rule.Conditions) {
continue OUTER
}
ctxData.CurrentRule = nil
for _, trig := range rule.Triggers {
activated, err := checkF(trig)
if err != nil {
logrus.WithError(err).WithField("part_id", trig.RuleModel.ID).Error("failed checking trigger")
continue
}
if activated {
triggeredRules = append(triggeredRules, rule)
activatedTriggers = append(activatedTriggers, trig)
break
}
}
}
if len(triggeredRules) < 1 {
// no matches :(
continue
}
ctxData.TriggeredRules = triggeredRules
ctxData.ActivatedTriggers = activatedTriggers
if ctxData.Message != nil {
ctxData.StrippedMessageContent = PrepareMessageForWordCheck(ctxData.Message.Content)
}
go p.RulesetRulesTriggered(ctxData, true)
activatededRules = true
logrus.WithField("guild", ctxData.GS.ID).Info("automod triggered ", len(triggeredRules), " rules")
}
return activatededRules
}
func (p *Plugin) RulesetRulesTriggered(ctxData *TriggeredRuleData, checkedConditions bool) {
ruleset := ctxData.Ruleset
if checkedConditions {
p.RulesetRulesTriggeredCondsPassed(ruleset, ctxData.TriggeredRules, ctxData)
return
}
// check if we match all conditions, starting with the ruleset conditions
if !p.CheckConditions(ctxData, ctxData.Ruleset.ParsedConditions) {
return
}
filteredRules := make([]*ParsedRule, 0, len(ctxData.TriggeredRules))
// Check the rule specific conditins
for _, rule := range ctxData.TriggeredRules {
ctxData.CurrentRule = rule
if !p.CheckConditions(ctxData, rule.Conditions) {
continue
}
// all conditions passed
filteredRules = append(filteredRules, rule)
}
if len(filteredRules) < 1 {
return // no rules passed
}
p.RulesetRulesTriggeredCondsPassed(ruleset, filteredRules, ctxData)
}
func (p *Plugin) CheckConditions(ctxData *TriggeredRuleData, conditions []*ParsedPart) bool {
// check if we match all conditions, starting with the ruleset conditions
for _, cond := range conditions {
met, err := cond.Part.(Condition).IsMet(ctxData, cond.ParsedSettings)
if err != nil {
logrus.WithError(err).WithField("guild", ctxData.GS.ID).Error("failed checking if automod condition was met")
return false // assume the condition failed
}
if !met {
return false // condition was not met
}
}
return true
}
func (p *Plugin) RulesetRulesTriggeredCondsPassed(ruleset *ParsedRuleset, triggeredRules []*ParsedRule, ctxData *TriggeredRuleData) {
loggedModels := make([]*models.AutomodTriggeredRule, len(triggeredRules))
// apply the effects
for i, rule := range triggeredRules {
ctxData.CurrentRule = rule
for _, effect := range rule.Effects {
go func(fx *ParsedPart, ctx *TriggeredRuleData) {
err := fx.Part.(Effect).Apply(ctx, fx.ParsedSettings)
if err != nil {
logrus.WithError(err).WithField("guild", ruleset.RSModel.GuildID).WithField("part", fx.Part.Name()).Error("failed applying automod effect")
}
}(effect, ctxData.Clone())
}
// Log the rule activation
cname := ""
cid := int64(0)
if ctxData.CS != nil {
ctxData.CS.Owner.RLock()
cname = ctxData.CS.Name
ctxData.CS.Owner.RUnlock()
cid = ctxData.CS.ID
}
tID := int64(0)
tTypeID := 0
for _, v := range ctxData.ActivatedTriggers {
if v.RuleModel.RuleID == rule.Model.ID {
tID = v.RuleModel.ID
tTypeID = v.RuleModel.TypeID
break
}
}
serializedExtraData := []byte("{}")
if ctxData.Message != nil {
var err error
serializedExtraData, err = json.Marshal(ctxData.Message)
if err != nil {
logrus.WithError(err).Error("automod failed serializing extra data")
serializedExtraData = []byte("{}")
}
}
loggedModels[i] = &models.AutomodTriggeredRule{
ChannelID: cid,
ChannelName: cname,
GuildID: ctxData.GS.ID,
TriggerID: null.Int64{Int64: tID, Valid: tID != 0},
TriggerTypeid: tTypeID,
RuleID: null.Int64{Int64: rule.Model.ID, Valid: true},
RuleName: rule.Model.Name,
RulesetName: rule.Model.R.Ruleset.Name,
UserID: ctxData.MS.ID,
UserName: ctxData.MS.Username + "#" + ctxData.MS.StrDiscriminator(),
Extradata: serializedExtraData,
}
}
tx, err := common.PQ.BeginTx(context.Background(), nil)
if err != nil {
logrus.WithError(err).Error("automod: failed creating transaction")
return
}
for _, v := range loggedModels {
err = v.Insert(context.Background(), tx, boil.Infer())
if err != nil {
logrus.WithError(err).Error("automod: failed inserting logged triggered rule")
tx.Rollback()
return
}
}
err = tx.Commit()
if err != nil {
logrus.WithError(err).Error("automod: failed committing logging transaction")
}
}
type CacheKey int
const (
CacheKeyRulesets CacheKey = iota
CacheKeyLists
)
func (p *Plugin) FetchGuildRulesets(gs *dstate.GuildState) ([]*ParsedRuleset, error) {
v, err := gs.UserCacheFetch(true, CacheKeyRulesets, func() (interface{}, error) {
rulesets, err := models.AutomodRulesets(qm.Where("guild_id=?", gs.ID),
qm.Load("RulesetAutomodRules.RuleAutomodRuleData"), qm.Load("RulesetAutomodRulesetConditions")).AllG(context.Background())
if err != nil {
return nil, err
}
parsedSets := make([]*ParsedRuleset, 0, len(rulesets))
for _, v := range rulesets {
parsed, err := ParseRuleset(v)
if err != nil {
return nil, err
}
parsedSets = append(parsedSets, parsed)
}
return parsedSets, nil
})
if err != nil {
return nil, err
}
cast := v.([]*ParsedRuleset)
return cast, nil
}
func FetchGuildLists(gs *dstate.GuildState) ([]*models.AutomodList, error) {
v, err := gs.UserCacheFetch(true, CacheKeyLists, func() (interface{}, error) {
lists, err := models.AutomodLists(qm.Where("guild_id = ?", gs.ID)).AllG(context.Background())
if err != nil {
return nil, err
}
return []*models.AutomodList(lists), nil
})
if err != nil {
return nil, err
}
cast := v.([]*models.AutomodList)
return cast, nil
}
var ErrListNotFound = errors.New("list not found")
func FindFetchGuildList(gs *dstate.GuildState, listID int64) (*models.AutomodList, error) {
lists, err := FetchGuildLists(gs)
if err != nil {
return nil, err
}
for _, v := range lists {
if v.ID == listID {
return v, nil
}
}
return nil, ErrListNotFound
}