feat(xp): update role after removing all old xp

This commit is contained in:
Anhgelus Morhtuuzh 2025-05-13 18:06:17 +02:00
parent eaf9fa51cd
commit f2fbf1db92
Signed by: anhgelus
GPG key ID: CAD341EFA92DDDE5
2 changed files with 45 additions and 4 deletions

View file

@ -8,6 +8,7 @@ import (
"github.com/bwmarrin/discordgo"
"slices"
"sync"
"time"
)
func onNewLevel(dg *discordgo.Session, m *discordgo.Member, level uint) {
@ -55,6 +56,31 @@ func (c *Copaing) OnNewLevel(dg *discordgo.Session, level uint) {
func PeriodicReducer(dg *discordgo.Session) {
wg := &sync.WaitGroup{}
var cs []*Copaing
if err := gokord.DB.Find(&cs).Error; err != nil {
utils.SendAlert("user/level.go - Fetching all copaings", err.Error())
return
}
cxps := make([]*cXP, len(cs))
for i, c := range cs {
if i%10 == 9 {
wg.Wait() // prevents spamming the DB
}
wg.Add(1)
go func() {
defer wg.Done()
xp, err := c.GetXP()
if err != nil {
utils.SendAlert("user/level.go - Getting XP", err.Error(), "copaing_id", c.ID, "guild_id", c.GuildID)
xp = 0
}
cxps[i] = &cXP{
Cxp: xp,
Copaing: c,
}
}()
}
wg.Wait()
for _, g := range dg.State.Guilds {
wg.Add(1)
go func() {
@ -71,5 +97,20 @@ func PeriodicReducer(dg *discordgo.Session) {
}()
}
wg.Wait()
for i, c := range cxps {
if i%50 == 49 {
utils.SendDebug("Sleeping...")
time.Sleep(15 * time.Second) // prevents spamming the API
}
oldXp := c.GetXP()
xp, err := c.ToCopaing().GetXP()
if err != nil {
utils.SendAlert("user/level.go - Getting XP", err.Error(), "guild_id", c.ID, "discord_id", c.DiscordID)
continue
}
if exp.Level(oldXp) != exp.Level(xp) {
c.OnNewLevel(dg, exp.Level(xp))
}
}
utils.SendDebug("Periodic reduce finished", "len(guilds)", len(dg.State.Guilds))
}