kefu/wechathook/routers/wechat.go

76 lines
2.0 KiB
Go

package routers
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"log"
"strings"
"wechathook/service"
)
func Wechat(c *gin.Context) {
// 声明一个map变量来存储JSON数据
var jsonData map[string]interface{}
// 解析JSON数据
if err := c.BindJSON(&jsonData); err != nil {
// 如果解析失败,返回错误信息
c.JSON(400, gin.H{"error": err.Error()})
return
}
// 将JSON数据转换为字符串
jsonBytes, _ := json.Marshal(jsonData)
jsonString := string(jsonBytes)
log.Println("收到数据:", jsonString)
resType := gjson.Get(jsonString, "type").String()
wxId := gjson.Get(jsonString, "wxid").String()
//好友请求
if resType == "D0006" {
v3 := gjson.Get(jsonString, "data.v3").String()
v4 := gjson.Get(jsonString, "data.v4").String()
service.AgreeFirend(v3, v4)
}
//收到消息
fromType := gjson.Get(jsonString, "data.fromType").Int()
if resType == "D0003" && fromType != 3 {
msgSource := gjson.Get(jsonString, "data.msgSource").Int()
atList := gjson.Get(jsonString, "data.atWxidList").String()
fromWxid := gjson.Get(jsonString, "data.fromWxid").String()
msg := gjson.Get(jsonString, "data.msg").String()
//群聊@消息
if fromType == 2 && strings.Contains(atList, wxId) {
SendWechatMsg(gjson.Get(jsonString, "data.finalFromWxid").String(), msg)
}
//私聊消息
if fromType == 1 && msgSource == 0 {
SendWechatMsg(fromWxid, msg)
}
}
c.JSON(200, gin.H{
"message": "pong",
})
}
func SendWechatMsg(fromWxid, msg string) {
reply := ""
//走匹配算法
reply = service.GetReplyFromLocal(msg)
if reply == "" {
//走接口
frientInfoStr, _ := service.GetFirendInfo(fromWxid)
reply, _ = service.GetReplyByAPI(fromWxid, gjson.Get(frientInfoStr, "result.nick").String(), gjson.Get(frientInfoStr, "result.avatarMinUrl").String(),
msg)
}
if reply != "" {
service.SendWechatMsg(fromWxid, reply)
}
}
// 获取微信信息
func GetWechatInfo(c *gin.Context) {
//获取登录状态
respString, _ := service.GetSelfInfo()
c.String(200, respString)
}