-
Notifications
You must be signed in to change notification settings - Fork 940
/
plugin_bot.go
779 lines (645 loc) · 22.9 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
package rsvp
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/jonas747/dcmd/v4"
"github.com/jonas747/discordgo/v2"
"github.com/jonas747/dstate/v4"
"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/scheduledevents2"
eventModels "github.com/jonas747/yagpdb/common/scheduledevents2/models"
"github.com/jonas747/yagpdb/rsvp/models"
"github.com/jonas747/yagpdb/timezonecompanion"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
)
var _ bot.BotInitHandler = (*Plugin)(nil)
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLastLegacy(p, p.handleMessageCreate, eventsystem.EventMessageCreate)
eventsystem.AddHandlerAsyncLastLegacy(p, p.handleMessageReactionAdd, eventsystem.EventMessageReactionAdd)
scheduledevents2.RegisterHandler("rsvp_update_session", int64(0), p.handleScheduledUpdate)
}
var _ commands.CommandProvider = (*Plugin)(nil)
func (p *Plugin) AddCommands() {
catEvents := &dcmd.Category{
Name: "Events",
Description: "Event commands",
HelpEmoji: "🎟",
EmbedColor: 0x42b9f4,
}
container, _ := commands.CommandSystem.Root.Sub("events", "event")
container.NotFound = commands.CommonContainerNotFoundHandler(container, "")
cmdCreateEvent := &commands.YAGCommand{
CmdCategory: catEvents,
Name: "Create",
Aliases: []string{"new", "make"},
Description: "Creates an event, You will be led through an interactive setup",
Plugin: p,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
count, err := models.RSVPSessions(models.RSVPSessionWhere.GuildID.EQ(parsed.GuildData.GS.ID)).CountG(parsed.Context())
if err != nil {
return nil, err
}
if count > 25 {
return "Max 25 active events at a time", nil
}
p.setupSessionsMU.Lock()
for _, v := range p.setupSessions {
if v.SetupChannel == parsed.ChannelID {
p.setupSessionsMU.Unlock()
return "Already a setup process going on in this channel, if you want to exit it type `exit`, admins can force cancel setups with `events stopsetup`", nil
}
}
var msgID int64
setupMessages := []int64{}
if parsed.TraditionalTriggerData != nil {
msgID = parsed.TraditionalTriggerData.Message.ID
setupMessages = []int64{msgID}
}
setupSession := &SetupSession{
CreatedOnMessageID: msgID,
GuildID: parsed.GuildData.GS.ID,
SetupChannel: parsed.ChannelID,
AuthorID: parsed.Author.ID,
LastAction: time.Now(),
plugin: p,
setupMessages: setupMessages,
stopCH: make(chan bool),
}
go setupSession.loopCheckActive()
p.setupSessions = append(p.setupSessions, setupSession)
p.setupSessionsMU.Unlock()
setupSession.mu.Lock()
setupSession.sendInitialMessage(parsed, "Started interactive setup:\nWhat channel should i put the event embed in? (type `this` or `here` for the current one)")
setupSession.mu.Unlock()
return "", nil
},
}
cmdEdit := &commands.YAGCommand{
CmdCategory: catEvents,
Name: "Edit",
Description: "Edits an event",
Plugin: p,
RequireDiscordPerms: []int64{discordgo.PermissionManageServer, discordgo.PermissionManageMessages},
Arguments: []*dcmd.ArgDef{
{Name: "ID", Type: dcmd.Int},
},
RequiredArgs: 1,
ArgSwitches: []*dcmd.ArgDef{
{Name: "title", Help: "Change the title of the event", Type: dcmd.String},
{Name: "time", Help: "Change the start time of the event", Type: dcmd.String},
{Name: "max", Help: "Change max participants", Type: dcmd.Int},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
m, err := models.RSVPSessions(
models.RSVPSessionWhere.GuildID.EQ(parsed.GuildData.GS.ID),
models.RSVPSessionWhere.LocalID.EQ(parsed.Args[0].Int64()),
qm.Load("RSVPSessionsMessageRSVPParticipants", qm.OrderBy("marked_as_participating_at asc")),
).OneG(parsed.Context())
if err != nil {
if err == sql.ErrNoRows {
return "Unknown event", nil
}
return nil, err
}
if parsed.Switch("title").Value != nil {
m.Title = parsed.Switch("title").Str()
}
if parsed.Switch("max").Value != nil {
m.MaxParticipants = parsed.Switch("max").Int()
}
timeChanged := false
if parsed.Switch("time").Value != nil {
registeredTimezone := timezonecompanion.GetUserTimezone(parsed.Author.ID)
if registeredTimezone == nil || UTCRegex.MatchString(parsed.Switch("time").Str()) {
registeredTimezone = time.UTC
}
t, err := dateParser.Parse(parsed.Switch("time").Str(), time.Now().In(registeredTimezone))
if err != nil || t == nil {
return "failed parsing the date; " + err.Error(), nil
}
m.StartsAt = t.Time
timeChanged = true
}
_, err = m.UpdateG(parsed.Context(), boil.Infer())
if err != nil {
return nil, err
}
if timeChanged {
_, err := eventModels.ScheduledEvents(qm.Where("event_name='rsvp_update_session' AND guild_id = ? AND data::text::bigint = ? AND processed = false", parsed.GuildData.GS.ID, m.MessageID)).DeleteAll(parsed.Context(), common.PQ)
if err != nil {
return nil, err
}
err = scheduledevents2.ScheduleEvent("rsvp_update_session", m.GuildID, NextUpdateTime(m), m.MessageID)
if err != nil {
return nil, err
}
}
UpdateEventEmbed(m)
return fmt.Sprintf("Updated #%d to '%s' - with max %d participants, starting at: %s", m.LocalID, m.Title, m.MaxParticipants, m.StartsAt.Format("02 Jan 2006 15:04 MST")), nil
},
}
cmdList := &commands.YAGCommand{
CmdCategory: catEvents,
Name: "List",
Aliases: []string{"ls"},
Description: "Lists all events in this server",
RequireDiscordPerms: []int64{discordgo.PermissionManageServer, discordgo.PermissionManageMessages},
Plugin: p,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
events, err := models.RSVPSessions(models.RSVPSessionWhere.GuildID.EQ(parsed.GuildData.GS.ID), qm.OrderBy("starts_at asc")).AllG(parsed.Context())
if err != nil {
return nil, err
}
if len(events) < 1 {
return "No active events on this server.", nil
}
var output strings.Builder
for _, v := range events {
timeUntil := v.StartsAt.Sub(time.Now())
humanized := common.HumanizeDuration(common.DurationPrecisionMinutes, timeUntil)
output.WriteString(fmt.Sprintf("#%2d: **%s** in `%s` https://ptb.discordapp.com/channels/%d/%d/%d\n",
v.LocalID, v.Title, humanized, parsed.GuildData.GS.ID, v.ChannelID, v.MessageID))
}
return output.String(), nil
},
}
cmdDel := &commands.YAGCommand{
CmdCategory: catEvents,
Name: "Delete",
Aliases: []string{"rm", "del"},
Description: "Deletes an event, specify the event ID of the event you wanna delete",
RequireDiscordPerms: []int64{discordgo.PermissionManageServer, discordgo.PermissionManageMessages},
RequiredArgs: 1,
Plugin: p,
Arguments: []*dcmd.ArgDef{
{Name: "ID", Type: dcmd.Int},
},
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
m, err := models.RSVPSessions(
models.RSVPSessionWhere.GuildID.EQ(parsed.GuildData.GS.ID),
models.RSVPSessionWhere.LocalID.EQ(parsed.Args[0].Int64()),
).OneG(parsed.Context())
if err != nil {
if err == sql.ErrNoRows {
return "Unknown event", nil
}
return nil, err
}
_, err = m.DeleteG(parsed.Context())
if err != nil {
return nil, err
}
return "Deleted `" + m.Title + "`", nil
},
}
cmdStopSetup := &commands.YAGCommand{
CmdCategory: catEvents,
Name: "StopSetup",
Aliases: []string{"cancelsetup"},
Description: "Force cancels the current setup session in this channel",
RequireDiscordPerms: []int64{discordgo.PermissionManageServer},
Plugin: p,
RunFunc: func(parsed *dcmd.Data) (interface{}, error) {
p.setupSessionsMU.Lock()
for _, v := range p.setupSessions {
if v.SetupChannel == parsed.ChannelID {
p.setupSessionsMU.Unlock()
go v.remove()
return "Canceled the current setup in this channel", nil
}
}
p.setupSessionsMU.Unlock()
return "No ongoing setup in the current channel.", nil
},
}
container.AddCommand(cmdCreateEvent, cmdCreateEvent.GetTrigger())
container.AddCommand(cmdEdit, cmdEdit.GetTrigger())
container.AddCommand(cmdList, cmdList.GetTrigger())
container.AddCommand(cmdDel, cmdDel.GetTrigger())
container.AddCommand(cmdStopSetup, cmdStopSetup.GetTrigger())
container.Description = "Manage events"
commands.RegisterSlashCommandsContainer(container, true, func(gs *dstate.GuildSet) ([]int64, error) {
return nil, nil
})
}
type RolesRunFunc func(gs *dstate.GuildSet) ([]int64, error)
func (p *Plugin) handleMessageCreate(evt *eventsystem.EventData) {
m := evt.MessageCreate()
if m.Author == nil {
return
}
p.setupSessionsMU.Lock()
defer p.setupSessionsMU.Unlock()
for _, v := range p.setupSessions {
if v.SetupChannel == m.ChannelID && m.Author.ID == v.AuthorID {
go v.handleMessage(m.Message)
break
}
}
}
func UpdateEventEmbed(m *models.RSVPSession) error {
usersToFetch := []int64{
m.AuthorID,
}
var participants []*models.RSVPParticipant
if m.R != nil {
for _, v := range m.R.RSVPSessionsMessageRSVPParticipants {
usersToFetch = append(usersToFetch, v.UserID)
}
participants = m.R.RSVPSessionsMessageRSVPParticipants
}
fetchedMembers, _ := bot.GetMembers(m.GuildID, usersToFetch...)
author := findUser(fetchedMembers, m.AuthorID)
embed := &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{
Name: author.Username,
IconURL: author.AvatarURL("64"),
},
Title: fmt.Sprintf("#%d: %s", m.LocalID, m.Title),
Timestamp: m.StartsAt.Format(time.RFC3339),
Color: 0x518eef,
Footer: &discordgo.MessageEmbedFooter{
Text: "Event starts ",
},
}
timeUntil := m.StartsAt.Sub(time.Now())
timeUntilStr := common.HumanizeDuration(common.DurationPrecisionMinutes, timeUntil)
if timeUntil > 0 {
timeUntilStr = "Starts in `" + timeUntilStr + "`"
} else {
timeUntilStr = "Started `" + timeUntilStr + "` ago"
}
UTCTime := m.StartsAt.UTC()
const timeFormat = "02 Jan 2006 15:04"
embed.Description = timeUntilStr
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Times",
Value: fmt.Sprintf("UTC: `%s`\nLook at the bottom of this message to see when the event starts in your local time.",
UTCTime.Format(timeFormat)),
}, &discordgo.MessageEmbedField{
Name: "Reactions usage",
Value: "React to mark you as a participant, undecided, or not joining",
})
participantsEmbed := &discordgo.MessageEmbedField{
Name: "Participants",
Inline: false,
Value: "```\n",
}
waitingListField := &discordgo.MessageEmbedField{
Name: "🕐 Waiting list",
Inline: false,
Value: "```\n",
}
addedParticipants := 0
numWaitingList := 0
numParticipantsShown := 0
numWaitingListShown := 0
waitingListHitMax := false
participantsHitMax := false
for _, v := range participants {
if v.JoinState != int16(ParticipantStateJoining) && v.JoinState != int16(ParticipantStateWaitlist) {
continue
}
user := findUser(fetchedMembers, v.UserID)
if (addedParticipants >= m.MaxParticipants && m.MaxParticipants > 0) || v.JoinState == int16(ParticipantStateWaitlist) {
// On the waiting list
if !waitingListHitMax {
// we hit the max limit so add them to the waiting list instead
toAdd := user.Username + "#" + user.Discriminator + "\n"
if utf8.RuneCountInString(toAdd)+utf8.RuneCountInString(waitingListField.Value) >= 990 {
waitingListHitMax = true
} else {
waitingListField.Value += toAdd
numWaitingListShown++
}
}
numWaitingList++
continue
}
if !participantsHitMax {
toAdd := user.Username + "#" + user.Discriminator + "\n"
if utf8.RuneCountInString(toAdd)+utf8.RuneCountInString(participantsEmbed.Value) > 990 {
participantsHitMax = true
} else {
participantsEmbed.Value += toAdd
numParticipantsShown++
}
}
addedParticipants++
}
// Finalize the participants field
if participantsEmbed.Value == "```\n" {
participantsEmbed.Value += "None"
} else if participantsHitMax {
participantsEmbed.Value += fmt.Sprintf("+ %d users", addedParticipants-numParticipantsShown)
}
participantsEmbed.Value += "```"
// Finalize the waiting list field
waitingListField.Name += " (" + strconv.Itoa(numWaitingList) + ")"
if waitingListField.Value == "```\n" {
waitingListField.Value += "None"
} else if waitingListHitMax {
waitingListField.Value += fmt.Sprintf("+ %d users", numWaitingList-numWaitingListShown)
}
waitingListField.Value += "```"
if m.MaxParticipants > 0 {
participantsEmbed.Name += fmt.Sprintf(" (%d / %d)", addedParticipants, m.MaxParticipants)
} else {
participantsEmbed.Name += fmt.Sprintf("(%d)", addedParticipants)
}
// The undecided and maybe people
undecidedField := ParticipantField(ParticipantStateMaybe, participants, fetchedMembers, "❔ Undecided")
// notJoiningField := ParticipantField(ParticipantStateNotJoining, participants, participantUsers, "Not joining")
embed.Fields = append(embed.Fields, participantsEmbed)
// hide waiting list if theres no limit
if m.MaxParticipants > 0 {
embed.Fields = append(embed.Fields, waitingListField)
}
embed.Fields = append(embed.Fields, undecidedField)
_, err := common.BotSession.ChannelMessageEditEmbed(m.ChannelID, m.MessageID, embed)
return err
}
func findUser(members []*dstate.MemberState, target int64) *discordgo.User {
for _, v := range members {
if v.User.ID == target {
return &v.User
}
}
return &discordgo.User{
Username: "Unknown (" + strconv.FormatInt(target, 10) + ")",
ID: target,
}
}
func ParticipantField(state ParticipantState, participants []*models.RSVPParticipant, users []*dstate.MemberState, name string) *discordgo.MessageEmbedField {
field := &discordgo.MessageEmbedField{
Name: name,
Inline: true,
Value: "```\n",
}
count := 0
countShown := 0
reachedMax := false
for _, v := range participants {
user := findUser(users, v.UserID)
if v.JoinState == int16(state) {
if !reachedMax {
toAdd := user.Username + "#" + user.Discriminator + "\n"
if utf8.RuneCountInString(toAdd)+utf8.RuneCountInString(field.Value) >= 100 {
reachedMax = true
} else {
field.Value += toAdd
countShown++
}
}
count++
}
}
if count == 0 {
field.Value += "None\n"
} else {
field.Name += " (" + strconv.Itoa(count) + ")"
if reachedMax {
field.Value += fmt.Sprintf("+ %d users", count-countShown)
}
}
field.Value += "```"
return field
}
func NextUpdateTime(m *models.RSVPSession) time.Time {
timeUntil := m.StartsAt.Sub(time.Now())
if timeUntil < time.Second*15 {
return time.Now().Add(time.Second * 1)
} else if timeUntil < time.Minute*2 {
return time.Now().Add(time.Second * 10)
} else if timeUntil < time.Minute*15 {
return time.Now().Add(time.Minute)
} else {
return time.Now().Add(time.Minute * 10)
}
}
func (p *Plugin) handleScheduledUpdate(evt *eventModels.ScheduledEvent, data interface{}) (retry bool, err error) {
mID := *(data.(*int64))
m, err := models.RSVPSessions(models.RSVPSessionWhere.MessageID.EQ(mID), qm.Load("RSVPSessionsMessageRSVPParticipants", qm.OrderBy("marked_as_participating_at asc"))).OneG(context.Background())
if err != nil {
return false, err
}
err = UpdateEventEmbed(m)
if err != nil {
code, _ := common.DiscordError(err)
if code == discordgo.ErrCodeUnknownMessage || code == discordgo.ErrCodeUnknownChannel {
m.DeleteG(context.Background())
return false, nil
}
return scheduledevents2.CheckDiscordErrRetry(err), err
}
if m.StartsAt.Sub(time.Now()) < 1 {
p.startEvent(m)
return false, nil
} else if m.StartsAt.Sub(time.Now()) < time.Minute*30 && !m.SentReminders && m.SendReminders {
m.SentReminders = true
_, err := m.UpdateG(context.Background(), boil.Whitelist("sent_reminders"))
if err != nil {
return true, err
}
p.sendReminders(m, "Event is starting in less than 30 minutes!", "The event you signed up for: **"+m.Title+"** is starting soon!")
}
err = scheduledevents2.ScheduleEvent("rsvp_update_session", evt.GuildID, NextUpdateTime(m), m.MessageID)
return false, err
}
type ParticipantState int16
const (
ParticipantStateJoining ParticipantState = 1
ParticipantStateMaybe ParticipantState = 2
ParticipantStateNotJoining ParticipantState = 3
ParticipantStateWaitlist ParticipantState = 4
)
func (p *Plugin) startEvent(m *models.RSVPSession) error {
p.sendReminders(m, "Event starting now!", "The event you signed up for: **"+m.Title+"** is starting now!")
common.BotSession.MessageReactionsRemoveAll(m.ChannelID, m.MessageID)
_, err := m.DeleteG(context.Background())
return err
}
func (p *Plugin) sendReminders(m *models.RSVPSession, title, desc string) {
serverName := strconv.FormatInt(m.GuildID, 10)
gs := bot.State.GetGuild(m.GuildID)
if gs != nil {
serverName = gs.Name
}
for _, v := range m.R.RSVPSessionsMessageRSVPParticipants {
if v.JoinState != int16(ParticipantStateJoining) && v.JoinState != int16(ParticipantStateMaybe) {
continue
}
err := bot.SendDMEmbed(v.UserID, &discordgo.MessageEmbed{
Title: title,
Description: desc,
Footer: &discordgo.MessageEmbedFooter{
Text: "From the server: " + serverName,
},
})
if err != nil {
logger.WithError(err).WithField("guild", m.GuildID).Error("failed sending reminder")
}
}
}
func (p *Plugin) handleMessageReactionAdd(evt *eventsystem.EventData) {
ra := evt.MessageReactionAdd()
if ra.UserID == common.BotUser.ID {
return
}
joining := ra.Emoji.Name == EmojiJoining
notJoining := ra.Emoji.Name == EmojiNotJoining
maybe := ra.Emoji.Name == EmojiMaybe
waitlist := ra.Emoji.Name == EmojiWaitlist
if !joining && !notJoining && !maybe && !waitlist {
return
}
m, err := models.RSVPSessions(models.RSVPSessionWhere.MessageID.EQ(ra.MessageID), qm.Load("RSVPSessionsMessageRSVPParticipants", qm.OrderBy("marked_as_participating_at asc"))).OneG(context.Background())
if err != nil {
if err == sql.ErrNoRows {
return
}
logger.WithError(err).WithField("guild", ra.GuildID).Error("failed retrieving RSVP session")
return
}
foundExisting := false
var participant *models.RSVPParticipant
for _, v := range m.R.RSVPSessionsMessageRSVPParticipants {
if v.UserID == ra.UserID {
participant = v
foundExisting = true
break
}
}
if !foundExisting {
participant = &models.RSVPParticipant{
RSVPSessionsMessageID: m.MessageID,
UserID: ra.UserID,
GuildID: ra.GuildID,
}
}
// common.BotSession.MessageReactionRemove(ra.ChannelID, ra.MessageID, ra.Emoji.APIName(), ra.UserID)
if joining {
if participant.JoinState == int16(ParticipantStateJoining) {
// already at this state
return
}
participant.JoinState = int16(ParticipantStateJoining)
participant.MarkedAsParticipatingAt = time.Now()
} else if maybe {
if participant.JoinState == int16(ParticipantStateMaybe) {
// already at this state
return
}
participant.JoinState = int16(ParticipantStateMaybe)
participant.MarkedAsParticipatingAt = time.Now()
} else if waitlist {
if participant.JoinState == int16(ParticipantStateWaitlist) {
// already at this state
return
}
participant.JoinState = int16(ParticipantStateWaitlist)
participant.MarkedAsParticipatingAt = time.Now()
} else if notJoining {
participant.JoinState = int16(ParticipantStateNotJoining)
}
if foundExisting {
_, err = participant.UpdateG(context.Background(), boil.Infer())
} else {
err = m.AddRSVPSessionsMessageRSVPParticipantsG(context.Background(), true, participant)
}
if err != nil {
logger.WithError(err).WithField("guild", ra.GuildID).Error("failed updating rsvp participant")
}
reactionsToRemove := []string{}
if !joining {
reactionsToRemove = append(reactionsToRemove, EmojiJoining)
}
if !notJoining {
reactionsToRemove = append(reactionsToRemove, EmojiNotJoining)
}
if !maybe {
reactionsToRemove = append(reactionsToRemove, EmojiMaybe)
}
if !waitlist {
reactionsToRemove = append(reactionsToRemove, EmojiWaitlist)
}
go removeReactions(ra.ChannelID, ra.MessageID, ra.UserID, reactionsToRemove...)
updatingSessiosMU.Lock()
for _, v := range updatingSessionEmbeds {
if v.ID == m.MessageID {
v.lastModelUpdate = time.Now()
updatingSessiosMU.Unlock()
return
}
}
s := &UpdatingSession{
ID: m.MessageID,
GuildID: m.GuildID,
lastModelUpdate: time.Now(),
}
updatingSessionEmbeds = append(updatingSessionEmbeds, s)
go s.run()
updatingSessiosMU.Unlock()
}
func removeReactions(channelID, messageID, userID int64, emojis ...string) {
for _, v := range emojis {
err := common.BotSession.MessageReactionRemove(channelID, messageID, v, userID)
if err != nil {
logger.WithError(err).Error("failed removing reaction")
}
}
}
var (
updatingSessionEmbeds []*UpdatingSession
updatingSessiosMU sync.Mutex
)
// Spam update protection, forces 5 seconds between each update
type UpdatingSession struct {
ID int64
GuildID int64
lastModelUpdate time.Time
lastEmbedUpdate time.Time
}
func (u *UpdatingSession) run() {
for {
u.update()
time.Sleep(time.Second * 5)
updatingSessiosMU.Lock()
if u.lastEmbedUpdate.After(u.lastModelUpdate) || u.lastEmbedUpdate.Equal(u.lastModelUpdate) {
// remove, no need for further updates
for i, v := range updatingSessionEmbeds {
if v == u {
updatingSessionEmbeds = append(updatingSessionEmbeds[:i], updatingSessionEmbeds[i+1:]...)
break
}
}
updatingSessiosMU.Unlock()
return
}
updatingSessiosMU.Unlock()
}
}
func (u *UpdatingSession) update() {
updatingSessiosMU.Lock()
u.lastEmbedUpdate = time.Now()
updatingSessiosMU.Unlock()
m, err := models.RSVPSessions(models.RSVPSessionWhere.MessageID.EQ(u.ID), qm.Load("RSVPSessionsMessageRSVPParticipants", qm.OrderBy("marked_as_participating_at asc"))).OneG(context.Background())
if err != nil {
logger.WithError(err).WithField("guild", u.GuildID).Error("failed retreiving rsvp")
return
}
err = UpdateEventEmbed(m)
if err != nil {
logger.WithError(err).WithField("guild", u.GuildID).Error("failed retreiving rsvp")
}
}