forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
456 lines (362 loc) · 11.1 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
452
453
454
455
456
package streaming
import (
"fmt"
"github.com/jonas747/discordgo"
"github.com/jonas747/dshardorchestrator"
"github.com/jonas747/dstate"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/bot/eventsystem"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/pubsub"
"github.com/jonas747/yagpdb/common/templates"
"github.com/mediocregopher/radix"
log "github.com/sirupsen/logrus"
"regexp"
"strings"
"sync"
)
func KeyCurrentlyStreaming(gID int64) string { return "currently_streaming:" + discordgo.StrID(gID) }
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ bot.ShardMigrationReceiver = (*Plugin)(nil)
func (p *Plugin) BotInit() {
eventsystem.AddHandler(bot.ConcurrentEventHandler(HandleGuildCreate), eventsystem.EventGuildCreate)
eventsystem.AddHandler(HandlePresenceUpdate, eventsystem.EventPresenceUpdate)
eventsystem.AddHandler(HandleGuildMemberUpdate, eventsystem.EventGuildMemberUpdate)
pubsub.AddHandler("update_streaming", HandleUpdateStreaming, nil)
}
func (p *Plugin) ShardMigrationReceive(evt dshardorchestrator.EventType, data interface{}) {
if evt != bot.EvtGuildState {
return
}
gs := data.(*dstate.GuildState)
go CheckGuildFull(gs, false)
}
// YAGPDB event
func HandleUpdateStreaming(event *pubsub.Event) {
log.Info("Received update streaming event ", event.TargetGuild)
gs := bot.State.Guild(true, event.TargetGuildInt)
if gs == nil {
return
}
gs.UserCacheDel(true, CacheKeyConfig)
CheckGuildFull(gs, true)
}
func CheckGuildFull(gs *dstate.GuildState, fetchMembers bool) {
config, err := GetConfig(gs.ID)
if err != nil {
log.WithError(err).WithField("guild", gs.ID).Error("Failed retrieving streaming config")
}
if !config.Enabled {
return
}
gs.RLock()
var wg sync.WaitGroup
slowCheck := make([]*dstate.MemberState, 0, len(gs.Members))
err = common.RedisPool.Do(radix.WithConn(KeyCurrentlyStreaming(gs.ID), func(conn radix.Conn) error {
for _, ms := range gs.Members {
if !ms.MemberSet || !ms.PresenceSet {
if ms.PresenceSet && fetchMembers {
// If were fetching members, then fetch the missing members
// TODO: Maybe use the gateway request for this?
slowCheck = append(slowCheck, ms)
wg.Add(1)
go func(gID, uID int64) {
bot.GetMember(gID, uID)
wg.Done()
}(gs.ID, ms.ID)
}
continue
}
err = CheckPresence(conn, config, ms, gs)
if err != nil {
log.WithError(err).Error("Error checking presence")
continue
}
}
return nil
}))
gs.RUnlock()
if fetchMembers {
wg.Wait()
} else {
return
}
log.WithField("guild", gs.ID).Info("Starting slowcheck")
gs.RLock()
err = common.RedisPool.Do(radix.WithConn(KeyCurrentlyStreaming(gs.ID), func(conn radix.Conn) error {
for _, ms := range slowCheck {
if !ms.MemberSet || !ms.PresenceSet {
continue
}
err = CheckPresence(conn, config, ms, gs)
if err != nil {
log.WithError(err).Error("Error checking presence")
continue
}
}
return nil
}))
gs.RUnlock()
log.WithField("guild", gs.ID).Info("Done slowcheck")
}
func HandleGuildMemberUpdate(evt *eventsystem.EventData) {
m := evt.GuildMemberUpdate()
gs := bot.State.Guild(true, m.GuildID)
if gs == nil {
return
}
config, err := BotCachedGetConfig(gs)
if err != nil {
log.WithError(err).Error("Failed retrieving streaming config")
return
}
if !config.Enabled {
return
}
ms := gs.Member(true, m.User.ID)
if ms == nil {
log.WithField("guild", m.GuildID).Error("Member not found in state")
return
}
gs.RLock()
defer gs.RUnlock()
if !ms.PresenceSet {
log.WithField("guild", m.GuildID).Warn("Presence not found in state")
return
}
err = CheckPresence(common.RedisPool, config, ms, gs)
if err != nil {
log.WithError(err).Error("Failed checking presence")
}
}
func HandleGuildCreate(evt *eventsystem.EventData) {
g := evt.GuildCreate()
config, err := GetConfig(g.ID)
if err != nil {
log.WithError(err).Error("Failed retrieving streaming config")
return
}
if !config.Enabled {
return
}
gs := bot.State.Guild(true, g.ID)
if gs == nil {
log.WithField("guild", g.ID).Error("Guild not found in state")
return
}
gs.RLock()
defer gs.RUnlock()
err = common.RedisPool.Do(radix.WithConn(KeyCurrentlyStreaming(g.ID), func(conn radix.Conn) error {
for _, ms := range gs.Members {
if !ms.MemberSet || !ms.PresenceSet {
continue
}
err = CheckPresence(conn, config, ms, gs)
if err != nil {
log.WithError(err).Error("Failed checking presence")
}
}
return nil
}))
}
func HandlePresenceUpdate(evt *eventsystem.EventData) {
p := evt.PresenceUpdate()
gs := bot.State.Guild(true, p.GuildID)
if gs == nil {
return
}
config, err := BotCachedGetConfig(gs)
if err != nil {
log.WithError(err).Error("Failed retrieving streaming config")
return
}
if !config.Enabled {
return
}
ms, err := bot.GetMember(p.GuildID, p.User.ID)
if ms == nil || err != nil {
log.WithError(err).WithField("guild", p.GuildID).WithField("user", p.User.ID).Debug("Failed retrieving member")
return
}
gs.RLock()
defer gs.RUnlock()
err = CheckPresence(common.RedisPool, config, ms, gs)
if err != nil {
log.WithError(err).WithField("guild", p.GuildID).Error("Failed checking presence")
}
}
func CheckPresence(client radix.Client, config *Config, ms *dstate.MemberState, gs *dstate.GuildState) error {
if !config.Enabled {
// RemoveStreaming(client, config, gs.ID, p.User.ID, member)
return nil
}
// Now the real fun starts
// Either add or remove the stream
if ms.PresenceStatus != dstate.StatusOffline && ms.PresenceGame != nil && ms.PresenceGame.URL != "" {
// Streaming
if !config.MeetsRequirements(ms) {
RemoveStreaming(client, config, gs.ID, ms)
return nil
}
if config.GiveRole != 0 {
go GiveStreamingRole(ms, config.GiveRole, gs.Guild)
}
// if true, then we were marked now, and not before
var markedNow bool
client.Do(radix.FlatCmd(&markedNow, "SADD", KeyCurrentlyStreaming(gs.ID), ms.ID))
if !markedNow {
// Already marked
return nil
}
// Send the streaming announcement if enabled
if config.AnnounceChannel != 0 && config.AnnounceMessage != "" {
SendStreamingAnnouncement(config, gs, ms)
}
} else {
// Not streaming
RemoveStreaming(client, config, gs.ID, ms)
}
return nil
}
func (config *Config) MeetsRequirements(ms *dstate.MemberState) bool {
// Check if they have the required role
if config.RequireRole != 0 {
if !common.ContainsInt64Slice(ms.Roles, config.RequireRole) {
// Dosen't have required role
return false
}
}
// Check if they have a ignored role
if config.IgnoreRole != 0 {
if common.ContainsInt64Slice(ms.Roles, config.IgnoreRole) {
// We ignore people with this role.. :'(
return false
}
}
if strings.TrimSpace(config.GameRegex) != "" {
gameName := ms.PresenceGame.Details
compiledRegex, err := regexp.Compile(strings.TrimSpace(config.GameRegex))
if err == nil {
// It should be verified before this that its valid
if !compiledRegex.MatchString(gameName) {
return false
}
}
}
if strings.TrimSpace(config.TitleRegex) != "" {
streamTitle := ms.PresenceGame.Name
compiledRegex, err := regexp.Compile(strings.TrimSpace(config.TitleRegex))
if err == nil {
// It should be verified before this that its valid
if !compiledRegex.MatchString(streamTitle) {
return false
}
}
}
return true
}
func RemoveStreaming(client radix.Client, config *Config, guildID int64, ms *dstate.MemberState) {
if ms.MemberSet {
client.Do(radix.FlatCmd(nil, "SREM", KeyCurrentlyStreaming(guildID), ms.ID))
go RemoveStreamingRole(ms, config.GiveRole, guildID)
} else {
// Was not streaming before if we removed 0 elements
var removed bool
client.Do(radix.FlatCmd(&removed, "SREM", KeyCurrentlyStreaming(guildID), ms.ID))
if removed && config.GiveRole != 0 {
go common.BotSession.GuildMemberRoleRemove(guildID, ms.ID, config.GiveRole)
}
}
}
func SendStreamingAnnouncement(config *Config, guild *dstate.GuildState, ms *dstate.MemberState) {
// Only send one announcment every 1 hour
var resp string
key := fmt.Sprintf("streaming_announcement_sent:%d:%d", guild.ID, ms.ID)
err := common.RedisPool.Do(radix.Cmd(&resp, "SET", key, "1", "EX", "3600", "NX"))
if err != nil {
log.WithError(err).Error("failed setting streaming announcment cooldown")
return
}
if resp != "OK" {
log.Info("streaming announcment cooldown: ", ms.ID)
return
}
// make sure the channel exists
foundChannel := false
for _, v := range guild.Channels {
if v.ID == config.AnnounceChannel {
foundChannel = true
}
}
// unknown channel, disable announcements
if !foundChannel {
config.AnnounceChannel = 0
config.Save(guild.ID)
log.WithField("guild", guild.ID).WithField("channel", config.AnnounceChannel).Warn("Channel not found in state, not sending streaming announcement")
return
}
ctx := templates.NewContext(guild, nil, ms)
ctx.Data["URL"] = common.EscapeSpecialMentions(ms.PresenceGame.URL)
ctx.Data["url"] = common.EscapeSpecialMentions(ms.PresenceGame.URL)
ctx.Data["Game"] = ms.PresenceGame.Details
ctx.Data["StreamTitle"] = ms.PresenceGame.Name
guild.RUnlock()
out, err := ctx.Execute(config.AnnounceMessage)
guild.RLock()
if err != nil {
log.WithError(err).WithField("guild", guild.ID).Warn("Failed executing template")
return
}
m, err := common.BotSession.ChannelMessageSend(config.AnnounceChannel, out)
if err == nil && ctx.DelResponse {
templates.MaybeScheduledDeleteMessage(guild.ID, config.AnnounceChannel, m.ID, ctx.DelResponseDelay)
}
}
func GiveStreamingRole(ms *dstate.MemberState, role int64, guild *discordgo.Guild) {
if role == 0 {
return
}
err := common.AddRoleDS(ms, role)
if err != nil {
if common.IsDiscordErr(err, discordgo.ErrCodeMissingPermissions, discordgo.ErrCodeUnknownRole, discordgo.ErrCodeMissingAccess) {
DisableStreamingRole(guild.ID)
}
log.WithError(err).WithField("guild", guild.ID).WithField("user", ms.ID).Error("Failed adding streaming role")
common.RedisPool.Do(radix.FlatCmd(nil, "SREM", KeyCurrentlyStreaming(guild.ID), ms.ID))
}
}
func RemoveStreamingRole(ms *dstate.MemberState, role int64, guildID int64) {
if role == 0 {
return
}
err := common.RemoveRoleDS(ms, role)
if err != nil {
log.WithError(err).WithField("guild", guildID).WithField("user", ms.ID).WithField("role", role).Error("Failed removing streaming role")
if common.IsDiscordErr(err, discordgo.ErrCodeMissingPermissions, discordgo.ErrCodeUnknownRole, discordgo.ErrCodeMissingAccess) {
DisableStreamingRole(guildID)
}
}
}
func DisableStreamingRole(guildID int64) {
log.WithField("guild", guildID).Warn("Disabling streaming role for server because of misssing permissions or unknown role")
conf, err := GetConfig(guildID)
if err != nil {
log.WithField("guild", guildID).WithError(err).Error("Failed retrieving streaming config, when there should be one?")
return
}
conf.GiveRole = 0
conf.Save(guildID)
}
type CacheKey int
const (
CacheKeyConfig CacheKey = iota
)
func BotCachedGetConfig(gs *dstate.GuildState) (*Config, error) {
v, err := gs.UserCacheFetch(true, CacheKeyConfig, func() (interface{}, error) {
return GetConfig(gs.ID)
})
if err != nil {
return nil, err
}
return v.(*Config), nil
}