feat(xp): new add
This commit is contained in:
parent
e0a8f66344
commit
799df74fcd
4 changed files with 45 additions and 17 deletions
|
@ -4,6 +4,8 @@ import (
|
|||
"fmt"
|
||||
"github.com/anhgelus/gokord"
|
||||
"github.com/anhgelus/gokord/utils"
|
||||
"github.com/anhgelus/les-copaings-bot/config"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Copaing struct {
|
||||
|
@ -14,9 +16,11 @@ type Copaing struct {
|
|||
}
|
||||
|
||||
type CopaingXP struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
XP uint `gorm:"default:0"`
|
||||
CopaingID uint `gorm:"not null;constraint:OnDelete:CASCADE;"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
XP uint `gorm:"default:0"`
|
||||
CopaingID uint `gorm:"not null;constraint:OnDelete:CASCADE;"`
|
||||
GuildID string `gorm:"not null;"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
const (
|
||||
|
@ -48,6 +52,30 @@ func (c *Copaing) Load() error {
|
|||
Error
|
||||
}
|
||||
|
||||
func (c *Copaing) GetXP() (uint, error) {
|
||||
cfg := config.GetGuildConfig(c.GuildID)
|
||||
xp := uint(0)
|
||||
y, m, d := time.Unix(time.Now().Unix()-int64(cfg.DaysXPRemains*24*60*60), 0).Date()
|
||||
rows, err := gokord.DB.
|
||||
Model(&CopaingXP{}).
|
||||
Where(fmt.Sprintf("created_at >= '%d-%d-%d' and guild_id = ? and discord_id = ?", y, m, d), c.GuildID, c.DiscordID).
|
||||
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/member.go - Scaning rows", err.Error(), "discord_id", c.DiscordID, "guild_id", c.GuildID)
|
||||
continue
|
||||
}
|
||||
xp += cXP.XP
|
||||
}
|
||||
return xp, nil
|
||||
}
|
||||
|
||||
func (c *Copaing) Save() error {
|
||||
return gokord.DB.Save(c).Error
|
||||
}
|
||||
|
|
13
user/xp.go
13
user/xp.go
|
@ -7,10 +7,10 @@ import (
|
|||
)
|
||||
|
||||
func (c *Copaing) AddXP(s *discordgo.Session, m *discordgo.Member, xp uint, fn func(uint, uint)) {
|
||||
pastLevel := exp.Level(c.XP)
|
||||
old := c.XP
|
||||
c.XP += xp
|
||||
if err := c.Save(); err != nil {
|
||||
old, err := c.GetXP()
|
||||
pastLevel := exp.Level(old)
|
||||
c.XP = append(c.XP, CopaingXP{CopaingID: c.ID, XP: xp, GuildID: c.GuildID})
|
||||
if err = c.Save(); err != nil {
|
||||
utils.SendAlert(
|
||||
"user/xp.go - Saving user",
|
||||
err.Error(),
|
||||
|
@ -21,12 +21,11 @@ func (c *Copaing) AddXP(s *discordgo.Session, m *discordgo.Member, xp uint, fn f
|
|||
"guild_id",
|
||||
c.GuildID,
|
||||
)
|
||||
c.XP = old
|
||||
return
|
||||
}
|
||||
newLevel := exp.Level(c.XP)
|
||||
newLevel := exp.Level(old + xp)
|
||||
if newLevel > pastLevel {
|
||||
fn(c.XP, newLevel)
|
||||
fn(old+xp, newLevel)
|
||||
onNewLevel(s, m, newLevel)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue