forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
314 lines (263 loc) · 7.36 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
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.v2/redis"
"github.com/sirupsen/logrus"
"sync"
"time"
)
func (p *Plugin) InitBot() {
commands.AddRootCommands(roleCommands...)
eventsystem.AddHandler(bot.RedisWrapper(OnMemberJoin), eventsystem.EventGuildMemberAdd)
eventsystem.AddHandler(HandlePresenceUpdate, eventsystem.EventPresenceUpdate)
}
var roleCommands = []*commands.YAGCommand{
&commands.YAGCommand{
CmdCategory: commands.CategoryDebug,
Name: "roledbg",
Description: "Debug debug debug autorole assignment",
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
client := parsed.Context().Value(commands.CtxKeyRedisClient).(*redis.Client)
processing, _ := client.Cmd("GET", KeyProcessing(parsed.GS.ID())).Int()
return fmt.Sprintf("Processing %d users.", processing), nil
},
},
}
var _ bot.BotStarterHandler = (*Plugin)(nil)
func (p *Plugin) StartBot() {
go runDurationChecker()
pubsub.AddHandler("autorole_stop_processing", HandleUpdateAutomodRules, nil)
}
// Stop updating
func HandleUpdateAutomodRules(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.Member != nil {
gs.RUnlock()
return
}
gs.RUnlock()
client := common.MustGetRedisClient()
defer common.RedisPool.Put(client)
config, err := GetGeneralConfig(client, 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
)
func stopProcessing(guildID int64) {
processingLock.Lock()
if c, ok := processingGuilds[guildID]; ok {
go func() {
select {
case c <- true:
default:
return
}
}()
}
processingLock.Unlock()
}
func runDurationChecker() {
client := common.MustGetRedisClient()
defer common.RedisPool.Put(client)
ticker := time.NewTicker(time.Minute)
state := bot.State
for {
<-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(client, g)
}
}
}
func checkGuild(client *redis.Client, 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, bot.State.User(true).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(client, 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(client, 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 client *redis.Client
// Reset the processing state
defer func() {
processingLock.Lock()
delete(processingGuilds, gs.ID())
processingLock.Unlock()
if client != nil {
client.Cmd("DEL", KeyProcessing(gs.ID()))
common.RedisPool.Put(client)
}
}()
membersToGiveRole := make([]int64, 0)
gs.RLock()
now := time.Now()
OUTER:
for _, ms := range gs.Members {
if ms.Member == nil {
continue
}
parsedJoined, err := discordgo.Timestamp(ms.Member.JoinedAt).Parse()
if err != nil {
logrus.WithError(err).Warn("Failed parsing join timestamp")
continue
}
if now.Sub(parsedJoined) > time.Duration(config.RequiredDuration)*time.Minute && config.CanAssignTo(ms.Member) {
for _, r := range ms.Member.Roles {
if r == config.Role {
continue OUTER
}
}
membersToGiveRole = append(membersToGiveRole, ms.ID())
}
}
gs.RUnlock()
if len(membersToGiveRole) > 10 {
var err error
client, err = common.RedisPool.Get()
if err != nil {
logrus.WithError(err).Error("Failed retrieving redis client from pool")
return
}
client.Cmd("SET", KeyProcessing(gs.ID()), len(membersToGiveRole))
}
for i, userID := range membersToGiveRole {
select {
case <-stopChan:
logrus.WithField("guild", gs.ID()).Info("Stopping autorole assigning...")
return
default:
}
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(client, gs.ID(), config)
return
}
logrus.WithError(err).WithField("guild", gs.ID()).Error("Failed adding autorole role")
} else {
if client != nil {
client.Cmd("SET", KeyProcessing(gs.ID()), len(membersToGiveRole)-i)
}
logrus.WithField("guild", gs.ID()).WithField("user", userID).Debug("Gave autorole role")
}
}
}
func saveGeneral(client *redis.Client, guildID int64, config *GeneralConfig) {
if client == nil {
client = common.MustGetRedisClient()
defer common.RedisPool.Put(client)
}
err := common.SetRedisJson(client, KeyGeneral(guildID), config)
if err != nil {
logrus.WithError(err).Error("Failed saving autorole config")
}
}
func OnMemberJoin(evt *eventsystem.EventData) {
addEvt := evt.GuildMemberAdd
client := bot.ContextRedis(evt.Context())
config, err := GetGeneralConfig(client, addEvt.GuildID)
if err != nil {
return
}
if config.Role != 0 && config.RequiredDuration < 1 && config.CanAssignTo(addEvt.Member) {
common.BotSession.GuildMemberRoleAdd(addEvt.GuildID, addEvt.User.ID, config.Role)
}
}
func (conf *GeneralConfig) CanAssignTo(member *discordgo.Member) bool {
if len(conf.IgnoreRoles) < 1 && len(conf.RequiredRoles) < 1 {
return true
}
for _, ignoreRole := range conf.IgnoreRoles {
if common.ContainsInt64Slice(member.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(member.Roles, reqRole) {
return true
}
}
return false
}
return true
}