-
Notifications
You must be signed in to change notification settings - Fork 938
/
plugin_bot.go
850 lines (704 loc) · 21.7 KB
/
plugin_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
package logs
import (
"context"
"database/sql"
"fmt"
"os"
"time"
"emperror.dev/errors"
"github.com/jonas747/yagpdb/bot/paginatedmessages"
"github.com/jonas747/dcmd"
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate"
"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/logs/models"
"github.com/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
)
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
commands.AddRootCommands(cmdLogs, cmdWhois, cmdNicknames, cmdUsernames, cmdMigrate)
}
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLastLegacy(p, bot.ConcurrentEventHandler(HandleQueueEvt), eventsystem.EventGuildMemberUpdate, eventsystem.EventGuildMemberAdd, eventsystem.EventMemberFetched)
// eventsystem.AddHandlerAsyncLastLegacy(bot.ConcurrentEventHandler(HandleGC), eventsystem.EventGuildCreate)
eventsystem.AddHandlerAsyncLast(p, HandleMsgDelete, eventsystem.EventMessageDelete, eventsystem.EventMessageDeleteBulk)
eventsystem.AddHandlerFirstLegacy(p, HandlePresenceUpdate, eventsystem.EventPresenceUpdate)
go EvtProcesser()
go EvtProcesserGCs()
}
var cmdLogs = &commands.YAGCommand{
Cooldown: 5,
CmdCategory: commands.CategoryTool,
Name: "Logs",
Aliases: []string{"log"},
Description: "Creates a log of the last messages in the current channel.",
LongDescription: "This includes deleted messages within an hour (or 12 hours for premium servers)",
Arguments: []*dcmd.ArgDef{
&dcmd.ArgDef{Name: "Count", Default: 100, Type: &dcmd.IntArg{Min: 2, Max: 250}},
},
RunFunc: func(cmd *dcmd.Data) (interface{}, error) {
num := cmd.Args[0].Int()
l, err := CreateChannelLog(cmd.Context(), nil, cmd.GS.ID, cmd.CS.ID, cmd.Msg.Author.Username, cmd.Msg.Author.ID, num)
if err != nil {
if err == ErrChannelBlacklisted {
return "This channel is blacklisted from creating message logs, this can be changed in the control panel.", nil
}
return "", err
}
return CreateLink(cmd.GS.ID, l.ID), err
},
}
var cmdWhois = &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "Whois",
Description: "Shows information about a user",
Aliases: []string{"whoami"},
RunInDM: false,
Arguments: []*dcmd.ArgDef{
{Name: "User", Type: &commands.MemberArg{}},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
config, err := GetConfig(common.PQ, parsed.Context(), parsed.GS.ID)
if err != nil {
return nil, err
}
member := commands.ContextMS(parsed.Context())
memberCPY := parsed.GS.MemberCopy(true, member.ID)
if memberCPY != nil {
member = memberCPY
}
if parsed.Args[0].Value != nil {
member = parsed.Args[0].Value.(*dstate.MemberState)
}
nick := ""
if member.Nick != "" {
nick = " (" + member.Nick + ")"
}
joinedAtStr := ""
joinedAtDurStr := ""
if !member.MemberSet {
joinedAtStr = "Couldn't find out"
joinedAtDurStr = "Couldn't find out"
} else {
joinedAtStr = member.JoinedAt.UTC().Format(time.RFC822)
dur := time.Since(member.JoinedAt)
joinedAtDurStr = common.HumanizeDuration(common.DurationPrecisionHours, dur)
}
if joinedAtDurStr == "" {
joinedAtDurStr = "Less than an hour ago"
}
t := bot.SnowflakeToTime(member.ID)
createdDurStr := common.HumanizeDuration(common.DurationPrecisionHours, time.Since(t))
if createdDurStr == "" {
createdDurStr = "Less than an hour ago"
}
var memberStatus string
state := [4]string{"Playing", "Streaming", "Listening", "Watching"}
if !member.PresenceSet || member.PresenceGame == nil {
memberStatus = fmt.Sprintf("Has no active status or is invisible/offline.")
} else {
if member.PresenceGame.Type == 4 {
memberStatus = fmt.Sprintf("%s: %s", member.PresenceGame.Name, member.PresenceGame.State)
} else {
memberStatus = fmt.Sprintf("%s: %s", state[member.PresenceGame.Type], member.PresenceGame.Name)
}
}
embed := &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s#%04d%s", member.Username, member.Discriminator, nick),
Fields: []*discordgo.MessageEmbedField{
&discordgo.MessageEmbedField{
Name: "ID",
Value: discordgo.StrID(member.ID),
Inline: true,
},
&discordgo.MessageEmbedField{
Name: "Avatar",
Value: "[Link](" + discordgo.EndpointUserAvatar(member.ID, member.StrAvatar()) + ")",
Inline: true,
},
&discordgo.MessageEmbedField{
Name: "Account Created",
Value: t.UTC().Format(time.RFC822),
Inline: true,
},
&discordgo.MessageEmbedField{
Name: "Account Age",
Value: createdDurStr,
Inline: true,
},
&discordgo.MessageEmbedField{
Name: "Joined Server At",
Value: joinedAtStr,
Inline: true,
}, &discordgo.MessageEmbedField{
Name: "Join Server Age",
Value: joinedAtDurStr,
Inline: true,
},
&discordgo.MessageEmbedField{
Name: "Status",
Value: memberStatus,
Inline: true,
},
},
Thumbnail: &discordgo.MessageEmbedThumbnail{
URL: discordgo.EndpointUserAvatar(member.ID, member.StrAvatar()),
},
}
if config.UsernameLoggingEnabled.Bool {
usernames, err := GetUsernames(parsed.Context(), member.ID, 5, 0)
if err != nil {
return err, err
}
usernamesStr := "```\n"
for _, v := range usernames {
usernamesStr += fmt.Sprintf("%20s: %s\n", v.CreatedAt.Time.UTC().Format(time.RFC822), v.Username.String)
}
usernamesStr += "```"
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "5 last usernames",
Value: usernamesStr,
})
} else {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Usernames",
Value: "Username tracking disabled",
})
}
if config.NicknameLoggingEnabled.Bool {
nicknames, err := GetNicknames(parsed.Context(), member.ID, parsed.GS.ID, 5, 0)
if err != nil {
return err, err
}
nicknameStr := "```\n"
if len(nicknames) < 1 {
nicknameStr += "No nicknames tracked"
} else {
for _, v := range nicknames {
nicknameStr += fmt.Sprintf("%20s: %s\n", v.CreatedAt.Time.UTC().Format(time.RFC822), v.Nickname.String)
}
}
nicknameStr += "```"
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "5 last nicknames",
Value: nicknameStr,
})
} else {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Nicknames",
Value: "Nickname tracking disabled",
})
}
return embed, nil
},
}
var cmdUsernames = &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "Usernames",
Description: "Shows past usernames of a user.",
Aliases: []string{"unames", "un"},
RunInDM: true,
Arguments: []*dcmd.ArgDef{
{Name: "User", Type: dcmd.User},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
if parsed.GS != nil {
config, err := GetConfig(common.PQ, parsed.Context(), parsed.GS.ID)
if err != nil {
return nil, err
}
if !config.UsernameLoggingEnabled.Bool {
return "Username logging is disabled on this server", nil
}
}
_, err := paginatedmessages.CreatePaginatedMessage(parsed.GS.ID, parsed.CS.ID, 1, 0, func(p *paginatedmessages.PaginatedMessage, page int) (*discordgo.MessageEmbed, error) {
target := parsed.Msg.Author
if parsed.Args[0].Value != nil {
target = parsed.Args[0].Value.(*discordgo.User)
}
offset := (page - 1) * 15
usernames, err := GetUsernames(context.Background(), target.ID, 15, offset)
if err != nil {
return nil, err
}
if len(usernames) < 1 && page > 1 {
return nil, paginatedmessages.ErrNoResults
}
out := fmt.Sprintf("Past username of **%s#%s** ```\n", target.Username, target.Discriminator)
for _, v := range usernames {
out += fmt.Sprintf("%20s: %s\n", v.CreatedAt.Time.UTC().Format(time.RFC822), v.Username.String)
}
out += "```"
if len(usernames) < 1 {
out = `No logged usernames`
}
embed := &discordgo.MessageEmbed{
Color: 0x277ee3,
Title: "Usernames of " + target.Username + "#" + target.Discriminator,
Description: out,
}
return embed, nil
})
return nil, err
},
}
var cmdNicknames = &commands.YAGCommand{
CmdCategory: commands.CategoryTool,
Name: "Nicknames",
Description: "Shows past nicknames of a user.",
Aliases: []string{"nn"},
RunInDM: false,
Arguments: []*dcmd.ArgDef{
{Name: "User", Type: dcmd.User},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
config, err := GetConfig(common.PQ, parsed.Context(), parsed.GS.ID)
if err != nil {
return nil, err
}
target := parsed.Msg.Author
if parsed.Args[0].Value != nil {
target = parsed.Args[0].Value.(*discordgo.User)
}
if !config.NicknameLoggingEnabled.Bool {
return "Nickname logging is disabled on this server", nil
}
_, err = paginatedmessages.CreatePaginatedMessage(parsed.GS.ID, parsed.CS.ID, 1, 0, func(p *paginatedmessages.PaginatedMessage, page int) (*discordgo.MessageEmbed, error) {
offset := (page - 1) * 15
nicknames, err := GetNicknames(context.Background(), target.ID, parsed.GS.ID, 15, offset)
if err != nil {
return nil, err
}
if page > 1 && len(nicknames) < 1 {
return nil, paginatedmessages.ErrNoResults
}
out := fmt.Sprintf("Past nicknames of **%s#%s** ```\n", target.Username, target.Discriminator)
for _, v := range nicknames {
out += fmt.Sprintf("%20s: %s\n", v.CreatedAt.Time.UTC().Format(time.RFC822), v.Nickname.String)
}
out += "```"
if len(nicknames) < 1 {
out = `No nicknames tracked`
}
embed := &discordgo.MessageEmbed{
Color: 0x277ee3,
Title: "Nicknames of " + target.Username + "#" + target.Discriminator,
Description: out,
}
return embed, nil
})
return nil, err
},
}
// Mark all log messages with this id as deleted
func HandleMsgDelete(evt *eventsystem.EventData) (retry bool, err error) {
if evt.Type == eventsystem.EventMessageDelete {
err := markLoggedMessageAsDeleted(evt.Context(), evt.MessageDelete().ID)
if err != nil {
return true, errors.WithStackIf(err)
}
return false, nil
}
for _, m := range evt.MessageDeleteBulk().Messages {
err := markLoggedMessageAsDeleted(evt.Context(), m)
if err != nil {
return true, errors.WithStackIf(err)
}
}
return false, nil
}
func markLoggedMessageAsDeleted(ctx context.Context, mID int64) error {
_, err := models.Messages2s(models.Messages2Where.ID.EQ(mID)).UpdateAllG(ctx,
models.M{"deleted": true})
return err
}
func HandlePresenceUpdate(evt *eventsystem.EventData) {
pu := evt.PresenceUpdate()
gs := evt.GS
gs.RLock()
defer gs.RUnlock()
ms := gs.Member(false, pu.User.ID)
if ms == nil || !ms.PresenceSet || !ms.MemberSet {
queueEvt(pu)
return
}
if pu.User.Username != "" && pu.User.Username != ms.Username {
queueEvt(pu)
return
}
if pu.Nick != ms.Nick {
queueEvt(pu)
return
}
}
// While presence update is sent when user changes username.... MAKES NO SENSE IMO BUT WHATEVER
// Also check nickname incase the user came online
func HandleQueueEvt(evt *eventsystem.EventData) {
queueEvt(evt.EvtInterface)
}
func queueEvt(evt interface{}) {
if os.Getenv("YAGPDB_LOGS_DISABLE_USERNAME_TRACKING") != "" {
return
}
select {
case evtChan <- evt:
return
default:
go func() {
evtChan <- evt
}()
}
}
func HandleGC(evt *eventsystem.EventData) {
gc := evt.GuildCreate()
evtChanGC <- &LightGC{
GuildID: gc.ID,
Members: gc.Members,
}
}
// type UsernameListing struct {
// gorm.Model
// UserID int64 `gorm:"index"`
// Username string
// }
// type NicknameListing struct {
// gorm.Model
// UserID int64 `gorm:"index"`
// GuildID string
// Nickname string
// }
func CheckUsername(exec boil.ContextExecutor, ctx context.Context, usernameStmt *sql.Stmt, user *discordgo.User) error {
var lastUsername string
row := usernameStmt.QueryRow(user.ID)
err := row.Scan(&lastUsername)
if err == nil && lastUsername == user.Username {
// Not changed
return nil
}
if err != nil && err != sql.ErrNoRows {
// Other error
return nil
}
logger.Debug("User changed username, old:", lastUsername, " | new:", user.Username)
listing := &models.UsernameListing{
UserID: null.Int64From(user.ID),
Username: null.StringFrom(user.Username),
}
err = listing.Insert(ctx, exec, boil.Infer())
if err != nil {
logger.WithError(err).WithField("user", user.ID).Error("failed setting last username")
}
return err
}
func CheckNickname(exec boil.ContextExecutor, ctx context.Context, nicknameStmt *sql.Stmt, userID, guildID int64, nickname string) error {
var lastNickname string
row := nicknameStmt.QueryRow(userID, guildID)
err := row.Scan(&lastNickname)
if err == sql.ErrNoRows && nickname == "" {
// don't need to be putting this in the database as the first record for the user
return nil
}
if err == nil && lastNickname == nickname {
// Not changed
return nil
}
if err != sql.ErrNoRows && err != nil {
return err
}
logger.Debug("User changed nickname, old:", lastNickname, " | new:", nickname)
listing := &models.NicknameListing{
UserID: null.Int64From(userID),
GuildID: null.StringFrom(discordgo.StrID(guildID)),
Nickname: null.StringFrom(nickname),
}
err = listing.Insert(ctx, exec, boil.Infer())
if err != nil {
logger.WithError(err).WithField("guild", guildID).WithField("user", userID).Error("failed setting last nickname")
}
return err
}
// func CheckNicknameBulk(gDB *gorm.DB, guildID int64, members []*discordgo.Member) {
// ids := make([]int64, 0, len(members))
// for _, v := range members {
// ids = append(ids, v.User.ID)
// }
// rows, err := gDB.CommonDB().Query(
// "select distinct on(user_id) nickname,user_id from nickname_listings where user_id = ANY ($1) AND guild_id=$2 order by user_id,id desc;", pq.Int64Array(ids), guildID)
// if err != nil {
// logger.WithError(err).Error("Failed querying current nicknames")
// }
// // Value is wether the nickname was identical
// queriedUsers := make(map[int64]bool)
// for rows.Next() {
// var nickname string
// var userID int64
// err = rows.Scan(&nickname, &userID)
// if err != nil {
// logger.WithError(err).Error("Error while scanning")
// continue
// }
// for _, member := range members {
// if member.User.ID == userID {
// if member.Nick == nickname {
// // Already have the last username tracked
// queriedUsers[userID] = true
// } else {
// queriedUsers[userID] = false
// logger.Debug("CHANGED Nick: ", nickname, " : ", member.Nick)
// }
// break
// }
// }
// }
// rows.Close()
// for _, member := range members {
// unchanged, queried := queriedUsers[member.User.ID]
// if queried && unchanged {
// continue
// }
// if !queried && member.Nick == "" {
// // don't need to be putting this in the database as the first record for the user
// continue
// }
// logger.Debug("User changed nickname, new: ", member.Nick)
// listing := NicknameListing{
// UserID: member.User.ID,
// GuildID: discordgo.StrID(guildID),
// Nickname: member.Nick,
// }
// err = gDB.Create(&listing).Error
// if err != nil {
// logger.WithError(err).Error("Failed setting nickname")
// }
// }
// }
// func CheckUsernameBulk(gDB *gorm.DB, users []*discordgo.User) {
// ids := make([]int64, 0, len(users))
// for _, v := range users {
// ids = append(ids, v.ID)
// }
// rows, err := gDB.CommonDB().Query(
// "select distinct on(user_id) username,user_id from username_listings where user_id = ANY ($1) order by user_id,id desc;", pq.Int64Array(ids))
// if err != nil {
// logger.WithError(err).Error("Failed querying current usernames")
// }
// unchangedUsers := make(map[int64]bool)
// for rows.Next() {
// var username string
// var userID int64
// err = rows.Scan(&username, &userID)
// if err != nil {
// logger.WithError(err).Error("Error while scanning")
// continue
// }
// // var foundUser *discordgo.User
// for _, user := range users {
// if user.ID == userID {
// if user.Username == username {
// // Already have the last username tracked
// unchangedUsers[userID] = true
// }
// break
// }
// }
// }
// rows.Close()
// for _, user := range users {
// if unchanged, ok := unchangedUsers[user.ID]; ok && unchanged {
// continue
// }
// logger.Debug("User changed username, new: ", user.Username)
// listing := UsernameListing{
// UserID: user.ID,
// Username: user.Username,
// }
// err = gDB.Create(&listing).Error
// if err != nil {
// logger.WithError(err).Error("Failed setting username")
// }
// }
// }
var (
evtChan = make(chan interface{}, 1000)
evtChanGC = make(chan *LightGC)
)
type UserGuildPair struct {
GuildID int64
User *discordgo.User
}
// Queue up all the events and process them one by one, because of limited connections
func EvtProcesser() {
queuedMembers := make([]*discordgo.Member, 0)
queuedUsers := make([]*UserGuildPair, 0)
ticker := time.NewTicker(time.Second * 10)
for {
select {
case e := <-evtChan:
switch t := e.(type) {
case *discordgo.PresenceUpdate:
if t.User.Username == "" {
continue
}
queuedUsers = append(queuedUsers, &UserGuildPair{GuildID: t.GuildID, User: t.User})
case *discordgo.GuildMemberUpdate:
queuedMembers = append(queuedMembers, t.Member)
case *discordgo.GuildMemberAdd:
queuedMembers = append(queuedMembers, t.Member)
case *discordgo.Member:
queuedMembers = append(queuedMembers, t)
}
case <-ticker.C:
started := time.Now()
err := ProcessBatch(queuedUsers, queuedMembers)
logger.Debugf("Updated %d members and %d users in %s", len(queuedMembers), len(queuedUsers), time.Since(started).String())
if err == nil {
// reset the slices
queuedUsers = queuedUsers[:0]
queuedMembers = queuedMembers[:0]
} else {
logger.WithError(err).Error("failed batch updating usernames and nicknames")
}
}
}
}
func ProcessBatch(users []*UserGuildPair, members []*discordgo.Member) error {
configs := make([]*models.GuildLoggingConfig, 0)
err := common.SqlTX(func(tx *sql.Tx) error {
nickStatement, err := tx.Prepare("select nickname from nickname_listings where user_id=$1 AND guild_id=$2 order by id desc limit 1;")
if err != nil {
return errors.WrapIf(err, "nick stmnt prepare")
}
usernameStatement, err := tx.Prepare("select username from username_listings where user_id=$1 order by id desc limit 1;")
if err != nil {
return errors.WrapIf(err, "username stmnt prepare")
}
// first find all the configs
OUTERUSERS:
for _, v := range users {
for _, c := range configs {
if c.GuildID == v.GuildID {
continue OUTERUSERS
}
}
config, err := GetConfigCached(tx, v.GuildID)
if err != nil {
return errors.WrapIf(err, "users_configs")
}
configs = append(configs, config)
}
OUTERMEMBERS:
for _, v := range members {
for _, c := range configs {
if c.GuildID == v.GuildID {
continue OUTERMEMBERS
}
}
config, err := GetConfigCached(tx, v.GuildID)
if err != nil {
return errors.WrapIf(err, "members_configs")
}
configs = append(configs, config)
}
// update users first
OUTERUSERS_UPDT:
for _, v := range users {
// check if username logging is disabled
for _, c := range configs {
if c.GuildID == v.GuildID {
if !c.UsernameLoggingEnabled.Bool {
continue OUTERUSERS_UPDT
}
break
}
}
err = CheckUsername(tx, context.Background(), usernameStatement, v.User)
if err != nil {
return errors.WrapIf(err, "user username check")
}
}
// update members
for _, v := range members {
checkNick := false
checkUser := false
// find config
for _, c := range configs {
if c.GuildID == v.GuildID {
checkNick = c.NicknameLoggingEnabled.Bool
checkUser = c.UsernameLoggingEnabled.Bool
break
}
}
if !checkNick && !checkUser {
continue
}
err = CheckUsername(tx, context.Background(), usernameStatement, v.User)
if err != nil {
return errors.WrapIf(err, "members username check")
}
err = CheckNickname(tx, context.Background(), nickStatement, v.User.ID, v.GuildID, v.Nick)
if err != nil {
return errors.WrapIf(err, "members nickname check")
}
}
return nil
})
return err
}
type LightGC struct {
GuildID int64
Members []*discordgo.Member
}
func EvtProcesserGCs() {
for {
<-evtChanGC
// tx := common.GORM.Begin()
// conf, err := GetConfig(gc.GuildID)
// if err != nil {
// logger.WithError(err).Error("Failed fetching config")
// continue
// }
// started := time.Now()
// users := make([]*discordgo.User, len(gc.Members))
// for i, m := range gc.Members {
// users[i] = m.User
// }
// if conf.NicknameLoggingEnabled {
// CheckNicknameBulk(tx, gc.GuildID, gc.Members)
// }
// if conf.UsernameLoggingEnabled {
// CheckUsernameBulk(tx, users)
// }
// err = tx.Commit().Error
// if err != nil {
// logger.WithError(err).Error("Failed committing transaction")
// continue
// }
// if len(gc.Members) > 100 {
// logger.Infof("Checked %d members in %s", len(gc.Members), time.Since(started).String())
// // Make sure this dosen't use all our resources
// time.Sleep(time.Second * 25)
// } else {
// time.Sleep(time.Second * 15)
// }
}
}
const CacheKeyConfig bot.GSCacheKey = "logs_config"
func GetConfigCached(exec boil.ContextExecutor, gID int64) (*models.GuildLoggingConfig, error) {
gs := bot.State.Guild(true, gID)
if gs == nil {
return GetConfig(exec, context.Background(), gID)
}
v, err := gs.UserCacheFetch(CacheKeyConfig, func() (interface{}, error) {
conf, err := GetConfig(exec, context.Background(), gID)
return conf, err
})
if err != nil {
return nil, err
}
return v.(*models.GuildLoggingConfig), nil
}