forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 5
/
plugin_bot.go
515 lines (408 loc) · 14 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
package moderation
import (
"strconv"
"strings"
"time"
"emperror.dev/errors"
"github.com/jonas747/discordgo"
"github.com/jonas747/dshardorchestrator"
"github.com/jonas747/dstate"
"github.com/jonas747/retryableredis"
"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/jonas747/yagpdb/common/scheduledevents2"
seventsmodels "github.com/jonas747/yagpdb/common/scheduledevents2/models"
)
var (
ErrFailedPerms = errors.New("Failed retrieving perms")
)
type ContextKey int
const (
ContextKeyConfig ContextKey = iota
)
const MuteDeniedChannelPerms = discordgo.PermissionSendMessages | discordgo.PermissionVoiceSpeak
var _ commands.CommandProvider = (*Plugin)(nil)
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ bot.ShardMigrationReceiver = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
commands.AddRootCommands(ModerationCommands...)
}
func (p *Plugin) BotInit() {
// scheduledevents.RegisterEventHandler("unmute", handleUnMuteLegacy)
// scheduledevents.RegisterEventHandler("mod_unban", handleUnbanLegacy)
scheduledevents2.RegisterHandler("moderation_unmute", ScheduledUnmuteData{}, handleScheduledUnmute)
scheduledevents2.RegisterHandler("moderation_unban", ScheduledUnbanData{}, handleScheduledUnban)
scheduledevents2.RegisterLegacyMigrater("unmute", handleMigrateScheduledUnmute)
scheduledevents2.RegisterLegacyMigrater("mod_unban", handleMigrateScheduledUnban)
eventsystem.AddHandlerAsyncLastLegacy(p, bot.ConcurrentEventHandler(HandleGuildBanAddRemove), eventsystem.EventGuildBanAdd, eventsystem.EventGuildBanRemove)
eventsystem.AddHandlerAsyncLast(p, HandleGuildMemberRemove, eventsystem.EventGuildMemberRemove)
eventsystem.AddHandlerAsyncLast(p, LockMemberMuteMW(HandleMemberJoin), eventsystem.EventGuildMemberAdd)
eventsystem.AddHandlerAsyncLast(p, LockMemberMuteMW(HandleGuildMemberUpdate), eventsystem.EventGuildMemberUpdate)
eventsystem.AddHandlerAsyncLastLegacy(p, bot.ConcurrentEventHandler(HandleGuildCreate), eventsystem.EventGuildCreate)
eventsystem.AddHandlerAsyncLast(p, HandleChannelCreateUpdate, eventsystem.EventChannelUpdate, eventsystem.EventChannelUpdate)
pubsub.AddHandler("mod_refresh_mute_override", HandleRefreshMuteOverrides, nil)
}
type ScheduledUnmuteData struct {
UserID int64 `json:"user_id"`
}
type ScheduledUnbanData struct {
UserID int64 `json:"user_id"`
}
func (p *Plugin) ShardMigrationReceive(evt dshardorchestrator.EventType, data interface{}) {
if evt == bot.EvtGuildState {
gs := data.(*dstate.GuildState)
go RefreshMuteOverrides(gs.ID)
}
}
func HandleRefreshMuteOverrides(evt *pubsub.Event) {
RefreshMuteOverrides(evt.TargetGuildInt)
}
func HandleGuildCreate(evt *eventsystem.EventData) {
gc := evt.GuildCreate()
RefreshMuteOverrides(gc.ID)
}
// Refreshes the mute override on the channel, currently it only adds it.
func RefreshMuteOverrides(guildID int64) {
config, err := GetConfig(guildID)
if err != nil {
return
}
if config.MuteRole == "" || !config.MuteManageRole {
return
}
guild := bot.State.Guild(true, guildID)
if guild == nil {
return // Still starting up and haven't received the guild yet
}
if guild.RoleCopy(true, config.IntMuteRole()) == nil {
return
}
guild.RLock()
channelsCopy := make([]*discordgo.Channel, 0, len(guild.Channels))
for _, v := range guild.Channels {
channelsCopy = append(channelsCopy, v.DGoCopy())
}
guild.RUnlock()
for _, v := range channelsCopy {
RefreshMuteOverrideForChannel(config, v)
}
}
func HandleChannelCreateUpdate(evt *eventsystem.EventData) (retry bool, err error) {
var channel *discordgo.Channel
if evt.Type == eventsystem.EventChannelCreate {
channel = evt.ChannelCreate().Channel
} else {
channel = evt.ChannelUpdate().Channel
}
if channel.GuildID == 0 {
return false, nil
}
config, err := GetConfig(channel.GuildID)
if err != nil {
return true, errors.WithStackIf(err)
}
if config.MuteRole == "" || !config.MuteManageRole {
return false, nil
}
RefreshMuteOverrideForChannel(config, channel)
return false, nil
}
func RefreshMuteOverrideForChannel(config *Config, channel *discordgo.Channel) {
// Ignore the channel
if common.ContainsInt64Slice(config.MuteIgnoreChannels, channel.ID) {
return
}
if !bot.BotProbablyHasPermission(channel.GuildID, channel.ID, discordgo.PermissionManageRoles) {
return
}
var override *discordgo.PermissionOverwrite
// Check for existing override
for _, v := range channel.PermissionOverwrites {
if v.Type == "role" && v.ID == config.IntMuteRole() {
override = v
break
}
}
allows := 0
denies := MuteDeniedChannelPerms
changed := true
if override != nil {
allows = override.Allow
denies = override.Deny
changed = false
if (allows & MuteDeniedChannelPerms) != 0 {
// One of the mute permissions was in the allows, remove it
allows &= ^MuteDeniedChannelPerms
changed = true
}
if (denies & MuteDeniedChannelPerms) != MuteDeniedChannelPerms {
// Missing one of the mute permissions
denies |= MuteDeniedChannelPerms
changed = true
}
}
if changed {
common.BotSession.ChannelPermissionSet(channel.ID, config.IntMuteRole(), "role", allows, denies)
}
}
func HandleGuildBanAddRemove(evt *eventsystem.EventData) {
var user *discordgo.User
var guildID = evt.GS.ID
var action ModlogAction
botPerformed := false
switch evt.Type {
case eventsystem.EventGuildBanAdd:
user = evt.GuildBanAdd().User
action = MABanned
var i int
common.RedisPool.Do(retryableredis.Cmd(&i, "GET", RedisKeyBannedUser(guildID, user.ID)))
if i > 0 {
// The bot banned the user earlier, don't make duplicate entries in the modlog
common.RedisPool.Do(retryableredis.Cmd(nil, "DEL", RedisKeyBannedUser(guildID, user.ID)))
return
}
case eventsystem.EventGuildBanRemove:
action = MAUnbanned
user = evt.GuildBanRemove().User
var i int
common.RedisPool.Do(retryableredis.Cmd(&i, "GET", RedisKeyUnbannedUser(guildID, user.ID)))
if i > 0 {
// The bot was the one that performed the unban
common.RedisPool.Do(retryableredis.Cmd(nil, "DEL", RedisKeyUnbannedUser(guildID, user.ID)))
botPerformed = true
}
default:
return
}
config, err := GetConfig(guildID)
if err != nil {
logger.WithError(err).WithField("guild", guildID).Error("Failed retrieving config")
return
}
if config.IntActionChannel() == 0 {
return
}
var author *discordgo.User
reason := ""
if !botPerformed {
// If we poll it too fast then there sometimes wont be a audit log entry
time.Sleep(time.Second * 3)
auditlogAction := discordgo.AuditLogActionMemberBanAdd
if evt.Type == eventsystem.EventGuildBanRemove {
auditlogAction = discordgo.AuditLogActionMemberBanRemove
}
var entry *discordgo.AuditLogEntry
author, entry = FindAuditLogEntry(guildID, auditlogAction, user.ID, -1)
if entry != nil {
reason = entry.Reason
}
}
if (action == MAUnbanned && !config.LogUnbans && !botPerformed) ||
(action == MABanned && !config.LogBans) {
return
}
// The bot only unbans people in the case of timed bans
if botPerformed {
author = common.BotUser
reason = "Timed ban expired"
}
err = CreateModlogEmbed(config.IntActionChannel(), author, action, user, reason, "")
if err != nil {
logger.WithError(err).WithField("guild", guildID).Error("Failed sending " + action.Prefix + " log message")
}
}
func HandleGuildMemberRemove(evt *eventsystem.EventData) (retry bool, err error) {
data := evt.GuildMemberRemove()
config, err := GetConfig(data.GuildID)
if err != nil {
return true, errors.WithStackIf(err)
}
if config.IntActionChannel() == 0 {
return false, nil
}
go checkAuditLogMemberRemoved(config, data)
return false, nil
}
func checkAuditLogMemberRemoved(config *Config, data *discordgo.GuildMemberRemove) {
// If we poll the audit log too fast then there sometimes wont be a audit log entry
time.Sleep(time.Second * 3)
author, entry := FindAuditLogEntry(data.GuildID, discordgo.AuditLogActionMemberKick, data.User.ID, time.Second*5)
if entry == nil || author == nil {
return
}
if author.ID == common.BotUser.ID {
// Bot performed the kick, don't make duplicate modlog entries
return
}
err := CreateModlogEmbed(config.IntActionChannel(), author, MAKick, data.User, entry.Reason, "")
if err != nil {
logger.WithError(err).WithField("guild", data.GuildID).Error("Failed sending kick log message")
}
}
// Since updating mutes are now a complex operation with removing roles and whatnot,
// to avoid weird bugs from happening we lock it so it can only be updated one place per user
func LockMemberMuteMW(next eventsystem.HandlerFunc) eventsystem.HandlerFunc {
return func(evt *eventsystem.EventData) (retry bool, err error) {
var userID int64
var guild int64
// TODO: add utility functions to the eventdata struct for fetching things like these?
if evt.Type == eventsystem.EventGuildMemberAdd {
userID = evt.GuildMemberAdd().User.ID
guild = evt.GuildMemberAdd().GuildID
} else if evt.Type == eventsystem.EventGuildMemberUpdate {
userID = evt.GuildMemberUpdate().User.ID
guild = evt.GuildMemberUpdate().GuildID
} else {
panic("Unknown event in lock memebr mute middleware")
}
// If there's less than 5 seconds of the mute left, don't bother doing anything
var muteLeft int
common.RedisPool.Do(retryableredis.Cmd(&muteLeft, "TTL", RedisKeyMutedUser(guild, userID)))
if muteLeft < 5 {
return false, nil
}
LockMute(userID)
defer UnlockMute(userID)
// The situation may have changed at this point, check again
common.RedisPool.Do(retryableredis.Cmd(&muteLeft, "TTL", RedisKeyMutedUser(guild, userID)))
if muteLeft < 5 {
return false, nil
}
return next(evt)
}
}
func HandleMemberJoin(evt *eventsystem.EventData) (retry bool, err error) {
c := evt.GuildMemberAdd()
config, err := GetConfig(c.GuildID)
if err != nil {
return true, errors.WithStackIf(err)
}
if config.MuteRole == "" {
return false, nil
}
err = common.BotSession.GuildMemberRoleAdd(c.GuildID, c.User.ID, config.IntMuteRole())
if err != nil {
return bot.CheckDiscordErrRetry(err), errors.WithStackIf(err)
}
return false, nil
}
func HandleGuildMemberUpdate(evt *eventsystem.EventData) (retry bool, err error) {
c := evt.GuildMemberUpdate()
config, err := GetConfig(c.GuildID)
if err != nil {
return true, errors.WithStackIf(err)
}
if config.MuteRole == "" {
return false, nil
}
guild := evt.GS
role := guild.RoleCopy(true, config.IntMuteRole())
if role == nil {
return false, nil // Probably deleted the mute role, do nothing then
}
removedRoles, err := AddMemberMuteRole(config, c.Member.User.ID, c.Member.Roles)
if err != nil {
return bot.CheckDiscordErrRetry(err), errors.WithStackIf(err)
}
if len(removedRoles) < 1 {
return false, nil
}
tx, err := common.PQ.Begin()
if err != nil {
return true, errors.WithStackIf(err)
}
// Append the removed roles to the removed_roles array column, if they don't already exist in it
const queryStr = "UPDATE muted_users SET removed_roles = array_append(removed_roles, $3 ) WHERE user_id=$2 AND guild_id=$1 AND NOT ($3 = ANY(removed_roles));"
for _, v := range removedRoles {
_, err := tx.Exec(queryStr, c.GuildID, c.Member.User.ID, v)
if err != nil {
tx.Rollback()
return true, errors.WithStackIf(err)
}
}
err = tx.Commit()
if err != nil {
return true, errors.WithStackIf(err)
}
return false, nil
}
func FindAuditLogEntry(guildID int64, typ int, targetUser int64, within time.Duration) (author *discordgo.User, entry *discordgo.AuditLogEntry) {
auditlog, err := common.BotSession.GuildAuditLog(guildID, 0, 0, typ, 10)
if err != nil {
return nil, nil
}
for _, entry := range auditlog.AuditLogEntries {
if entry.TargetID == targetUser {
if within != -1 {
t := bot.SnowflakeToTime(entry.ID)
if time.Since(t) > within {
return nil, nil
}
}
// Find the user details from the id
for _, v := range auditlog.Users {
if v.ID == entry.UserID {
return v, entry
}
}
break
}
}
return nil, nil
}
func handleMigrateScheduledUnmute(t time.Time, data string) error {
split := strings.Split(data, ":")
if len(split) < 2 {
logger.Error("invalid unmute event", data)
return nil
}
guildID, _ := strconv.ParseInt(split[0], 10, 64)
userID, _ := strconv.ParseInt(split[1], 10, 64)
return scheduledevents2.ScheduleEvent("moderation_unmute", guildID, t, &ScheduledUnmuteData{
UserID: userID,
})
}
func handleMigrateScheduledUnban(t time.Time, data string) error {
split := strings.Split(data, ":")
if len(split) < 2 {
logger.Error("Invalid unban event", data)
return nil // Can't re-schedule an invalid event..
}
guildID, _ := strconv.ParseInt(split[0], 10, 64)
userID, _ := strconv.ParseInt(split[1], 10, 64)
return scheduledevents2.ScheduleEvent("moderation_unban", guildID, t, &ScheduledUnbanData{
UserID: userID,
})
}
func handleScheduledUnmute(evt *seventsmodels.ScheduledEvent, data interface{}) (retry bool, err error) {
unmuteData := data.(*ScheduledUnmuteData)
member, err := bot.GetMember(evt.GuildID, unmuteData.UserID)
if err != nil {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
err = MuteUnmuteUser(nil, false, evt.GuildID, 0, common.BotUser, "Mute Duration Expired", member, 0)
if errors.Cause(err) != ErrNoMuteRole {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
return false, nil
}
func handleScheduledUnban(evt *seventsmodels.ScheduledEvent, data interface{}) (retry bool, err error) {
unbanData := data.(*ScheduledUnbanData)
guildID := evt.GuildID
userID := unbanData.UserID
g := bot.State.Guild(true, guildID)
if g == nil {
logger.WithField("guild", guildID).Error("Unban scheduled for guild not in state")
return false, nil
}
common.RedisPool.Do(retryableredis.FlatCmd(nil, "SETEX", RedisKeyUnbannedUser(guildID, userID), 30, 1))
err = common.BotSession.GuildBanDelete(guildID, userID)
if err != nil {
logger.WithField("guild", guildID).WithError(err).Error("failed unbanning user")
return scheduledevents2.CheckDiscordErrRetry(err), err
}
return false, nil
}