aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md2
-rw-r--r--commands/rank.go21
-rw-r--r--commands/top.go1
-rw-r--r--main.go13
-rw-r--r--xp/events.go2
-rw-r--r--xp/functions.go12
-rw-r--r--xp/level.go118
-rw-r--r--xp/member.go143
8 files changed, 303 insertions, 9 deletions
diff --git a/README.md b/README.md
index bedf971..44cee92 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ message (number of different rune)
- $xp-vocal(x)=0.01 x^{1.3}+1$ where $x$ is the time spent in vocal (in second)
- $level(x)=0.2 \sqrt{x}$ where $x$ is the xp
- $level^{-1}(x)=(5x)^2$ where $x$ is the level
-- $lose(x,y)= x^2\cdot 10^{-2+\ln(x/85)}\cdot\lfloor y/500 \rfloor$ where $x$ is the inactivity time (hour) and $y$ is the xp
+- $lose(x,y)= x^2\cdot 10^{-2+\ln(x/85)}\cdot\lfloor y/500 +1 \rfloor$ where $x$ is the inactivity time (hour) and $y$ is the xp
## Technologies
diff --git a/commands/rank.go b/commands/rank.go
index cd37a0c..219977d 100644
--- a/commands/rank.go
+++ b/commands/rank.go
@@ -9,7 +9,8 @@ import (
func Rank(s *discordgo.Session, i *discordgo.InteractionCreate) {
optMap := utils.GenerateOptionMap(i)
- c := xp.Copaing{DiscordID: i.Member.User.ID, GuildID: i.GuildID}
+ 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
msg := "Votre niveau"
m := i.Member
var err error
@@ -24,25 +25,33 @@ func Rank(s *discordgo.Session, i *discordgo.InteractionCreate) {
}
m, err = s.GuildMember(i.GuildID, u.ID)
if err != nil {
- utils.SendAlert("rank.go - Fetching guild member", err.Error())
+ utils.SendAlert(
+ "rank.go - Fetching guild member",
+ err.Error(),
+ "discord_id",
+ u.ID,
+ "guild_id",
+ i.GuildID,
+ )
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())
}
return
}
- c.DiscordID = u.ID
+ c.DiscordID = u.ID // current copaing = member targeted by member who wrote /rank
+ c.Load() // reload copaing (change line before)
+ xp.XPUpdate(s, c) // update xp without resetting event
msg = fmt.Sprintf("Le niveau de %s", m.DisplayName())
}
- c.Load()
lvl := xp.Level(c.XP)
- nxtLvl := xp.XPForLevel(lvl + 1)
+ nxtLvlXP := xp.XPForLevel(lvl + 1)
err = resp.Message(fmt.Sprintf(
"%s : **%d**\n> XP : %d\n> Prochain niveau dans %d XP",
msg,
lvl,
c.XP,
- nxtLvl-lvl,
+ nxtLvlXP-c.XP,
)).Send()
if err != nil {
utils.SendAlert("rank.go - Sending rank", err.Error())
diff --git a/commands/top.go b/commands/top.go
index bc444a3..c0f4dae 100644
--- a/commands/top.go
+++ b/commands/top.go
@@ -9,6 +9,7 @@ import (
)
func Top(s *discordgo.Session, i *discordgo.InteractionCreate) {
+ xp.LastEventUpdate(s, xp.GetCopaing(i.User.ID, i.GuildID))
resp := utils.ResponseBuilder{C: s, I: i}
err := resp.IsDeferred().Send()
if err != nil {
diff --git a/main.go b/main.go
index ed84b8a..d8cdbc2 100644
--- a/main.go
+++ b/main.go
@@ -3,10 +3,12 @@ package main
import (
"flag"
"github.com/anhgelus/gokord"
+ "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/bwmarrin/discordgo"
+ "time"
)
var token string
@@ -120,7 +122,18 @@ func main() {
}
func afterInit(dg *discordgo.Session) {
+ // handlers
dg.AddHandler(xp.OnMessage)
dg.AddHandler(xp.OnVoiceUpdate)
dg.AddHandler(xp.OnLeave)
+
+ // setup timer for periodic reducer
+ d := 24 * time.Hour
+ if gokord.Debug {
+ // reduce time for debug
+ d = time.Minute
+ }
+ utils.NewTimer(d, func(stop chan struct{}) {
+ xp.PeriodicReducer(dg)
+ })
}
diff --git a/xp/events.go b/xp/events.go
index 3895073..7504c77 100644
--- a/xp/events.go
+++ b/xp/events.go
@@ -31,6 +31,7 @@ func OnMessage(s *discordgo.Session, m *discordgo.MessageCreate) {
return
}
c := GetCopaing(m.Author.ID, m.GuildID)
+ LastEventUpdate(s, c)
// add xp
trimmed := utils.TrimMessage(strings.ToLower(m.Content))
m.Member.User = m.Author
@@ -67,6 +68,7 @@ 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)
if cfg.IsDisabled(e.ChannelID) {
return
diff --git a/xp/functions.go b/xp/functions.go
index 196c3d3..7ab57f2 100644
--- a/xp/functions.go
+++ b/xp/functions.go
@@ -1,6 +1,9 @@
package xp
-import "math"
+import (
+ "github.com/anhgelus/gokord"
+ "math"
+)
func XPMessage(length uint, diversity uint) uint {
return uint(math.Floor(
@@ -27,7 +30,12 @@ func XPForLevel(level uint) uint {
}
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)),
+ 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
index 671bf2e..4830298 100644
--- a/xp/level.go
+++ b/xp/level.go
@@ -5,6 +5,8 @@ import (
"github.com/anhgelus/les-copaings-bot/config"
"github.com/bwmarrin/discordgo"
"slices"
+ "sync"
+ "time"
)
func onNewLevel(s *discordgo.Session, m *discordgo.Member, level uint) {
@@ -42,3 +44,119 @@ func onNewLevel(s *discordgo.Session, m *discordgo.Member, level uint) {
}
}
}
+
+func (c *Copaing) OnNewLevel(s *discordgo.Session, level uint) {
+ m, err := s.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(s, m, level)
+}
+
+func LastEventUpdate(s *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(s, lvl)
+ }
+ c.Save()
+ }
+ c.SetLastEvent()
+}
+
+func XPUpdate(s *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(s, lvl)
+ }
+ utils.SendDebug("Save XP", "old", oldXP, "new", c.XP, "user", c.DiscordID)
+ c.Save()
+ }
+}
+
+func PeriodicReducer(s *discordgo.Session) {
+ var wg sync.WaitGroup
+ for _, g := range s.State.Guilds {
+ for _, m := range utils.FetchGuildUser(s, g.ID) {
+ if m.User.Bot {
+ continue
+ }
+ wg.Add(1)
+ go func() {
+ c := GetCopaing(m.User.ID, g.ID)
+ XPUpdate(s, c)
+ wg.Done()
+ }()
+ }
+ wg.Wait() // finish the entire guild before starting another
+ utils.SendDebug("Periodic reduce, guild finished", "guild", g.Name)
+ time.Sleep(10 * time.Second) // sleep prevents from spamming the Discord API and the database
+ }
+ utils.SendDebug("Periodic reduce finished", "len(guilds)", len(s.State.Guilds))
+}
diff --git a/xp/member.go b/xp/member.go
index 4f1e6ee..bbf013c 100644
--- a/xp/member.go
+++ b/xp/member.go
@@ -1,11 +1,17 @@
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 {
@@ -17,6 +23,11 @@ type Copaing struct {
var redisClient *redis.Client
+const (
+ LastEvent = "last_event"
+ AlreadyRemoved = "already_removed"
+)
+
func GetCopaing(discordID string, guildID string) *Copaing {
c := Copaing{DiscordID: discordID, GuildID: guildID}
return c.Load()
@@ -42,6 +53,138 @@ func (c *Copaing) AddXP(s *discordgo.Session, m *discordgo.Member, xp uint, fn f
}
}
+func (c *Copaing) SetLastEvent() {
+ client, err := getRedisClient()
+ if err != nil {
+ utils.SendAlert("xp/member.go - Getting redis client (set)", err.Error())
+ return
+ }
+ u := c.GetUserBase()
+ t := time.Now().Unix()
+ err = client.Set(context.Background(), fmt.Sprintf(
+ "%s:%s",
+ u.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", u.GenKey())
+ return
+ }
+ err = client.Set(context.Background(), fmt.Sprintf(
+ "%s:%s",
+ u.GenKey(),
+ AlreadyRemoved,
+ ), "0", 0).Err()
+ if err != nil {
+ utils.SendAlert("xp/member.go - Setting already removed to 0", err.Error(), "time", t, "base_key", u.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
+ }
+ u := c.GetUserBase()
+ res := client.Get(context.Background(), fmt.Sprintf("%s:%s", u.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", u.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",
+ u.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
+ }
+ u := c.GetUserBase()
+ exp := xp + c.XPAlreadyRemoved()
+ err = client.Set(context.Background(), fmt.Sprintf(
+ "%s:%s",
+ u.GenKey(),
+ AlreadyRemoved,
+ ), exp, 0).Err()
+ if err != nil {
+ utils.SendAlert(
+ "xp/member.go - Setting already removed",
+ err.Error(),
+ "xp already removed",
+ exp,
+ "base_key",
+ u.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
+ }
+ u := c.GetUserBase()
+ res := client.Get(context.Background(), fmt.Sprintf("%s:%s", u.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", u.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",
+ u.GenKey(),
+ "val",
+ res.Val(),
+ )
+ return 0
+ }
+ if xp < 0 {
+ utils.SendAlert(
+ "xp/member.go - Assertion xp >= 0",
+ "xp is negative",
+ "base_key",
+ u.GenKey(),
+ "xp",
+ xp,
+ )
+ return 0
+ }
+ return uint(xp)
+}
+
+func (c *Copaing) GetUserBase() *gokord.UserBase {
+ return &gokord.UserBase{DiscordID: c.DiscordID, GuildID: c.GuildID}
+}
+
func getRedisClient() (*redis.Client, error) {
if redisClient == nil {
var err error