refactor(router): 加入redis保存群聊内容

This commit is contained in:
liyp 2024-09-22 20:39:44 +08:00
parent 43af7b4623
commit 787e3775be
3 changed files with 40 additions and 2 deletions

View file

@ -65,7 +65,7 @@ func AddToContext(key string, message []byte, contextlenth int64) {
// 如果上下文超过5条删除所有上下文
listLength := GetListLength(key)
// log.Println("listLength:", listLength)
if listLength >= contextlenth*2 {
if contextlenth > 0 && listLength >= contextlenth*2 {
rdb.Del(ctx, key) // 删除该用户的所有上下文
}
rdb.RPush(ctx, key, message) // 添加新消息到列表

View file

@ -1,13 +1,25 @@
package utils
import (
"context"
"encoding/json"
"fmt"
"go-bot/config"
"go-bot/tools"
"go-bot/workers"
"regexp"
"strings"
"time"
)
type GroupMessage struct {
GroupID float64 `json:"group_id"`
UserID float64 `json:"user_id"`
Message string `json:"raw_message"`
Role string `json:"role"`
Time string `json:"time"`
}
func Router(data map[string]interface{}) {
// 输出格式化后的JSON
@ -18,6 +30,32 @@ func Router(data map[string]interface{}) {
sender := data["sender"].(map[string]interface{})
role := sender["role"].(string)
mid := data["message_id"].(float64)
redisClient := tools.GetRedisClient()
if redisClient != nil {
var group_message GroupMessage
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return
}
group_message.GroupID = gid
group_message.UserID = uid
group_message.Message = data["raw_message"].(string)
group_message.Role = role
group_message.Time = (time.Unix(int64(data["time"].(float64)), 0).In(loc)).Format("2006-01-02 15:04:05")
jsonString, err := json.Marshal(group_message)
if err != nil {
return
}
key := fmt.Sprintf("group_message:%f:%f", gid, uid)
exists, err := tools.CheckKeyExists(fmt.Sprintf("group_message:%f:%f", gid, uid))
if err != nil || !exists {
redisClient.RPush(context.Background(), key, jsonString, 7*24*time.Hour)
// tools.SetValue(key, string(jsonString), 10*time.Second)
} else {
tools.AddToContext(key, jsonString, 0)
}
}
//包含发送消息的'!'
raw_msg := data["raw_message"].(string)

View file

@ -94,7 +94,7 @@ func (a *AI) GetMsg() string {
log.Println("获取上下文失败:", err)
return "获取上下文失败"
}
log.Println("读取的 JSON 字符串:", message)
// log.Println("读取的 JSON 字符串:", message)
var msg openai.ChatCompletionMessage
err = json.Unmarshal([]byte(message), &msg)