forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
451 lines (368 loc) · 10.7 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
package autorole
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/jonas747/dcmd"
"github.com/jonas747/discordgo"
"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"
)
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ bot.BotStopperHandler = (*Plugin)(nil)
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
commands.AddRootCommands(roleCommands...)
}
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLast(OnMemberJoin, eventsystem.EventGuildMemberAdd)
eventsystem.AddHandlerAsyncLast(HandlePresenceUpdate, eventsystem.EventPresenceUpdate)
eventsystem.AddHandlerAsyncLast(HandleGuildChunk, eventsystem.EventGuildMembersChunk)
pubsub.AddHandler("autorole_stop_processing", HandleUpdateAutoroles, nil)
go runDurationChecker()
}
func (p *Plugin) StopBot(wg *sync.WaitGroup) {
close(completeStop)
wg.Done()
}
var roleCommands = []*commands.YAGCommand{
&commands.YAGCommand{
CmdCategory: commands.CategoryDebug,
Name: "Roledbg",
Description: "Debug debug debug autorole assignment",
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
var processing int
err := common.RedisPool.Do(retryableredis.Cmd(&processing, "GET", KeyProcessing(parsed.GS.ID)))
return fmt.Sprintf("Processing %d users.", processing), err
},
},
}
// Stop updating
func HandleUpdateAutoroles(event *pubsub.Event) {
gs := bot.State.Guild(true, event.TargetGuildInt)
if gs != nil {
gs.UserCacheDel(true, CacheKeyConfig)
}
stopProcessing(event.TargetGuildInt)
}
// HandlePresenceUpdate makes sure the member with joined_at is available for the relevant guilds
// TODO: Figure out a solution that scales better
func HandlePresenceUpdate(evt *eventsystem.EventData) {
p := evt.PresenceUpdate()
if p.Status == discordgo.StatusOffline {
return
}
gs := bot.State.Guild(true, p.GuildID)
if gs == nil {
return
}
gs.RLock()
m := gs.Member(false, p.User.ID)
if m != nil && m.MemberSet {
gs.RUnlock()
return
}
gs.RUnlock()
config, err := GuildCacheGetGeneralConfig(gs)
if err != nil {
return
}
if !config.OnlyOnJoin && config.Role != 0 {
go bot.GetMember(gs.ID, p.User.ID)
}
}
var (
processingGuilds = make(map[int64]chan bool)
processingLock sync.Mutex
completeStop = make(chan bool)
)
func stopProcessing(guildID int64) {
processingLock.Lock()
if c, ok := processingGuilds[guildID]; ok {
go func() {
select {
case c <- true:
default:
return
}
}()
}
processingLock.Unlock()
}
func runDurationChecker() {
ticker := time.NewTicker(time.Second)
state := bot.State
var guildsToCheck []*dstate.GuildState
var i int
var numToCheckPerRun int
for {
select {
case <-completeStop:
return
case <-ticker.C:
}
if len(guildsToCheck) < 0 || i >= len(guildsToCheck) {
// Copy the list of guilds so that we dont need to keep the entire state locked
guildsToCheck = state.GuildsSlice(true)
i = 0
// Hit each guild once per minute
numToCheckPerRun = len(guildsToCheck) / 60
if numToCheckPerRun < 1 {
numToCheckPerRun = 1
}
}
for checkedThisRound := 0; i < len(guildsToCheck) && checkedThisRound < numToCheckPerRun; i++ {
g := guildsToCheck[i]
checkGuild(g)
checkedThisRound++
}
}
}
// returns true if we should skip the guild
func stateLockedSkipGuild(gs *dstate.GuildState, conf *GeneralConfig) bool {
gs.RLock()
defer gs.RUnlock()
if gs.Guild.Unavailable {
return true
}
if !bot.BotProbablyHasPermissionGS(false, gs, 0, discordgo.PermissionManageRoles) {
return true
}
if gs.Role(false, conf.Role) == nil {
conf.Role = 0
saveGeneral(gs.ID, conf)
return true
}
return false
}
func checkGuild(gs *dstate.GuildState) {
conf, err := GuildCacheGetGeneralConfig(gs)
if err != nil {
logger.WithField("guild", gs.ID).WithError(err).Error("Failed retrieivng general config")
return
}
if conf.Role == 0 || conf.OnlyOnJoin {
return
}
if stateLockedSkipGuild(gs, conf) {
return
}
if WorkingOnFullScan(gs.ID) {
return // Working on a full scan, do nothing
}
go processGuild(gs, conf)
}
func processGuild(gs *dstate.GuildState, config *GeneralConfig) {
processingLock.Lock()
if _, ok := processingGuilds[gs.ID]; ok {
// Still processing this guild
processingLock.Unlock()
return
}
stopChan := make(chan bool, 1)
processingGuilds[gs.ID] = stopChan
processingLock.Unlock()
var setProcessingRedis bool
// Reset the processing state
defer func() {
processingLock.Lock()
delete(processingGuilds, gs.ID)
processingLock.Unlock()
if setProcessingRedis {
common.RedisPool.Do(retryableredis.Cmd(nil, "DEL", KeyProcessing(gs.ID)))
}
}()
membersToGiveRole := make([]int64, 0)
gs.RLock()
OUTER:
for _, ms := range gs.Members {
if !ms.MemberSet {
continue
}
if config.CanAssignTo(ms.Roles, ms.JoinedAt) {
for _, r := range ms.Roles {
if r == config.Role {
continue OUTER
}
}
membersToGiveRole = append(membersToGiveRole, ms.ID)
}
}
gs.RUnlock()
if len(membersToGiveRole) > 10 {
setProcessingRedis = true
common.RedisPool.Do(retryableredis.FlatCmd(nil, "SET", KeyProcessing(gs.ID), len(membersToGiveRole)))
}
cntSinceLastRedisUpdate := 0
for i, userID := range membersToGiveRole {
time.Sleep(time.Second)
select {
case <-stopChan:
logger.WithField("guild", gs.ID).Info("Stopping autorole assigning...")
return
default:
}
cntSinceLastRedisUpdate++
err := common.BotSession.GuildMemberRoleAdd(gs.ID, userID, config.Role)
if err != nil {
if cast, ok := err.(*discordgo.RESTError); ok && cast.Message != nil && cast.Message.Code == 50013 {
// No perms, remove autorole
logger.WithError(err).Info("No perms to add autorole, removing from config")
config.Role = 0
saveGeneral(gs.ID, config)
return
}
logger.WithError(err).WithField("guild", gs.ID).Error("Failed adding autorole role")
} else {
if setProcessingRedis && cntSinceLastRedisUpdate > 10 {
common.RedisPool.Do(retryableredis.FlatCmd(nil, "SET", KeyProcessing(gs.ID), len(membersToGiveRole)-i))
cntSinceLastRedisUpdate = 0
}
}
}
}
func saveGeneral(guildID int64, config *GeneralConfig) {
err := common.SetRedisJson(KeyGeneral(guildID), config)
if err != nil {
logger.WithError(err).Error("Failed saving autorole config")
}
}
func OnMemberJoin(evt *eventsystem.EventData) {
addEvt := evt.GuildMemberAdd()
config, err := GetGeneralConfig(addEvt.GuildID)
if err != nil {
return
}
gs := bot.State.Guild(true, addEvt.GuildID)
ms := gs.MemberCopy(true, addEvt.User.ID)
if ms == nil {
logger.Error("Member not found in add event")
return
}
if config.Role != 0 && config.RequiredDuration < 1 && config.CanAssignTo(ms.Roles, ms.JoinedAt) {
common.BotSession.GuildMemberRoleAdd(addEvt.GuildID, addEvt.User.ID, config.Role)
}
}
func (conf *GeneralConfig) CanAssignTo(currentRoles []int64, joinedAt time.Time) bool {
if time.Since(joinedAt) < time.Duration(conf.RequiredDuration)*time.Minute {
return false
}
if len(conf.IgnoreRoles) < 1 && len(conf.RequiredRoles) < 1 {
return true
}
for _, ignoreRole := range conf.IgnoreRoles {
if common.ContainsInt64Slice(currentRoles, ignoreRole) {
return false
}
}
// If require roles are set up, make sure the member has one of them
if len(conf.RequiredRoles) > 0 {
for _, reqRole := range conf.RequiredRoles {
if common.ContainsInt64Slice(currentRoles, reqRole) {
return true
}
}
return false
}
return true
}
func RedisKeyGuildChunkProecssing(gID int64) string {
return "autorole_guild_chunk_processing:" + strconv.FormatInt(gID, 10)
}
func HandleGuildChunk(evt *eventsystem.EventData) {
chunk := evt.GuildMembersChunk()
err := common.RedisPool.Do(retryableredis.Cmd(nil, "SETEX", RedisKeyGuildChunkProecssing(chunk.GuildID), "100", "1"))
if err != nil {
logger.WithError(err).Error("failed marking autorole chunk processing")
}
config, err := GetGeneralConfig(chunk.GuildID)
if err != nil {
return
}
if config.Role == 0 {
return
}
stopProcessing(chunk.GuildID)
lastTimeUpdatedBlockingKey := time.Now()
lastTimeUpdatedConfig := time.Now()
OUTER:
for _, m := range chunk.Members {
joinedAt, err := m.JoinedAt.Parse()
if err != nil {
logger.WithError(err).WithField("ts", m.JoinedAt).WithField("user", m.User.ID).WithField("guild", chunk.GuildID).Error("failed parsing join timestamp")
if config.RequiredDuration > 0 {
continue // Need the joined_at field for this
}
}
if !config.CanAssignTo(m.Roles, joinedAt) {
continue
}
for _, r := range m.Roles {
if r == config.Role {
continue OUTER
}
}
time.Sleep(time.Second)
logger.Println("assigning to ", m.User.ID, " from guild chunk event")
err = common.AddRole(m, config.Role, chunk.GuildID)
if err != nil {
logger.WithError(err).WithField("user", m.User.ID).WithField("guild", chunk.GuildID).Error("failed adding autorole role")
if common.IsDiscordErr(err, 50013, 10011) {
// No perms, remove autorole
logger.WithError(err).WithField("guild", chunk.GuildID).Info("No perms to add autorole, or nonexistant, removing from config")
config.Role = 0
saveGeneral(chunk.GuildID, config)
return
}
}
if time.Since(lastTimeUpdatedConfig) > time.Second*10 {
// Refresh the config occasionally to make sure it dosen't go stale
newConf, err := GetGeneralConfig(chunk.GuildID)
if err == nil {
config = newConf
} else {
return
}
lastTimeUpdatedConfig = time.Now()
config = newConf
if config.Role == 0 {
logger.WithField("guild", chunk.GuildID).Info("autorole role was set to none in the middle of full retroactive assignment, cancelling")
return
}
}
if time.Since(lastTimeUpdatedBlockingKey) > time.Second*10 {
lastTimeUpdatedBlockingKey = time.Now()
err := common.RedisPool.Do(retryableredis.Cmd(nil, "SETEX", RedisKeyGuildChunkProecssing(chunk.GuildID), "100", "1"))
if err != nil {
logger.WithError(err).Error("failed marking autorole chunk processing")
}
}
}
}
func WorkingOnFullScan(guildID int64) bool {
var b bool
err := common.RedisPool.Do(retryableredis.Cmd(&b, "EXISTS", RedisKeyGuildChunkProecssing(guildID)))
if err != nil {
logger.WithError(err).WithField("guild", guildID).Error("failed checking WorkingOnFullScan")
return false
}
return b
}
type CacheKey int
const CacheKeyConfig CacheKey = 1
func GuildCacheGetGeneralConfig(gs *dstate.GuildState) (*GeneralConfig, error) {
v, err := gs.UserCacheFetch(true, CacheKeyConfig, func() (interface{}, error) {
config, err := GetGeneralConfig(gs.ID)
return config, err
})
if err != nil {
return nil, err
}
return v.(*GeneralConfig), nil
}