forked from lxh/go-wxhelper
57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
|
package message
|
|||
|
|
|||
|
import (
|
|||
|
"encoding/json"
|
|||
|
"log"
|
|||
|
"strings"
|
|||
|
"time"
|
|||
|
"wechat-robot/model/entity"
|
|||
|
"wechat-robot/model/robot"
|
|||
|
"wechat-robot/pkg/types"
|
|||
|
"wechat-robot/service/message"
|
|||
|
)
|
|||
|
|
|||
|
// Message
|
|||
|
// @description: 处理消息
|
|||
|
// @param msg
|
|||
|
// @return err
|
|||
|
func Message(msg []byte) (err error) {
|
|||
|
var m robot.Message
|
|||
|
if err = json.Unmarshal(msg, &m); err != nil {
|
|||
|
log.Printf("消息解析失败: %v", err)
|
|||
|
log.Printf("消息内容: %d -> %v", len(msg), string(msg))
|
|||
|
return
|
|||
|
}
|
|||
|
// 记录原始数据
|
|||
|
m.Raw = string(msg)
|
|||
|
// 提取出群成员信息
|
|||
|
// Sys类型的消息正文不包含微信 Id,所以不需要处理
|
|||
|
if m.IsGroup() && m.Type != types.MsgTypeSys {
|
|||
|
// 群消息,处理一下消息和发信人
|
|||
|
groupUser := strings.Split(m.Content, "\n")[0]
|
|||
|
groupUser = strings.ReplaceAll(groupUser, ":", "")
|
|||
|
// 如果两个id一致,说明是系统发的
|
|||
|
if m.FromUser != groupUser {
|
|||
|
m.GroupUser = groupUser
|
|||
|
}
|
|||
|
// 用户的操作单独提出来处理一下
|
|||
|
m.Content = strings.Join(strings.Split(m.Content, "\n")[1:], "\n")
|
|||
|
}
|
|||
|
log.Printf("收到微信消息\n机器人Id: %s\n消息来源: %s\n群成员: %s\n消息类型: %v\n消息内容: %s", m.ToUser, m.FromUser, m.GroupUser, m.Type, m.Content)
|
|||
|
|
|||
|
// 消息入库
|
|||
|
var ent entity.Message
|
|||
|
ent.MsgId = m.MsgId
|
|||
|
ent.Timestamp = m.CreateTime
|
|||
|
ent.MessageTime = time.Unix(int64(m.CreateTime), 0)
|
|||
|
ent.Content = m.Content
|
|||
|
ent.FromUser = m.FromUser
|
|||
|
ent.GroupUser = m.GroupUser
|
|||
|
ent.ToUser = m.ToUser
|
|||
|
ent.Type = m.Type
|
|||
|
ent.DisplayFullContent = m.DisplayFullContent
|
|||
|
ent.Raw = m.Raw
|
|||
|
err = message.Save(ent)
|
|||
|
return
|
|||
|
}
|