Compare commits

...

3 Commits

Author SHA1 Message Date
李寻欢
91d2fc50e2 🎨 优化传递给AI的消息,去掉艾特机器人那一段字符串 2023-11-17 09:44:14 +08:00
李寻欢
119c2a5359 🎨 优化AI返回内容格式,加个换行 2023-11-13 16:58:52 +08:00
李寻欢
06a64c5e5a 🐛 Fix a bug. 2023-11-13 13:43:59 +08:00

View File

@@ -2,10 +2,14 @@ package handler
import (
"context"
"fmt"
"github.com/sashabaranov/go-openai"
"go-wechat/config"
"go-wechat/entity"
"go-wechat/utils"
"log"
"regexp"
"strings"
)
// handleAtMessage
@@ -15,8 +19,21 @@ func handleAtMessage(m entity.Message) {
if !config.Conf.Ai.Enable {
return
}
// 预处理一下发送的消息,用正则去掉@机器人的内容
re := regexp.MustCompile(`@([^]+)`)
matches := re.FindStringSubmatch(m.Content)
if len(matches) > 0 {
// 过滤掉第一个匹配到的
m.Content = strings.Replace(m.Content, matches[0], "", 1)
}
// 默认使用AI回复
client := openai.NewClient(config.Conf.Ai.ApiKey)
conf := openai.DefaultConfig(config.Conf.Ai.ApiKey)
if config.Conf.Ai.BaseUrl != "" {
conf.BaseURL = fmt.Sprintf("%s/v1", config.Conf.Ai.BaseUrl)
}
client := openai.NewClientWithConfig(conf)
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
@@ -31,10 +48,11 @@ func handleAtMessage(m entity.Message) {
)
if err != nil {
log.Printf("OpenAI聊天发起失败: %v", err.Error())
utils.SendMessage(m.FromUser, m.GroupUser, "AI炸啦~", 0)
return
}
// 发送消息
utils.SendMessage(m.FromUser, m.GroupUser, resp.Choices[0].Message.Content, 0)
utils.SendMessage(m.FromUser, m.GroupUser, "\n"+resp.Choices[0].Message.Content, 0)
}