forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
318 lines (266 loc) · 7.21 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
package autorole
import (
"fmt"
"github.com/jonas747/dcmd"
"github.com/jonas747/discordgo"
"github.com/jonas747/dutil/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/common/pubsub"
"github.com/mediocregopher/radix.v3"
"github.com/sirupsen/logrus"
"sync"
"time"
)
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ bot.BotStartedHandler = (*Plugin)(nil)
var _ bot.BotStopperHandler = (*Plugin)(nil)
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
commands.AddRootCommands(roleCommands...)
}
func (p *Plugin) BotInit() {
eventsystem.AddHandler(OnMemberJoin, eventsystem.EventGuildMemberAdd)
eventsystem.AddHandler(HandlePresenceUpdate, eventsystem.EventPresenceUpdate)
pubsub.AddHandler("autorole_stop_processing", HandleUpdateAutoroles, nil)
}
func (p *Plugin) BotStarted() {
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(radix.Cmd(&processing, "GET", KeyProcessing(parsed.GS.ID)))
return fmt.Sprintf("Processing %d users.", processing), err
},
},
}
// Stop updating
func HandleUpdateAutoroles(event *pubsub.Event) {
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 := GetGeneralConfig(gs.ID)
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.Minute)
state := bot.State
for {
select {
case <-completeStop:
return
case <-ticker.C:
}
// Copy the list of guilds so that we dont need to keep the entire state locked
state.RLock()
guildStates := make([]*dstate.GuildState, len(state.Guilds))
i := 0
for _, v := range state.Guilds {
guildStates[i] = v
i++
}
state.RUnlock()
for _, g := range guildStates {
checkGuild(g)
}
}
}
func checkGuild(gs *dstate.GuildState) {
gs.RLock()
defer gs.RUnlock()
if gs.Guild.Unavailable {
return
}
logger := logrus.WithField("guild", gs.ID)
perms, err := gs.MemberPermissions(false, 0, common.BotUser.ID)
if err != nil && err != dstate.ErrChannelNotFound {
logger.WithError(err).Error("Error checking perms")
return
}
if perms&discordgo.PermissionManageRoles == 0 {
// Not enough permissions to assign roles, skip this guild
return
}
conf, err := GetGeneralConfig(gs.ID)
if err != nil {
logger.WithError(err).Error("Failed retrieivng general config")
return
}
if conf.Role == 0 || conf.OnlyOnJoin {
return
}
// Make sure the role exists
for _, role := range gs.Guild.Roles {
if role.ID == conf.Role {
go processGuild(gs, conf)
return
}
}
// If not remove it
logger.Info("Autorole role dosen't exist, removing config...")
conf.Role = 0
saveGeneral(gs.ID, 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(radix.Cmd(nil, "DEL", KeyProcessing(gs.ID)))
}
}()
membersToGiveRole := make([]int64, 0)
gs.RLock()
now := time.Now()
OUTER:
for _, ms := range gs.Members {
if !ms.MemberSet {
continue
}
if now.Sub(ms.JoinedAt) > time.Duration(config.RequiredDuration)*time.Minute && config.CanAssignTo(ms) {
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(radix.FlatCmd(nil, "SET", KeyProcessing(gs.ID), len(membersToGiveRole)))
}
cntSinceLastRedisUpdate := 0
for i, userID := range membersToGiveRole {
select {
case <-stopChan:
logrus.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
logrus.WithError(err).Info("No perms to add autorole, removing from config")
config.Role = 0
saveGeneral(gs.ID, config)
return
}
logrus.WithError(err).WithField("guild", gs.ID).Error("Failed adding autorole role")
} else {
if setProcessingRedis && cntSinceLastRedisUpdate > 10 {
common.RedisPool.Do(radix.FlatCmd(nil, "SET", KeyProcessing(gs.ID), len(membersToGiveRole)-i))
cntSinceLastRedisUpdate = 0
}
logrus.WithField("guild", gs.ID).WithField("user", userID).Debug("Gave autorole role")
}
}
}
func saveGeneral(guildID int64, config *GeneralConfig) {
err := common.SetRedisJson(KeyGeneral(guildID), config)
if err != nil {
logrus.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 {
logrus.Error("Member not found in add event")
return
}
if config.Role != 0 && config.RequiredDuration < 1 && config.CanAssignTo(ms) {
common.BotSession.GuildMemberRoleAdd(addEvt.GuildID, addEvt.User.ID, config.Role)
}
}
func (conf *GeneralConfig) CanAssignTo(ms *dstate.MemberState) bool {
if len(conf.IgnoreRoles) < 1 && len(conf.RequiredRoles) < 1 {
return true
}
for _, ignoreRole := range conf.IgnoreRoles {
if common.ContainsInt64Slice(ms.Roles, 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(ms.Roles, reqRole) {
return true
}
}
return false
}
return true
}