diff --git a/db/level.go b/db/level.go index 503b380..4552752 100644 --- a/db/level.go +++ b/db/level.go @@ -1,7 +1,6 @@ package db import ( - "fmt" "time" "github.com/jinzhu/gorm" @@ -13,10 +12,19 @@ type PlayerLevel struct { XP int64 } -func IncrementXP(userID string, value int64) { - db.Where(&PlayerLevel{UserID: userID}). +func GetXP(userID string) int64 { + result := PlayerLevel{ + UserID: userID, + } + db.Where(&result).First(&result) + return result.XP +} + +func IncrementXP(userID string, value int64, newTime time.Time) { + db.Model(&PlayerLevel{}). + Where(&PlayerLevel{UserID: userID}). UpdateColumn("xp", gorm.Expr("xp + ?", value)). - UpdateColumn("last_active", time.Now()) + UpdateColumn("last_active", newTime) } func GetLastActive(userID string) time.Time { diff --git a/level/listener.go b/level/listener.go index 494393c..11190ad 100644 --- a/level/listener.go +++ b/level/listener.go @@ -2,12 +2,33 @@ package level import ( "github.com/bwmarrin/discordgo" + + "gitea.teamortix.com/chanbakjsd/Milen/db" + "gitea.teamortix.com/chanbakjsd/Milen/util" ) var ShouldListen = true func Event(dg *discordgo.Session, m *discordgo.MessageCreate) { - if m.Author.Bot || ShouldListen { + if m.Author.Bot || !ShouldListen { + return + } + + prevTime := db.GetLastActive(m.Author.ID) + nextTime, err := discordgo.SnowflakeTimestamp(m.ID) + if err != nil { + util.ReportError(dg, err) return } + xp := int64(nextTime.Sub(prevTime).Seconds()) + if xp > int64(len(m.Content)-3)/3 { + xp = int64(len(m.Content)-3) / 3 + } + if xp > 10 { + xp = 10 + } + if xp < 0 { + xp = 0 + } + db.IncrementXP(m.Author.ID, xp, nextTime) } diff --git a/main.go b/main.go index dff08d7..2b16ba9 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import ( "gitea.teamortix.com/chanbakjsd/Milen/commands" "gitea.teamortix.com/chanbakjsd/Milen/db" + "gitea.teamortix.com/chanbakjsd/Milen/level" "gitea.teamortix.com/chanbakjsd/Milen/reactrole" "gitea.teamortix.com/chanbakjsd/Milen/util" ) @@ -25,6 +26,7 @@ func main() { } dg.AddHandler(commands.Event) + dg.AddHandler(level.Event) dg.AddHandler(reactrole.EventAdd) dg.AddHandler(reactrole.EventRemove)