feat: 完善消息模块,新增多种消息类型和统一消息解析机制

This commit is contained in:
lixiangwuxian
2025-03-08 16:50:38 +08:00
parent 13ea5d7f98
commit f1e2fb6a20
19 changed files with 840 additions and 37 deletions

View File

@@ -1,36 +1,41 @@
package message
import (
"encoding/json"
"fmt"
"regexp"
)
// @某个QQ用户的结构体
// AtMessage @消息
type AtMessage struct {
Type string `json:"type"`
Data AtData `json:"data"`
Type string `json:"type"`
Data AtMessageData `json:"data"`
}
// @消息数据结构体
type AtData struct {
QQ string `json:"qq"`
type AtMessageData struct {
QQ string `json:"qq"` // QQ号"all"表示@全体成员
}
func init() {
RegisterMessageType(TypeAt, func() CQMessage {
return &AtMessage{Type: TypeAt}
})
}
func (msg *AtMessage) SetData(data json.RawMessage) error {
return json.Unmarshal(data, &msg.Data)
}
func (msg *AtMessage) ToCQString() string {
return fmt.Sprintf(`\[CQ:at,qq=%s\]`, msg.Data.QQ)
return fmt.Sprintf("[CQ:at,qq=%s]", msg.Data.QQ)
}
func (msg *AtMessage) ParseMessage(data string) error {
// 使用正则表达式提取QQ号
re := regexp.MustCompile(`\[CQ:at,qq=(\d+)\]`)
re := regexp.MustCompile(`\[CQ:at,qq=(\d+|all)\]`)
matches := re.FindStringSubmatch(data)
if len(matches) < 2 {
return fmt.Errorf("数据格式不正确")
}
// 返回解析后的结构体
msg.Data = AtData{
QQ: matches[1],
return fmt.Errorf("@消息格式不正确")
}
msg.Data.QQ = matches[1]
return nil
}