qq_bot/service/jrrp/jrrp.go
2025-07-05 15:46:36 +08:00

90 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package jrrp
import (
"errors"
"math"
"math/rand"
"time"
"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
"gorm.io/gorm"
)
// JrrpData GORM模型
type JrrpData struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
Qqid string `json:"qqid" gorm:"column:qqid;uniqueIndex"`
Date string `json:"date" gorm:"column:date"`
RpValue int `json:"rp_value" gorm:"column:rp_value"`
}
// TableName 指定表名
func (JrrpData) TableName() string {
return "jrrp"
}
// 初始化 SQLite 数据库
func initDB() {
sqlite3.AutoMigrate(&JrrpData{})
}
// 获取今天的日期
func getTodayFullDate() string {
today := time.Now().Format("2006-01-02")
return today
}
// 构造RP值
func rpValueConstructor() (string, int) {
rand.Seed(time.Now().UnixNano())
rpValue := int(math.Floor(math.Sqrt(rand.Float64()*100) * 10))
if rpValue == 0 {
rpValue = 1
}
return getTodayFullDate(), rpValue
}
// Jrrp 结构体
type Jrrp struct {
}
// NewJrrp 创建 Jrrp 实例
func NewJrrp() *Jrrp {
initDB()
return &Jrrp{}
}
// GetJrrp 获取RP值
func (j *Jrrp) GetJrrp(qqid string) (int, error) {
db := sqlite3.GetGormDB()
today := getTodayFullDate()
var jrrpData JrrpData
err := db.Where("qqid = ?", qqid).First(&jrrpData).Error
if errors.Is(err, gorm.ErrRecordNotFound) || jrrpData.Date != today {
// 记录不存在或日期不是今天生成新的RP值
newDate, newRpValue := rpValueConstructor()
newJrrpData := JrrpData{
Qqid: qqid,
Date: newDate,
RpValue: newRpValue,
}
// 使用 GORM 的 Save 方法,如果记录存在则更新,不存在则创建
err = db.Where("qqid = ?", qqid).Assign(JrrpData{
Date: newDate,
RpValue: newRpValue,
}).FirstOrCreate(&newJrrpData).Error
if err != nil {
return 0, err
}
return newRpValue, nil
} else if err != nil {
return 0, err
}
return jrrpData.RpValue, nil
}