qq_bot/message/forward.go

101 lines
2.5 KiB
Go

package message
import (
"encoding/json"
"fmt"
"regexp"
)
// ForwardMessage 转发消息
type ForwardMessage struct {
Type string `json:"type"`
Data ForwardMessageData `json:"data"`
}
type ForwardMessageData struct {
ID string `json:"id"` // 转发消息ID
Content []interface{} `json:"content,omitempty"` // 转发消息内容
}
// NodeMessage 转发消息节点
type NodeMessage struct {
Type string `json:"type"`
Data NodeMessageData `json:"data"`
}
type NodeMessageData struct {
ID string `json:"id,omitempty"` // 转发消息ID
UserID string `json:"user_id,omitempty"` // 发送者QQ号
Nickname string `json:"nickname,omitempty"` // 发送者昵称
Content []interface{} `json:"content,omitempty"` // 消息内容
}
func init() {
RegisterMessageType(TypeForward, func() CQMessage {
return NewForwardMessage()
})
RegisterMessageType(TypeNode, func() CQMessage {
return NewNodeMessage()
})
}
func NewForwardMessage() *ForwardMessage {
return &ForwardMessage{Type: TypeForward}
}
// ForwardMessage methods
func (msg *ForwardMessage) SetData(data json.RawMessage) error {
return json.Unmarshal(data, &msg.Data)
}
func NewNodeMessage() *NodeMessage {
return &NodeMessage{Type: TypeNode}
}
func (msg *ForwardMessage) ToCQString() string {
return fmt.Sprintf("[CQ:forward,id=%s]", msg.Data.ID)
}
func (msg *ForwardMessage) ParseMessage(data string) error {
re := regexp.MustCompile(`\[CQ:forward,id=(.*?)\]`)
matches := re.FindStringSubmatch(data)
if len(matches) < 2 {
return fmt.Errorf("转发消息格式不正确")
}
msg.Data.ID = matches[1]
return nil
}
// NodeMessage methods
func (msg *NodeMessage) SetData(data json.RawMessage) error {
return json.Unmarshal(data, &msg.Data)
}
func (msg *NodeMessage) ToCQString() string {
if msg.Data.ID != "" {
return fmt.Sprintf("[CQ:node,id=%s]", msg.Data.ID)
}
return fmt.Sprintf("[CQ:node,user_id=%s,nickname=%s]", msg.Data.UserID, msg.Data.Nickname)
}
func (msg *NodeMessage) ParseMessage(data string) error {
// 解析已有消息节点
idRe := regexp.MustCompile(`\[CQ:node,id=(.*?)\]`)
matches := idRe.FindStringSubmatch(data)
if len(matches) == 2 {
msg.Data.ID = matches[1]
return nil
}
// 解析自定义消息节点
customRe := regexp.MustCompile(`\[CQ:node,user_id=(.*?),nickname=(.*?)\]`)
matches = customRe.FindStringSubmatch(data)
if len(matches) == 3 {
msg.Data.UserID = matches[1]
msg.Data.Nickname = matches[2]
return nil
}
return fmt.Errorf("转发消息节点格式不正确")
}