diff --git a/Dockerfile b/Dockerfile index ca8d3f8..7ebb090 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM docker.io/golang:1.23-alpine +FROM docker.io/golang:1.24-alpine WORKDIR /app @@ -9,5 +9,6 @@ COPY . . RUN go mod tidy && go build -o app . ENV TOKEN="" +ENV TZ="Europe/Paris" CMD ./app -token $TOKEN diff --git a/PRIVACY.md b/PRIVACY.md index 87f3f69..eb60bac 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -32,9 +32,9 @@ En tant qu'utilisateur, vous avez le droit de : - avoir accès à vos données sauvegardées - modifier ces données -Pour exercer vos droits concernant l'accès aux données ou à la modification des données, contacter me@anhgelus.world. +Pour exercer vos droits concernant l'accès aux données ou à la modification des données, contactez me@anhgelus.world. -Concernant la suppression des données, entraîne de facto une remise à zéro de votre profile sur un serveur, contacter le propriétaire du serveur. +La suppression des données entraîne de facto une remise à zéro de votre profile sur un serveur, contactez le propriétaire du serveur pour exercer ce droit. Concernant la suppression intégrale des données, contacter me@anhgelus.world. diff --git a/README.md b/README.md index fe7bc74..7fa11a5 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,11 @@ Bot for the private server Discord "Les Copaings" ## Features -- Levels & XP +- Levels & CopaingXPs - Roles management - Purge command -### XP +### CopaingXPs Functions: - $xp-message(x;y) = 0.025 x^{1.25}\sqrt{y}+1$ where $x$ is the length of the message and $y$ is the diversity of the diff --git a/commands/config.go b/commands/config.go index 1e680c7..a3857c6 100644 --- a/commands/config.go +++ b/commands/config.go @@ -5,7 +5,7 @@ import ( "github.com/anhgelus/gokord" "github.com/anhgelus/gokord/utils" "github.com/anhgelus/les-copaings-bot/config" - "github.com/anhgelus/les-copaings-bot/xp" + "github.com/anhgelus/les-copaings-bot/exp" "github.com/bwmarrin/discordgo" "strings" ) @@ -17,9 +17,9 @@ func ConfigShow(s *discordgo.Session, i *discordgo.InteractionCreate) { l := len(cfg.XpRoles) - 1 for i, r := range cfg.XpRoles { if i == l { - roles += fmt.Sprintf("> Niveau %d - <@&%s>", xp.Level(r.XP), r.RoleID) + roles += fmt.Sprintf("> Niveau %d - <@&%s>", exp.Level(r.XP), r.RoleID) } else { - roles += fmt.Sprintf("> Niveau %d - <@&%s>\n", xp.Level(r.XP), r.RoleID) + roles += fmt.Sprintf("> Niveau %d - <@&%s>\n", exp.Level(r.XP), r.RoleID) } } if len(roles) == 0 { @@ -38,16 +38,21 @@ func ConfigShow(s *discordgo.Session, i *discordgo.InteractionCreate) { if len(chans) == 0 { chans = "Aucun salon désactivé :)" } + var defaultChan string + if len(cfg.FallbackChannel) == 0 { + defaultChan = "Pas de valeur" + } else { + defaultChan = fmt.Sprintf("<#%s>", cfg.FallbackChannel) + } err := resp.Embeds([]*discordgo.MessageEmbed{ { - Type: discordgo.EmbedTypeRich, - Title: "Config", - Description: "Configuration", - Color: utils.Success, + Type: discordgo.EmbedTypeRich, + Title: "Config", + Color: utils.Success, Fields: []*discordgo.MessageEmbedField{ { Name: "Salons par défaut", - Value: fmt.Sprintf("<#%s>", cfg.FallbackChannel), + Value: defaultChan, Inline: false, }, { @@ -60,6 +65,11 @@ func ConfigShow(s *discordgo.Session, i *discordgo.InteractionCreate) { Value: chans, Inline: false, }, + { + Name: "Jours avant la réduction", + Value: fmt.Sprintf("%d", cfg.DaysXPRemains), + Inline: false, + }, }, }, }).Send() @@ -98,7 +108,7 @@ func ConfigXP(s *discordgo.Session, i *discordgo.InteractionCreate) { } return } - exp := xp.XPForLevel(uint(level)) + xp := exp.LevelXP(uint(level)) r, ok := optMap["role"] if !ok { err := resp.Message("Le rôle n'a pas été renseigné.").Send() @@ -116,7 +126,7 @@ func ConfigXP(s *discordgo.Session, i *discordgo.InteractionCreate) { case "add": for _, r := range cfg.XpRoles { if r.RoleID == role.ID { - err := resp.Message("Le rôle est déjà présent dans la config").Send() + err = resp.Message("Le rôle est déjà présent dans la config").Send() if err != nil { utils.SendAlert("commands/config.go - Role already in config", err.Error()) } @@ -124,7 +134,7 @@ func ConfigXP(s *discordgo.Session, i *discordgo.InteractionCreate) { } } cfg.XpRoles = append(cfg.XpRoles, config.XpRole{ - XP: exp, + XP: xp, RoleID: role.ID, }) err = cfg.Save() @@ -143,7 +153,7 @@ func ConfigXP(s *discordgo.Session, i *discordgo.InteractionCreate) { case "del": _, r := cfg.FindXpRole(role.ID) if r == nil { - err := resp.Message("Le rôle n'a pas été trouvé dans la config.").Send() + err = resp.Message("Le rôle n'a pas été trouvé dans la config.").Send() if err != nil { utils.SendAlert("commands/config.go - Role not found (del)", err.Error()) } @@ -165,13 +175,13 @@ func ConfigXP(s *discordgo.Session, i *discordgo.InteractionCreate) { case "edit": _, r := cfg.FindXpRole(role.ID) if r == nil { - err := resp.Message("Le rôle n'a pas été trouvé dans la config.").Send() + err = resp.Message("Le rôle n'a pas été trouvé dans la config.").Send() if err != nil { utils.SendAlert("commands/config.go - Role not found (edit)", err.Error()) } return } - r.XP = exp + r.XP = xp err = gokord.DB.Save(r).Error if err != nil { utils.SendAlert( @@ -186,7 +196,7 @@ func ConfigXP(s *discordgo.Session, i *discordgo.InteractionCreate) { ) } default: - err := resp.Message("Le type d'action n'est pas valide.").Send() + err = resp.Message("Le type d'action n'est pas valide.").Send() if err != nil { utils.SendAlert("commands/config.go - Invalid action type", err.Error()) } @@ -316,3 +326,46 @@ func ConfigFallbackChannel(s *discordgo.Session, i *discordgo.InteractionCreate) utils.SendAlert("commands/config.go - Channel saved message", err.Error()) } } + +func ConfigPeriodBeforeReduce(s *discordgo.Session, i *discordgo.InteractionCreate) { + optMap := utils.GenerateOptionMapForSubcommand(i) + resp := utils.ResponseBuilder{C: s, I: i} + resp.IsEphemeral() + // verify every args + days, ok := optMap["days"] + if !ok { + err := resp.Message("Le nombre de jours n'a pas été renseigné.").Send() + if err != nil { + utils.SendAlert("commands/config.go - Days not set (fallback)", err.Error()) + } + return + } + d := days.IntValue() + if d < 30 { + err := resp.Message("Le nombre de jours est inférieur à 30.").Send() + if err != nil { + utils.SendAlert("commands/config.go - Days < 30 (fallback)", err.Error()) + } + return + } + // save + cfg := config.GetGuildConfig(i.GuildID) + cfg.DaysXPRemains = uint(d) + err := cfg.Save() + if err != nil { + utils.SendAlert( + "commands/config.go - Saving config", + err.Error(), + "guild_id", + i.GuildID, + "days", + d, + ) + err = resp.Message("Il y a eu une erreur lors de la modification de de la base de données.").Send() + } else { + err = resp.Message("Nombre de jours enregistré.").Send() + } + if err != nil { + utils.SendAlert("commands/config.go - Days saved message", err.Error()) + } +} diff --git a/commands/credits.go b/commands/credits.go index fb26530..d5aa42e 100644 --- a/commands/credits.go +++ b/commands/credits.go @@ -11,12 +11,12 @@ func Credits(s *discordgo.Session, i *discordgo.InteractionCreate) { { Type: discordgo.EmbedTypeRich, Title: "Crédits", - Description: "Auteur du bot : @anhgelus (https://github.com/anhgelus)\nLangage : Go 1.22\nLicence : AGPLv3", + Description: "Auteur du bot : @anhgelus (https://github.com/anhgelus)\nLangage : Go 1.24\nLicence : AGPLv3", Color: utils.Success, Fields: []*discordgo.MessageEmbedField{ { Name: "anhgelus/gokord", - Value: "v0.3.0 - MPL 2.0", + Value: "v0.6.3 - MPL 2.0", Inline: true, }, { @@ -24,29 +24,9 @@ func Credits(s *discordgo.Session, i *discordgo.InteractionCreate) { Value: "v0.28.1 - BSD-3-Clause", Inline: true, }, - { - Name: "pelletier/go-toml/v2", - Value: "v2.2.1 - MIT", - Inline: true, - }, { Name: "redis/go-redis/v9", - Value: "v9.5.1 - BSD-2-Clause", - Inline: true, - }, - { - Name: "gorm.io/gorm", - Value: "v1.25.9 - MIT", - Inline: true, - }, - { - Name: "gorm.io/driver/postgres", - Value: "v1.5.7 - MIT", - Inline: true, - }, - { - Name: "other", - Value: "Et leurs dépendances !", + Value: "v9.8.0 - BSD-2-Clause", Inline: true, }, }, diff --git a/commands/rank.go b/commands/rank.go index 4d6f817..70c0222 100644 --- a/commands/rank.go +++ b/commands/rank.go @@ -3,14 +3,14 @@ package commands import ( "fmt" "github.com/anhgelus/gokord/utils" - "github.com/anhgelus/les-copaings-bot/xp" + "github.com/anhgelus/les-copaings-bot/exp" + "github.com/anhgelus/les-copaings-bot/user" "github.com/bwmarrin/discordgo" ) func Rank(s *discordgo.Session, i *discordgo.InteractionCreate) { optMap := utils.GenerateOptionMap(i) - c := xp.GetCopaing(i.Member.User.ID, i.GuildID) // current copaing = member who used /rank - xp.LastEventUpdate(s, c) // update xp and reset last event + c := user.GetCopaing(i.Member.User.ID, i.GuildID) // current user = member who used /rank msg := "Votre niveau" m := i.Member var err error @@ -20,13 +20,13 @@ func Rank(s *discordgo.Session, i *discordgo.InteractionCreate) { if u.Bot { err = resp.Message("Imagine si les bots avaient un niveau :rolling_eyes:").IsEphemeral().Send() if err != nil { - utils.SendAlert("rank.go - Reply error user is a bot", err.Error()) + utils.SendAlert("commands/rank.go - Reply error user is a bot", err.Error()) } } m, err = s.GuildMember(i.GuildID, u.ID) if err != nil { utils.SendAlert( - "rank.go - Fetching guild member", + "commands/rank.go - Fetching guild member", err.Error(), "discord_id", u.ID, @@ -35,24 +35,39 @@ func Rank(s *discordgo.Session, i *discordgo.InteractionCreate) { ) err = resp.Message("Erreur : impossible de récupérer le membre").IsEphemeral().Send() if err != nil { - utils.SendAlert("rank.go - Reply error fetching guild member", err.Error()) + utils.SendAlert("commands/rank.go - Reply error fetching guild member", err.Error()) } return } - c = xp.GetCopaing(u.ID, i.GuildID) // current copaing = member targeted by member who wrote /rank - xp.XPUpdate(s, c) // update xp without resetting event + c = user.GetCopaing(u.ID, i.GuildID) // current user = member targeted by member who wrote /rank msg = fmt.Sprintf("Le niveau de %s", m.DisplayName()) } - lvl := xp.Level(c.XP) - nxtLvlXP := xp.XPForLevel(lvl + 1) + xp, err := c.GetXP() + if err != nil { + utils.SendAlert( + "commands/rank.go - Fetching xp", + err.Error(), + "discord_id", + c.ID, + "guild_id", + i.GuildID, + ) + err = resp.Message("Erreur : impossible de récupérer l'XP").IsEphemeral().Send() + if err != nil { + utils.SendAlert("commands/rank.go - Reply error fetching xp", err.Error()) + } + return + } + lvl := exp.Level(xp) + nxtLvlXP := exp.LevelXP(lvl + 1) err = resp.Message(fmt.Sprintf( "%s : **%d**\n> XP : %d\n> Prochain niveau dans %d XP", msg, lvl, - c.XP, - nxtLvlXP-c.XP, + xp, + nxtLvlXP-xp, )).Send() if err != nil { - utils.SendAlert("rank.go - Sending rank", err.Error()) + utils.SendAlert("commands/rank.go - Sending rank", err.Error()) } } diff --git a/commands/reset.go b/commands/reset.go index 0c18044..3f8af03 100644 --- a/commands/reset.go +++ b/commands/reset.go @@ -3,12 +3,12 @@ package commands import ( "github.com/anhgelus/gokord" "github.com/anhgelus/gokord/utils" - "github.com/anhgelus/les-copaings-bot/xp" + "github.com/anhgelus/les-copaings-bot/user" "github.com/bwmarrin/discordgo" ) func Reset(s *discordgo.Session, i *discordgo.InteractionCreate) { - var copaings []*xp.Copaing + var copaings []*user.Copaing gokord.DB.Where("guild_id = ?", i.GuildID).Delete(&copaings) resp := utils.ResponseBuilder{C: s, I: i} if err := resp.IsEphemeral().Message("L'XP a été reset.").Send(); err != nil { @@ -20,9 +20,9 @@ func ResetUser(s *discordgo.Session, i *discordgo.InteractionCreate) { resp := utils.ResponseBuilder{C: s, I: i} resp.IsEphemeral() optMap := utils.GenerateOptionMap(i) - v, ok := optMap["copaing"] + v, ok := optMap["user"] if !ok { - if err := resp.Message("Le copaing n'a pas été renseigné.").Send(); err != nil { + if err := resp.Message("Le user n'a pas été renseigné.").Send(); err != nil { utils.SendAlert("commands/reset.go - Copaing not set", err.Error()) } return @@ -34,8 +34,15 @@ func ResetUser(s *discordgo.Session, i *discordgo.InteractionCreate) { } return } - xp.GetCopaing(m.ID, i.GuildID).Reset() - if err := resp.Message("Le copaing bien été reset.").Send(); err != nil { - utils.SendAlert("commands/reset.go - Sending success (copaing)", err.Error()) + err := user.GetCopaing(m.ID, i.GuildID).Delete() + if err != nil { + utils.SendAlert("commands/reset.go - Copaing not deleted", err.Error(), "discord_id", m.ID, "guild_id", i.GuildID) + err = resp.Message("Erreur : impossible de reset l'utilisateur").Send() + if err != nil { + utils.SendAlert("commands/reset.go - Error deleting", err.Error()) + } + } + if err = resp.Message("Le user bien été reset.").Send(); err != nil { + utils.SendAlert("commands/reset.go - Sending success (user)", err.Error()) } } diff --git a/commands/top.go b/commands/top.go index 8320fe9..a43e055 100644 --- a/commands/top.go +++ b/commands/top.go @@ -2,14 +2,14 @@ package commands import ( "fmt" - "github.com/anhgelus/gokord" "github.com/anhgelus/gokord/utils" - "github.com/anhgelus/les-copaings-bot/xp" + "github.com/anhgelus/les-copaings-bot/exp" + "github.com/anhgelus/les-copaings-bot/user" "github.com/bwmarrin/discordgo" + "sync" ) func Top(s *discordgo.Session, i *discordgo.InteractionCreate) { - xp.LastEventUpdate(s, xp.GetCopaing(i.Member.User.ID, i.GuildID)) resp := utils.ResponseBuilder{C: s, I: i} err := resp.IsDeferred().Send() if err != nil { @@ -17,26 +17,48 @@ func Top(s *discordgo.Session, i *discordgo.InteractionCreate) { return } resp.NotDeferred().IsEdit() - go func() { - var tops []xp.Copaing - gokord.DB.Where("guild_id = ?", i.GuildID).Limit(10).Order("xp desc").Find(&tops) - msg := "" - for i, c := range tops { - if i == 9 { - msg += fmt.Sprintf("%d. **<@%s>** - niveau %d", i+1, c.DiscordID, xp.Level(c.XP)) - } else { - msg += fmt.Sprintf("%d. **<@%s>** - niveau %d\n", i+1, c.DiscordID, xp.Level(c.XP)) + embeds := make([]*discordgo.MessageEmbed, 3) + wg := sync.WaitGroup{} + + fn := func(s string, n uint, d int, id int) { + defer wg.Done() + tops, err := user.GetBestXP(i.GuildID, n, d) + if err != nil { + utils.SendAlert("commands/top.go - Fetching best xp", err.Error(), "n", n, "d", d, "id", id, "guild_id", i.GuildID) + embeds[id] = &discordgo.MessageEmbed{ + Title: s, + Description: "Erreur : impossible de récupérer la liste", + Color: utils.Error, } + return } - err = resp.Embeds([]*discordgo.MessageEmbed{ - { - Title: "Top", - Description: msg, - Color: utils.Success, - }, - }).Send() + embeds[id] = &discordgo.MessageEmbed{ + Title: s, + Description: genTopsMessage(tops), + Color: utils.Success, + } + } + + wg.Add(3) + go fn("Top full time", 10, -1, 0) + go fn("Top 30 jours", 5, 30, 1) + go fn("Top 7 jours", 5, 7, 2) + go func() { + wg.Wait() + err = resp.Embeds(embeds).Send() if err != nil { utils.SendAlert("commands/top.go - Sending response top", err.Error()) } }() } + +func genTopsMessage(tops []user.CopaingAccess) string { + msg := "" + for i, c := range tops { + msg += fmt.Sprintf("%d. **<@%s>** - niveau %d", i+1, c.ToCopaing().DiscordID, exp.Level(c.GetXP())) + if i != len(tops)-1 { + msg += "\n" + } + } + return msg +} diff --git a/config/guild.go b/config/guild.go index 242cc89..fb7eaef 100644 --- a/config/guild.go +++ b/config/guild.go @@ -3,20 +3,20 @@ package config import ( "github.com/anhgelus/gokord" "github.com/anhgelus/gokord/utils" - "gorm.io/gorm" "strings" ) type GuildConfig struct { - gorm.Model - GuildID string `gorm:"not null"` + ID uint `gorm:"primarykey"` + GuildID string `gorm:"not null;unique"` XpRoles []XpRole DisabledChannels string FallbackChannel string + DaysXPRemains uint `gorm:"default:90"` // 30 * 3 = 90 (three months) } type XpRole struct { - gorm.Model + ID uint `gorm:"primarykey"` XP uint RoleID string GuildConfigID uint diff --git a/config/redis.go b/config/redis.go new file mode 100644 index 0000000..bfec5a0 --- /dev/null +++ b/config/redis.go @@ -0,0 +1,28 @@ +package config + +import ( + "github.com/anhgelus/gokord" + "github.com/anhgelus/gokord/utils" + "github.com/redis/go-redis/v9" +) + +var redisClient *redis.Client + +func GetRedisClient() (*redis.Client, error) { + if redisClient == nil { + var err error + redisClient, err = gokord.BaseCfg.GetRedisCredentials().Connect() + return redisClient, err + } + return redisClient, nil +} + +func CloseRedisClient() { + if redisClient == nil { + return + } + err := redisClient.Close() + if err != nil { + utils.SendAlert("config/redis.go - Closing redis client", err.Error()) + } +} diff --git a/docker-compose.yml b/docker-compose.yml index e6b9b89..2575340 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ services: bot: build: . + restart: always env_file: - .env volumes: @@ -15,4 +16,10 @@ services: env_file: - .env volumes: - - ./data:/var/lib/postgresql/data \ No newline at end of file + - ./data:/var/lib/postgresql/data + adminer: + image: docker.io/adminer + ports: + - "8080:8080" + depends_on: + - postgres diff --git a/xp/events.go b/events.go similarity index 69% rename from xp/events.go rename to events.go index 94d8889..54c444e 100644 --- a/xp/events.go +++ b/events.go @@ -1,15 +1,15 @@ -package xp +package main import ( "context" "errors" "fmt" - "github.com/anhgelus/gokord" "github.com/anhgelus/gokord/utils" "github.com/anhgelus/les-copaings-bot/config" + "github.com/anhgelus/les-copaings-bot/exp" + "github.com/anhgelus/les-copaings-bot/user" "github.com/bwmarrin/discordgo" "github.com/redis/go-redis/v9" - "slices" "strconv" "strings" "time" @@ -30,20 +30,19 @@ func OnMessage(s *discordgo.Session, m *discordgo.MessageCreate) { if cfg.IsDisabled(m.ChannelID) { return } - c := GetCopaing(m.Author.ID, m.GuildID) - LastEventUpdate(s, c) - // add xp + c := user.GetCopaing(m.Author.ID, m.GuildID) + // add exp trimmed := utils.TrimMessage(strings.ToLower(m.Content)) m.Member.User = m.Author m.Member.GuildID = m.GuildID - xp := XPMessage(uint(len(trimmed)), calcDiversity(trimmed)) + xp := exp.MessageXP(uint(len(trimmed)), exp.CalcDiversity(trimmed)) if xp > MaxXpPerMessage { xp = MaxXpPerMessage } c.AddXP(s, m.Member, xp, func(_ uint, _ uint) { if err := s.MessageReactionAdd(m.ChannelID, m.Message.ID, "⬆"); err != nil { utils.SendAlert( - "xp/events.go - add reaction for new level", err.Error(), + "events.go - add reaction for new level", err.Error(), "channel id", m.ChannelID, "message id", m.Message.ID, ) @@ -51,25 +50,14 @@ func OnMessage(s *discordgo.Session, m *discordgo.MessageCreate) { }) } -func calcDiversity(msg string) uint { - var chars []rune - for _, c := range []rune(msg) { - if !slices.Contains(chars, c) { - chars = append(chars, c) - } - } - return uint(len(chars)) -} - func OnVoiceUpdate(s *discordgo.Session, e *discordgo.VoiceStateUpdate) { if e.Member.User.Bot { return } - LastEventUpdate(s, GetCopaing(e.UserID, e.GuildID)) cfg := config.GetGuildConfig(e.GuildID) - client, err := getRedisClient() + client, err := config.GetRedisClient() if err != nil { - utils.SendAlert("xp/events.go - Getting redis client", err.Error()) + utils.SendAlert("events.go - Getting redis client", err.Error()) return } if e.BeforeUpdate == nil && e.ChannelID != "" { @@ -87,7 +75,7 @@ func OnVoiceUpdate(s *discordgo.Session, e *discordgo.VoiceStateUpdate) { func onConnection(_ *discordgo.Session, e *discordgo.VoiceStateUpdate, client *redis.Client) { utils.SendDebug("User connected", "username", e.Member.DisplayName()) - c := GetCopaing(e.UserID, e.GuildID) + c := user.GetCopaing(e.UserID, e.GuildID) err := client.Set( context.Background(), c.GenKey(ConnectedSince), @@ -95,13 +83,13 @@ func onConnection(_ *discordgo.Session, e *discordgo.VoiceStateUpdate, client *r 0, ).Err() if err != nil { - utils.SendAlert("xp/events.go - Setting connected_since", err.Error()) + utils.SendAlert("events.go - Setting connected_since", err.Error()) } } func onDisconnect(s *discordgo.Session, e *discordgo.VoiceStateUpdate, client *redis.Client) { now := time.Now().Unix() - c := GetCopaing(e.UserID, e.GuildID) + c := user.GetCopaing(e.UserID, e.GuildID) key := c.GenKey(ConnectedSince) res := client.Get(context.Background(), key) // check validity of user (1) @@ -112,16 +100,16 @@ func onDisconnect(s *discordgo.Session, e *discordgo.VoiceStateUpdate, client *r return } if res.Err() != nil { - utils.SendAlert("xp/events.go - Getting connected_since", res.Err().Error()) + utils.SendAlert("events.go - Getting connected_since", res.Err().Error()) err := client.Set(context.Background(), key, strconv.Itoa(NotConnected), 0).Err() if err != nil { - utils.SendAlert("xp/events.go - Set connected_since to not connected after get err", err.Error()) + utils.SendAlert("events.go - Set connected_since to not connected after get err", err.Error()) } return } con, err := res.Int64() if err != nil { - utils.SendAlert("xp/events.go - Converting result to int64", err.Error()) + utils.SendAlert("events.go - Converting result to int64", err.Error()) return } // check validity of user (2) @@ -134,12 +122,12 @@ func onDisconnect(s *discordgo.Session, e *discordgo.VoiceStateUpdate, client *r utils.SendDebug("User disconnected", "username", e.Member.DisplayName(), "since", con) err = client.Set(context.Background(), key, strconv.Itoa(NotConnected), 0).Err() if err != nil { - utils.SendAlert("xp/events.go - Set connected_since to not connected", err.Error()) + utils.SendAlert("events.go - Set connected_since to not connected", err.Error()) } - // add xp + // add exp timeInVocal := now - con if timeInVocal < 0 { - utils.SendAlert("xp/events.go - Calculating time spent in vocal", "the time is negative") + utils.SendAlert("events.go - Calculating time spent in vocal", "the time is negative") return } if timeInVocal > MaxTimeInVocal { @@ -147,23 +135,26 @@ func onDisconnect(s *discordgo.Session, e *discordgo.VoiceStateUpdate, client *r timeInVocal = MaxTimeInVocal } e.Member.GuildID = e.GuildID - c.AddXP(s, e.Member, XPVocal(uint(timeInVocal)), func(_ uint, newLevel uint) { + c.AddXP(s, e.Member, exp.VocalXP(uint(timeInVocal)), func(_ uint, newLevel uint) { cfg := config.GetGuildConfig(e.GuildID) _, err = s.ChannelMessageSend(cfg.FallbackChannel, fmt.Sprintf( "%s est maintenant niveau %d", e.Member.Mention(), newLevel, )) if err != nil { - utils.SendAlert("xp/events.go - Sending new level in fallback channel", err.Error()) + utils.SendAlert("events.go - Sending new level in fallback channel", err.Error()) } }) } func OnLeave(_ *discordgo.Session, e *discordgo.GuildMemberRemove) { utils.SendDebug("Leave event", "user_id", e.User.ID) - c := GetCopaing(e.User.ID, e.GuildID) - if err := gokord.DB.Where("guild_id = ?", e.GuildID).Delete(c).Error; err != nil { + if e.User.Bot { + return + } + c := user.GetCopaing(e.User.ID, e.GuildID) + if err := c.Delete(); err != nil { utils.SendAlert( - "xp/events.go - deleting copaing from db", err.Error(), + "events.go - deleting user from db", err.Error(), "user_id", e.User.ID, "guild_id", e.GuildID, ) diff --git a/exp/functions.go b/exp/functions.go new file mode 100644 index 0000000..720a755 --- /dev/null +++ b/exp/functions.go @@ -0,0 +1,59 @@ +package exp + +import ( + "fmt" + "github.com/anhgelus/gokord" + "math" + "slices" + "time" +) + +func MessageXP(length uint, diversity uint) uint { + return uint(math.Floor( + 0.025*math.Pow(float64(length), 1.25)*math.Sqrt(float64(diversity)) + 1, + )) +} + +func CalcDiversity(msg string) uint { + var chars []rune + for _, c := range []rune(msg) { + if !slices.Contains(chars, c) { + chars = append(chars, c) + } + } + return uint(len(chars)) +} + +func VocalXP(time uint) uint { + return uint(math.Floor( + 0.01*math.Pow(float64(time), 1.3) + 1, + )) +} + +// Level gives the level with the given XP. +// See LevelXP to get the XP required to get a level. +func Level(xp uint) uint { + return uint(math.Floor( + 0.2 * math.Sqrt(float64(xp)), + )) +} + +// LevelXP gives the XP required to get this level. +// See Level to get the level with the given XP. +func LevelXP(level uint) uint { + return uint(math.Floor( + math.Pow(float64(5*level), 2), + )) +} + +// TimeStampNDaysBefore returns the timestamp (year-month-day) n days before today +func TimeStampNDaysBefore(n uint) string { + var y, d int + var m time.Month + if gokord.Debug { + y, m, d = time.Unix(time.Now().Unix()-int64(24*60*60), 0).Date() // reduce time for debug + } else { + y, m, d = time.Unix(time.Now().Unix()-int64(n*24*60*60), 0).Date() + } + return fmt.Sprintf("%d-%d-%d", y, m, d) +} diff --git a/go.mod b/go.mod index 1950e11..c80b3b4 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,11 @@ module github.com/anhgelus/les-copaings-bot -go 1.23.0 - -toolchain go1.24.0 +go 1.24 require ( - github.com/anhgelus/gokord v0.6.2 + github.com/anhgelus/gokord v0.6.3 github.com/bwmarrin/discordgo v0.28.1 - github.com/redis/go-redis/v9 v9.7.1 - gorm.io/gorm v1.25.12 + github.com/redis/go-redis/v9 v9.8.0 ) require ( @@ -17,14 +14,14 @@ require ( github.com/gorilla/websocket v1.5.3 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.7.2 // indirect + github.com/jackc/pgx/v5 v5.7.4 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect - github.com/pelletier/go-toml/v2 v2.2.3 // indirect - golang.org/x/crypto v0.36.0 // indirect - golang.org/x/sync v0.12.0 // indirect - golang.org/x/sys v0.31.0 // indirect - golang.org/x/text v0.23.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + golang.org/x/crypto v0.38.0 // indirect + golang.org/x/sync v0.14.0 // indirect + golang.org/x/sys v0.33.0 // indirect + golang.org/x/text v0.25.0 // indirect gorm.io/driver/postgres v1.5.11 // indirect ) diff --git a/go.sum b/go.sum index 9b7206e..a188c46 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,8 @@ github.com/anhgelus/gokord v0.6.1 h1:zgNeFMyp+jXyaQH3CzOJGhE6y+NMfFHVTgZK7uT18ek github.com/anhgelus/gokord v0.6.1/go.mod h1:R1SMf1+C8FshZ1/fDyBBt1Y9ob097UShHON21btlw2s= github.com/anhgelus/gokord v0.6.2 h1:jR5l6NVGio+yChg8kxeNJSm6mbBfWxSLkvR6FPoh5E4= github.com/anhgelus/gokord v0.6.2/go.mod h1:R1SMf1+C8FshZ1/fDyBBt1Y9ob097UShHON21btlw2s= +github.com/anhgelus/gokord v0.6.3 h1:4Z57e64YcecI6gokGVpIq8YOfvybJofX2Kx1HYRTuwo= +github.com/anhgelus/gokord v0.6.3/go.mod h1:UIpun+/+pgtvMQZdXvsy3qBhNSPG+q18shwDShDEI3Y= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= @@ -36,6 +38,8 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= +github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -44,12 +48,16 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= github.com/redis/go-redis/v9 v9.7.1 h1:4LhKRCIduqXqtvCUlaq9c8bdHOkICjDMrr1+Zb3osAc= github.com/redis/go-redis/v9 v9.7.1/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= +github.com/redis/go-redis/v9 v9.8.0 h1:q3nRvjrlge/6UD7eTu/DSg2uYiU2mCL0G/uzBWqhicI= +github.com/redis/go-redis/v9 v9.8.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -62,6 +70,8 @@ golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= +golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= @@ -69,6 +79,8 @@ golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ= +golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -76,6 +88,8 @@ golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= @@ -84,6 +98,8 @@ golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= +golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= @@ -93,3 +109,5 @@ gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314= gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI= gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= +gorm.io/gorm v1.26.1 h1:ghB2gUI9FkS46luZtn6DLZ0f6ooBJ5IbVej2ENFDjRw= +gorm.io/gorm v1.26.1/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE= diff --git a/main.go b/main.go index 5bbc289..4b4062e 100644 --- a/main.go +++ b/main.go @@ -7,7 +7,7 @@ import ( "github.com/anhgelus/gokord/utils" "github.com/anhgelus/les-copaings-bot/commands" "github.com/anhgelus/les-copaings-bot/config" - "github.com/anhgelus/les-copaings-bot/xp" + "github.com/anhgelus/les-copaings-bot/user" "github.com/bwmarrin/discordgo" "time" ) @@ -17,10 +17,10 @@ var ( //go:embed updates.json updatesData []byte Version = gokord.Version{ - Major: 2, - Minor: 4, + Major: 3, + Minor: 0, Patch: 0, - } // git version: 0.4.0 (it's the v2 of the bot) + } stopPeriodicReducer chan<- interface{} ) @@ -36,7 +36,7 @@ func main() { panic(err) } - err = gokord.DB.AutoMigrate(&xp.Copaing{}, &config.GuildConfig{}, &config.XpRole{}) + err = gokord.DB.AutoMigrate(&user.Copaing{}, &config.GuildConfig{}, &config.XpRole{}, &user.CopaingXP{}) if err != nil { panic(err) } @@ -99,6 +99,16 @@ func main() { ).IsRequired()). SetHandler(commands.ConfigChannel), ). + AddSub( + gokord.NewCommand("period-before-reduce", "Temps avant la perte d'xp (affecte aussi le /top)"). + HasOption(). + AddOption(gokord.NewOption( + discordgo.ApplicationCommandOptionInteger, + "days", + "Nombre de jours avant la perte d'xp (doit être égal ou plus grand que 30)", + ).IsRequired()). + SetHandler(commands.ConfigPeriodBeforeReduce), + ). AddSub( gokord.NewCommand("fallback-channel", "Modifie le salon textuel par défaut"). HasOption(). @@ -123,7 +133,7 @@ func main() { HasOption(). AddOption(gokord.NewOption( discordgo.ApplicationCommandOptionUser, - "copaing", + "user", "Copaing a reset", ).IsRequired()). SetHandler(commands.ResetUser). @@ -176,22 +186,16 @@ func main() { stopPeriodicReducer <- true } - xp.CloseRedisClient() + config.CloseRedisClient() } func afterInit(dg *discordgo.Session) { // handlers - dg.AddHandler(xp.OnMessage) - dg.AddHandler(xp.OnVoiceUpdate) - dg.AddHandler(xp.OnLeave) + dg.AddHandler(OnMessage) + dg.AddHandler(OnVoiceUpdate) + dg.AddHandler(OnLeave) - // setup timer for periodic reducer - d := 24 * time.Hour - if gokord.Debug { - // reduce time for debug - d = time.Minute - } - stopPeriodicReducer = utils.NewTimer(d, func(stop chan<- interface{}) { - xp.PeriodicReducer(dg) + stopPeriodicReducer = utils.NewTimer(24*time.Hour, func(stop chan<- interface{}) { + user.PeriodicReducer(dg) }) } diff --git a/updates.json b/updates.json index c378f8b..fd73d8f 100644 --- a/updates.json +++ b/updates.json @@ -8,5 +8,15 @@ "config" ] } + }, + { + "version": "3.0.0", + "commands": { + "added": [], + "removed": [], + "updated": [ + "config" + ] + } } ] diff --git a/user/level.go b/user/level.go new file mode 100644 index 0000000..6d9b674 --- /dev/null +++ b/user/level.go @@ -0,0 +1,116 @@ +package user + +import ( + "github.com/anhgelus/gokord" + "github.com/anhgelus/gokord/utils" + "github.com/anhgelus/les-copaings-bot/config" + "github.com/anhgelus/les-copaings-bot/exp" + "github.com/bwmarrin/discordgo" + "slices" + "sync" + "time" +) + +func onNewLevel(dg *discordgo.Session, m *discordgo.Member, level uint) { + cfg := config.GetGuildConfig(m.GuildID) + xpForLevel := exp.LevelXP(level) + for _, role := range cfg.XpRoles { + if role.XP <= xpForLevel && !slices.Contains(m.Roles, role.RoleID) { + utils.SendDebug( + "Add role", + "role_id", role.RoleID, + "user_id", m.User.ID, + "guild_id", m.GuildID, + ) + err := dg.GuildMemberRoleAdd(m.GuildID, m.User.ID, role.RoleID) + if err != nil { + utils.SendAlert("user/level.go - Adding role", err.Error(), "role_id", role.RoleID) + } + } else if role.XP > xpForLevel && slices.Contains(m.Roles, role.RoleID) { + utils.SendDebug( + "Remove role", + "role_id", role.RoleID, + "user_id", m.User.ID, + "guild_id", m.GuildID, + ) + err := dg.GuildMemberRoleRemove(m.GuildID, m.User.ID, role.RoleID) + if err != nil { + utils.SendAlert("user/level.go - Removing role", err.Error(), "role_id", role.RoleID) + } + } + } +} + +func (c *Copaing) OnNewLevel(dg *discordgo.Session, level uint) { + m, err := dg.GuildMember(c.GuildID, c.DiscordID) + if err != nil { + utils.SendAlert( + "user/level.go - Getting member for new level", err.Error(), + "discord_id", c.DiscordID, + "guild_id", c.GuildID, + ) + return + } + onNewLevel(dg, m, level) +} + +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() { + defer wg.Done() + cfg := config.GetGuildConfig(g.ID) + err := gokord.DB. + Model(&CopaingXP{}). + Where("guild_id = ? and created_at < ?", g.ID, exp.TimeStampNDaysBefore(cfg.DaysXPRemains)). + Delete(&CopaingXP{}). + Error + if err != nil { + utils.SendAlert("user/level.go - Removing old XP", err.Error(), "guild_id", g.ID) + } + }() + } + 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)) +} diff --git a/user/member.go b/user/member.go new file mode 100644 index 0000000..71a369b --- /dev/null +++ b/user/member.go @@ -0,0 +1,69 @@ +package user + +import ( + "fmt" + "github.com/anhgelus/gokord" + "github.com/anhgelus/gokord/utils" + "time" +) + +type Copaing struct { + ID uint `gorm:"primarykey"` + DiscordID string `gorm:"not null"` + CopaingXPs []CopaingXP `gorm:"constraint:OnDelete:SET NULL;"` + GuildID string `gorm:"not null"` +} + +type CopaingXP struct { + ID uint `gorm:"primarykey"` + XP uint `gorm:"default:0"` + CopaingID uint + GuildID string `gorm:"not null;"` + CreatedAt time.Time +} + +type CopaingAccess interface { + ToCopaing() *Copaing + GetXP() uint +} + +const ( + LastEvent = "last_event" + AlreadyRemoved = "already_removed" +) + +func GetCopaing(discordID string, guildID string) *Copaing { + c := Copaing{DiscordID: discordID, GuildID: guildID} + if err := c.Load(); err != nil { + utils.SendAlert( + "user/member.go - Loading user", + err.Error(), + "discord_id", + discordID, + "guild_id", + guildID, + ) + return nil + } + return &c +} + +func (c *Copaing) Load() error { + return gokord.DB. + Where("discord_id = ? and guild_id = ?", c.DiscordID, c.GuildID). + Preload("CopaingXPs"). + FirstOrCreate(c). + Error +} + +func (c *Copaing) Save() error { + return gokord.DB.Save(c).Error +} + +func (c *Copaing) GenKey(key string) string { + return fmt.Sprintf("%s:%s:%s", c.GuildID, c.DiscordID, key) +} + +func (c *Copaing) Delete() error { + return gokord.DB.Where("guild_id = ? AND discord_id = ?", c.GuildID, c.DiscordID).Delete(c).Error +} diff --git a/user/xp.go b/user/xp.go new file mode 100644 index 0000000..71a1ced --- /dev/null +++ b/user/xp.go @@ -0,0 +1,137 @@ +package user + +import ( + "github.com/anhgelus/gokord" + "github.com/anhgelus/gokord/utils" + "github.com/anhgelus/les-copaings-bot/config" + "github.com/anhgelus/les-copaings-bot/exp" + "github.com/bwmarrin/discordgo" + "slices" + "sync" +) + +type cXP struct { + Cxp uint + *Copaing +} + +func (c *cXP) ToCopaing() *Copaing { + return c.Copaing +} + +func (c *cXP) GetXP() uint { + return c.Cxp +} + +func (c *Copaing) AddXP(s *discordgo.Session, m *discordgo.Member, xp uint, fn func(uint, uint)) { + old, err := c.GetXP() + if err != nil { + utils.SendAlert("user/xp.go - Getting xp", err.Error(), "discord_id", c.DiscordID, "guild_id", c.GuildID) + return + } + pastLevel := exp.Level(old) + utils.SendDebug("Adding xp", "member", m.DisplayName(), "old xp", old, "xp to add", xp, "old level", pastLevel) + c.CopaingXPs = append(c.CopaingXPs, CopaingXP{CopaingID: c.ID, XP: xp, GuildID: c.GuildID}) + if err = c.Save(); err != nil { + utils.SendAlert( + "user/xp.go - Saving user", + err.Error(), + "xp", + c.CopaingXPs, + "discord_id", + c.DiscordID, + "guild_id", + c.GuildID, + ) + return + } + newLevel := exp.Level(old + xp) + if newLevel > pastLevel { + fn(old+xp, newLevel) + onNewLevel(s, m, newLevel) + } +} + +func (c *Copaing) GetXP() (uint, error) { + cfg := config.GetGuildConfig(c.GuildID) + return c.GetXPForDays(cfg.DaysXPRemains) +} + +func (c *Copaing) GetXPForDays(n uint) (uint, error) { + xp := uint(0) + rows, err := gokord.DB. + Model(&CopaingXP{}). + Where( + "created_at >= ? and guild_id = ? and copaing_id = ?", + exp.TimeStampNDaysBefore(n), + c.GuildID, + c.ID, + ). + Rows() + defer rows.Close() + if err != nil { + return 0, err + } + for rows.Next() { + var cxp CopaingXP + err = gokord.DB.ScanRows(rows, &cxp) + if err != nil { + utils.SendAlert("user/xp.go - Scanning rows", err.Error(), "copaing_id", c.ID, "guild_id", c.GuildID) + continue + } + xp += cxp.XP + } + return xp, nil +} + +// GetBestXP returns n Copaing with the best XP within d days (d <= cfg.DaysXPRemain; d < 0 <=> d = cfg.DaysXPRemain) +// +// This function is slow +func GetBestXP(guildId string, n uint, d int) ([]CopaingAccess, error) { + if d < 0 { + cfg := config.GetGuildConfig(guildId) + d = int(cfg.DaysXPRemains) + } + rows, err := gokord.DB.Model(&Copaing{}).Where("guild_id = ?", guildId).Rows() + defer rows.Close() + if err != nil { + return nil, err + } + var l []*cXP + wg := sync.WaitGroup{} + for rows.Next() { + var c Copaing + err = gokord.DB.ScanRows(rows, &c) + if err != nil { + utils.SendAlert("user/xp.go - Scanning rows", err.Error(), "guild_id", guildId) + continue + } + wg.Add(1) + go func() { + defer wg.Done() + xp, err := c.GetXPForDays(uint(d)) + if err != nil { + utils.SendAlert("user/xp.go - Fetching xp", err.Error(), "discord_id", c.DiscordID, "guild_id", guildId) + return + } + l = append(l, &cXP{Cxp: xp, Copaing: &c}) + }() + } + wg.Wait() + slices.SortFunc(l, func(a, b *cXP) int { + // desc order + if a.Cxp < b.Cxp { + return 1 + } + if a.Cxp > b.Cxp { + return -1 + } + return 0 + }) + m := min(len(l), int(n)) + cs := make([]CopaingAccess, m) + for i, c := range l[:m] { + cs[i] = c + } + return cs, nil +} diff --git a/xp/functions.go b/xp/functions.go deleted file mode 100644 index 7ab57f2..0000000 --- a/xp/functions.go +++ /dev/null @@ -1,41 +0,0 @@ -package xp - -import ( - "github.com/anhgelus/gokord" - "math" -) - -func XPMessage(length uint, diversity uint) uint { - return uint(math.Floor( - 0.025*math.Pow(float64(length), 1.25)*math.Sqrt(float64(diversity)) + 1, - )) -} - -func XPVocal(time uint) uint { - return uint(math.Floor( - 0.01*math.Pow(float64(time), 1.3) + 1, - )) -} - -func Level(xp uint) uint { - return uint(math.Floor( - 0.2 * math.Sqrt(float64(xp)), - )) -} - -func XPForLevel(level uint) uint { - return uint(math.Floor( - math.Pow(float64(5*level), 2), - )) -} - -func Lose(time uint, xp uint) uint { - if gokord.Debug { - return uint(math.Floor( - math.Pow(float64(time), 3) * math.Pow(10, -2+math.Log(float64(time))) * math.Floor(float64(xp/500)+1), - )) // a little bit faster to lose xp - } - return uint(math.Floor( - math.Pow(float64(time), 2) * math.Pow(10, -2+math.Log(float64(time/85))) * math.Floor(float64(xp/500)+1), - )) -} diff --git a/xp/level.go b/xp/level.go deleted file mode 100644 index a20d5cf..0000000 --- a/xp/level.go +++ /dev/null @@ -1,206 +0,0 @@ -package xp - -import ( - "github.com/anhgelus/gokord" - "github.com/anhgelus/gokord/utils" - "github.com/anhgelus/les-copaings-bot/config" - "github.com/bwmarrin/discordgo" - "slices" - "sync" - "time" -) - -func onNewLevel(dg *discordgo.Session, m *discordgo.Member, level uint) { - cfg := config.GetGuildConfig(m.GuildID) - xpForLevel := XPForLevel(level) - for _, role := range cfg.XpRoles { - if role.XP <= xpForLevel && !slices.Contains(m.Roles, role.RoleID) { - utils.SendDebug( - "Add role", - "role_id", role.RoleID, - "user_id", m.User.ID, - "guild_id", m.GuildID, - ) - err := dg.GuildMemberRoleAdd(m.GuildID, m.User.ID, role.RoleID) - if err != nil { - utils.SendAlert("xp/level.go - Adding role", err.Error(), "role_id", role.RoleID) - } - } else if role.XP > xpForLevel && slices.Contains(m.Roles, role.RoleID) { - utils.SendDebug( - "Remove role", - "role_id", role.RoleID, - "user_id", m.User.ID, - "guild_id", m.GuildID, - ) - err := dg.GuildMemberRoleRemove(m.GuildID, m.User.ID, role.RoleID) - if err != nil { - utils.SendAlert("xp/level.go - Removing role", err.Error(), "role_id", role.RoleID) - } - } - } -} - -func (c *Copaing) OnNewLevel(dg *discordgo.Session, level uint) { - m, err := dg.GuildMember(c.GuildID, c.DiscordID) - if err != nil { - utils.SendAlert( - "xp/level.go - Getting member for new level", err.Error(), - "discord_id", c.DiscordID, - "guild_id", c.GuildID, - ) - return - } - onNewLevel(dg, m, level) -} - -func LastEventUpdate(dg *discordgo.Session, c *Copaing) { - h := c.HourSinceLastEvent() - l := Lose(h, c.XP) - xp := c.XPAlreadyRemoved() - oldXP := c.XP - if l-xp < 0 { - utils.SendWarn("lose - xp already removed is negative", "lose", l, "xp", xp) - c.XP = 0 - } else { - calc := int(c.XP) - int(l) + int(c.XPAlreadyRemoved()) - if calc < 0 { - c.XP = 0 - } else { - c.XP = uint(calc) - } - } - if oldXP != c.XP { - lvl := Level(c.XP) - if Level(oldXP) != lvl { - utils.SendDebug( - "Level changed", - "old", Level(oldXP), - "new", lvl, - "discord_id", c.DiscordID, - "guild_id", c.GuildID, - ) - c.OnNewLevel(dg, lvl) - } - if err := c.Save(); err != nil { - utils.SendAlert( - "xp/level.go - Saving copaing", err.Error(), - "xp", c.XP, - "discord_id", c.DiscordID, - "guild_id", c.GuildID, - ) - } - } - c.SetLastEvent() -} - -func XPUpdate(dg *discordgo.Session, c *Copaing) { - oldXP := c.XP - if oldXP == 0 { - return - } - h := c.HourSinceLastEvent() - l := Lose(h, c.XP) - xp := c.XPAlreadyRemoved() - if l-xp < 0 { - utils.SendWarn("lose - xp_removed is negative", "lose", l, "xp removed", xp) - c.AddXPAlreadyRemoved(0) - } else { - calc := int(c.XP) - int(l) + int(xp) - if calc < 0 { - c.AddXPAlreadyRemoved(c.XP) - c.XP = 0 - } else { - c.XP = uint(calc) - c.AddXPAlreadyRemoved(l - xp) - } - } - if oldXP != c.XP { - lvl := Level(c.XP) - if Level(oldXP) != lvl { - utils.SendDebug( - "Level updated", - "old", Level(oldXP), - "new", lvl, - "discord_id", c.DiscordID, - "guild_id", c.GuildID, - ) - c.OnNewLevel(dg, lvl) - } - utils.SendDebug("Save XP", "old", oldXP, "new", c.XP, "user", c.DiscordID) - if err := c.Save(); err != nil { - utils.SendAlert( - "xp/level.go - Saving copaing", err.Error(), - "xp", c.XP, - "discord_id", c.DiscordID, - "guild_id", c.GuildID, - ) - } - } -} - -func PeriodicReducer(dg *discordgo.Session) { - var wg sync.WaitGroup - for _, g := range dg.State.Guilds { - var cs []*Copaing - err := gokord.DB.Where("guild_id = ?", g.ID).Find(&cs).Error - if err != nil { - utils.SendAlert("xp/level.go - Querying all copaings in Guild", err.Error(), "guild_id", g.ID) - continue - } - for i, c := range cs { - if i%50 == 49 { - time.Sleep(15 * time.Second) // sleep prevents from spamming the Discord API and the database - } - var u *discordgo.User - u, err = dg.User(c.DiscordID) - if err != nil { - utils.SendAlert( - "xp/level.go - Fetching user", err.Error(), - "discord_id", c.DiscordID, - "guild_id", g.ID, - ) - utils.SendWarn("Removing user from database", "discord_id", c.DiscordID) - if err = gokord.DB.Delete(c).Error; err != nil { - utils.SendAlert( - "xp/level.go - Removing user from database", err.Error(), - "discord_id", c.DiscordID, - "guild_id", g.ID, - ) - } - continue - } - if u.Bot { - continue - } - if _, err = dg.GuildMember(g.ID, c.DiscordID); err != nil { - utils.SendAlert( - "xp/level.go - Fetching member", err.Error(), - "discord_id", c.DiscordID, - "guild_id", g.ID, - ) - utils.SendWarn( - "Removing user from guild in database", - "discord_id", c.DiscordID, - "guild_id", g.ID, - ) - if err = gokord.DB.Where("guild_id = ?", g.ID).Delete(c).Error; err != nil { - utils.SendAlert( - "xp/level.go - Removing user from guild in database", err.Error(), - "discord_id", c.DiscordID, - "guild_id", g.ID, - ) - } - continue - } - wg.Add(1) - go func() { - XPUpdate(dg, c) - wg.Done() - }() - } - wg.Wait() // finish the entire guild before starting another - utils.SendDebug("Periodic reduce, guild finished", "guild", g.Name) - time.Sleep(15 * time.Second) // sleep prevents from spamming the Discord API and the database - } - utils.SendDebug("Periodic reduce finished", "len(guilds)", len(dg.State.Guilds)) -} diff --git a/xp/member.go b/xp/member.go deleted file mode 100644 index ad9e6c5..0000000 --- a/xp/member.go +++ /dev/null @@ -1,296 +0,0 @@ -package xp - -import ( - "context" - "errors" - "fmt" - "github.com/anhgelus/gokord" - "github.com/anhgelus/gokord/utils" - "github.com/bwmarrin/discordgo" - "github.com/redis/go-redis/v9" - "gorm.io/gorm" - "math" - "strconv" - "time" -) - -type Copaing struct { - gorm.Model - DiscordID string `gorm:"not null"` - XP uint `gorm:"default:0"` - GuildID string `gorm:"not null"` -} - -type leftCopaing struct { - ID uint - StopDelete chan<- interface{} -} - -var ( - redisClient *redis.Client - - leftCopaingsMap = map[string]*leftCopaing{} -) - -const ( - LastEvent = "last_event" - AlreadyRemoved = "already_removed" -) - -func GetCopaing(discordID string, guildID string) *Copaing { - c := Copaing{DiscordID: discordID, GuildID: guildID} - if err := c.Load(); err != nil { - utils.SendAlert( - "xp/member.go - Loading copaing", - err.Error(), - "discord_id", - discordID, - "guild_id", - guildID, - ) - return nil - } - return &c -} - -func (c *Copaing) Load() error { - // check if user left in the past 48 hours - k := c.GuildID + ":" + c.DiscordID - l, ok := leftCopaingsMap[k] - if !ok || l == nil { - // if not, common first or create - return gokord.DB.Where("discord_id = ? and guild_id = ?", c.DiscordID, c.GuildID).FirstOrCreate(c).Error - } - // else, getting last data - tmp := Copaing{ - Model: gorm.Model{ - ID: c.ID, - }, - DiscordID: c.DiscordID, - GuildID: c.GuildID, - } - if err := gokord.DB.Unscoped().Find(&tmp).Error; err != nil { - // if error, avoid getting old data and use new one - utils.SendAlert( - "xp/member.go - Getting copaing in soft delete", err.Error(), - "discord_id", c.DiscordID, - "guild_id", c.DiscordID, - "last_id", l.ID, - ) - return gokord.DB.Where("discord_id = ? and guild_id = ?", c.DiscordID, c.GuildID).FirstOrCreate(c).Error - } - // resetting internal data - tmp.Model = gorm.Model{} - l.StopDelete <- true - leftCopaingsMap[k] = nil - // creating new data - err := gokord.DB.Create(&tmp).Error - if err != nil { - return err - } - // delete old data - if err = gokord.DB.Unscoped().Delete(&tmp).Error; err != nil { - utils.SendAlert( - "xp/member.go - Deleting copaing in soft delete", err.Error(), - "discord_id", c.DiscordID, - "guild_id", c.DiscordID, - "last_id", l.ID, - ) - } - return nil -} - -func (c *Copaing) Save() error { - return gokord.DB.Save(c).Error -} - -func (c *Copaing) GenKey(key string) string { - return fmt.Sprintf("%s:%s:%s", c.GuildID, c.DiscordID, key) -} - -func (c *Copaing) AddXP(s *discordgo.Session, m *discordgo.Member, xp uint, fn func(uint, uint)) { - pastLevel := Level(c.XP) - old := c.XP - c.XP += xp - if err := c.Save(); err != nil { - utils.SendAlert( - "xp/level.go - Saving copaing", - err.Error(), - "xp", - c.XP, - "discord_id", - c.DiscordID, - "guild_id", - c.GuildID, - ) - c.XP = old - return - } - newLevel := Level(c.XP) - if newLevel > pastLevel { - fn(c.XP, newLevel) - onNewLevel(s, m, newLevel) - } -} - -func (c *Copaing) SetLastEvent() { - client, err := getRedisClient() - if err != nil { - utils.SendAlert("xp/member.go - Getting redis client (set)", err.Error()) - return - } - t := time.Now().Unix() - err = client.Set(context.Background(), c.GenKey(LastEvent), strconv.FormatInt(t, 10), 0).Err() - if err != nil { - utils.SendAlert("xp/member.go - Setting last event", err.Error(), "time", t, "base_key", c.GenKey("")) - return - } - err = client.Set(context.Background(), c.GenKey(AlreadyRemoved), "0", 0).Err() - if err != nil { - utils.SendAlert( - "xp/member.go - Setting already removed to 0", - err.Error(), - "time", - t, - "base_key", - c.GenKey(""), - ) - return - } -} - -func (c *Copaing) HourSinceLastEvent() uint { - client, err := getRedisClient() - if err != nil { - utils.SendAlert("xp/member.go - Getting redis client (get)", err.Error()) - return 0 - } - res := client.Get(context.Background(), c.GenKey(LastEvent)) - if errors.Is(res.Err(), redis.Nil) { - return 0 - } else if res.Err() != nil { - utils.SendAlert("xp/member.go - Getting last event", res.Err().Error(), "base_key", c.GenKey("")) - return 0 - } - t := time.Now().Unix() - last, err := strconv.Atoi(res.Val()) - if err != nil { - utils.SendAlert( - "xp/member.go - Converting time fetched into int (last event)", - err.Error(), - "base_key", - c.GenKey(""), - "val", - res.Val(), - ) - return 0 - } - if gokord.Debug { - return uint(math.Floor(float64(t-int64(last)) / 60)) // not hours of unix, is minutes of unix - } - return utils.HoursOfUnix(t - int64(last)) -} - -func (c *Copaing) AddXPAlreadyRemoved(xp uint) uint { - client, err := getRedisClient() - if err != nil { - utils.SendAlert("xp/member.go - Getting redis client (set)", err.Error()) - return 0 - } - exp := xp + c.XPAlreadyRemoved() - err = client.Set(context.Background(), c.GenKey(AlreadyRemoved), exp, 0).Err() - if err != nil { - utils.SendAlert( - "xp/member.go - Setting already removed", - err.Error(), - "xp already removed", - exp, - "base_key", - c.GenKey(""), - ) - return 0 - } - return exp -} - -func (c *Copaing) XPAlreadyRemoved() uint { - client, err := getRedisClient() - if err != nil { - utils.SendAlert("xp/member.go - Getting redis client (xp)", err.Error()) - return 0 - } - res := client.Get(context.Background(), fmt.Sprintf("%s:%s", c.GenKey(""), AlreadyRemoved)) - if errors.Is(res.Err(), redis.Nil) { - return 0 - } else if res.Err() != nil { - utils.SendAlert("xp/member.go - Getting already removed", res.Err().Error(), "base_key", c.GenKey("")) - return 0 - } - xp, err := strconv.Atoi(res.Val()) - if err != nil { - utils.SendAlert( - "xp/member.go - Converting time fetched into int (already removed)", - err.Error(), - "base_key", - c.GenKey(""), - "val", - res.Val(), - ) - return 0 - } - if xp < 0 { - utils.SendAlert( - "xp/member.go - Assertion xp >= 0", - "xp is negative", - "base_key", - c.GenKey(""), - "xp", - xp, - ) - return 0 - } - return uint(xp) -} - -func (c *Copaing) Reset() { - gokord.DB.Where("guild_id = ? AND discord_id = ?", c.GuildID, c.DiscordID).Delete(c) -} - -func (c *Copaing) AfterDelete(db *gorm.DB) error { - id := c.ID - dID := c.DiscordID - gID := c.GuildID - k := c.GuildID + ":" + c.DiscordID - ch := utils.NewTimer(48*time.Hour, func(stop chan<- interface{}) { - if err := db.Unscoped().Where("id = ?", id).Delete(c).Error; err != nil { - utils.SendAlert( - "xp/member.go - Removing copaing from database", err.Error(), - "discord_id", dID, - "guild_id", gID, - ) - } - stop <- true - leftCopaingsMap[k] = nil - }) - leftCopaingsMap[k] = &leftCopaing{id, ch} - return nil -} - -func getRedisClient() (*redis.Client, error) { - if redisClient == nil { - var err error - redisClient, err = gokord.BaseCfg.GetRedisCredentials().Connect() - return redisClient, err - } - return redisClient, nil -} - -func CloseRedisClient() { - if redisClient == nil { - return - } - err := redisClient.Close() - if err != nil { - utils.SendAlert("xp/member.go - Closing redis client", err.Error()) - } -}