kefu/wechatbot/main.go

149 lines
3.5 KiB
Go
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"github.com/eatmoreapple/openwechat"
"github.com/joho/godotenv"
"github.com/skip2/go-qrcode"
"github.com/tidwall/gjson"
"github.com/zh-five/xdaemon"
"golangWechat/lib"
"io/ioutil"
"log"
"os"
"strings"
)
var (
UID string
Nickname string
ApiBase string
ApiKey string
ApiModel string
ReplyType string
ReplyOn string
ReplyKeyword string
)
func main() {
// 获取所有的命令行参数
args := os.Args
if len(args) > 1 && args[1] == "-d" {
initDaemon()
}
bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式
// 注册登陆二维码回调
bot.UUIDCallback = ConsoleQrCode
// 注册消息处理函数
bot.MessageHandler = MessageHandler
// 登陆
reloadStorage := openwechat.NewFileHotReloadStorage("storage.json")
defer reloadStorage.Close()
err := bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption())
if err != nil {
log.Println(err)
return
}
// 获取登陆的用户
self, err := bot.GetCurrentUser()
if err != nil {
log.Println(err)
return
}
UID = self.ID()
Nickname = self.NickName
log.Println("当前登录用户:", UID, Nickname, self)
// 阻塞主goroutine, 直到发生异常或者用户主动退出
bot.Block()
}
func ConsoleQrCode(uuid string) {
fmt.Println("打开个人微信扫描下面的二维码")
q, _ := qrcode.New("https://login.weixin.qq.com/l/"+uuid, qrcode.Medium)
fmt.Println(q.ToString(false))
}
func MessageHandler(msg *openwechat.Message) {
initEnv()
if msg.IsText() {
log.Printf("收到消息:%s\n", msg.Content)
if msg.Content == "" {
return
}
isSend := false
//单聊
sender, err := msg.Sender()
senderId := ""
//群聊
if msg.IsSendByGroup() {
sender, err = msg.SenderInGroup()
senderId = lib.Md5(sender.NickName)
if err == nil {
log.Println("消息发送者:" + sender.NickName)
}
if strings.Contains(msg.Content, "@"+Nickname) || lib.ContainsAny(msg.Content, strings.Split(ReplyKeyword, "|")) {
msg.Content = strings.TrimSpace(strings.ReplaceAll(msg.Content, "@"+Nickname, ""))
isSend = true
} else {
isSend = false
}
} else {
if err == nil {
log.Println("消息发送者:" + sender.NickName)
}
if ReplyType != "GROUP" && sender.NickName != Nickname {
senderId = sender.ID()
isSend = true
}
}
if isSend && ReplyOn == "on" && msg.Content != "" {
replyContent, err := lib.AskGPT(ApiBase, ApiKey, ApiModel, senderId, msg.Content)
//data := url.Values{}
//data.Set("visitor_id", senderId)
//data.Set("content", msg.Content)
//data.Set("visitor_name", sender.NickName)
//res, err := lib.PostForm(Api, data)
if replyContent != "" && err == nil {
log.Println(replyContent)
r := gjson.Get(replyContent, "choices.0.message.content").String()
r = lib.TrimHtml(r)
r = strings.TrimSpace(r)
if r == "" {
return
}
if msg.IsSendByGroup() {
r = fmt.Sprintf("@%s %s", sender.NickName, r)
}
msg.ReplyText(r)
}
}
}
}
// 初始化环境变量
func initEnv() error {
// 读取环境变量
err := godotenv.Load(".env")
ApiBase = os.Getenv("API_BASE")
ApiKey = os.Getenv("API_KEY")
ApiModel = os.Getenv("API_MODEL")
ReplyType = os.Getenv("REPLY_TYPE")
ReplyOn = os.Getenv("REPLY_ON")
ReplyKeyword = os.Getenv("REPLY_KEYWORD")
return err
}
// 初始化守护进程
func initDaemon() {
d := xdaemon.NewDaemon("bot.log")
d.MaxError = 5
d.Run()
//记录pid
ioutil.WriteFile("bot.sock", []byte(fmt.Sprintf("%d %d", os.Getppid(), os.Getpid())), 0666)
}