121 lines
2.9 KiB
Go
121 lines
2.9 KiB
Go
package kfccrazy
|
|
|
|
import (
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.lxtend.com/lixiangwuxian/qqbot/constants"
|
|
"git.lxtend.com/lixiangwuxian/qqbot/handler"
|
|
"git.lxtend.com/lixiangwuxian/qqbot/model"
|
|
"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
|
|
"git.lxtend.com/lixiangwuxian/qqbot/util"
|
|
)
|
|
|
|
// KfcCrazy GORM模型
|
|
type KfcCrazy struct {
|
|
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
Content string `json:"content" gorm:"column:content;not null"`
|
|
CreatedBy string `json:"created_by" gorm:"column:created_by;not null"`
|
|
CreatedAt time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (KfcCrazy) TableName() string {
|
|
return "kfc_crazy"
|
|
}
|
|
|
|
func init() {
|
|
// handler.RegisterHelpInform("疯狂星期四", "疯狂星期四", "随机输出疯狂星期四文案")
|
|
// handler.RegisterHandler("疯狂星期四", pickKfc, constants.LEVEL_USER)
|
|
// handler.RegisterHelpInform("疯狂星期四文案添加", "疯狂星期四文案添加", "添加疯狂星期四文案")
|
|
handler.RegisterHandler("疯狂星期四文案添加", storeKfc, constants.LEVEL_TRUSTED)
|
|
|
|
// 使用GORM自动迁移替代手写SQL
|
|
sqlite3.AutoMigrate(&KfcCrazy{})
|
|
}
|
|
|
|
func storeKfc(msg model.Message) (reply *model.Reply) {
|
|
// 分割消息获取文案内容
|
|
tokens := util.SplitN(msg.RawMsg, 2)
|
|
if len(tokens) < 2 {
|
|
return &model.Reply{
|
|
ReplyMsg: "请输入要添加的疯狂星期四文案",
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|
|
|
|
content := strings.TrimSpace(tokens[1])
|
|
if content == "" {
|
|
return &model.Reply{
|
|
ReplyMsg: "文案内容不能为空",
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|
|
|
|
// 存储文案到数据库
|
|
kfcData := KfcCrazy{
|
|
Content: content,
|
|
CreatedBy: strconv.FormatInt(msg.UserId, 10),
|
|
}
|
|
|
|
db := sqlite3.GetGormDB()
|
|
result := db.Create(&kfcData)
|
|
if result.Error != nil {
|
|
return &model.Reply{
|
|
ReplyMsg: "保存文案失败",
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|
|
|
|
return &model.Reply{
|
|
ReplyMsg: "文案添加成功",
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|
|
|
|
func pickKfc(msg model.Message) (reply *model.Reply) {
|
|
// 判断是否是周四
|
|
if time.Now().Weekday() != time.Thursday {
|
|
return nil
|
|
}
|
|
|
|
db := sqlite3.GetGormDB()
|
|
|
|
// 获取文案总数
|
|
var count int64
|
|
result := db.Model(&KfcCrazy{}).Count(&count)
|
|
if result.Error != nil {
|
|
return &model.Reply{
|
|
ReplyMsg: "获取文案失败",
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|
|
|
|
if count == 0 {
|
|
return nil
|
|
}
|
|
|
|
// 随机获取一条文案
|
|
var kfcData KfcCrazy
|
|
result = db.Order("RANDOM()").First(&kfcData)
|
|
if result.Error != nil {
|
|
return &model.Reply{
|
|
ReplyMsg: "获取文案失败",
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|
|
|
|
return &model.Reply{
|
|
ReplyMsg: kfcData.Content,
|
|
ReferOriginMsg: true,
|
|
FromMsg: msg,
|
|
}
|
|
}
|