feat: 完善消息模块,新增多种消息类型和统一消息解析机制
This commit is contained in:
@@ -1,39 +1,46 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// 回复消息结构体
|
||||
// ReplyMessage 回复消息
|
||||
type ReplyMessage struct {
|
||||
Type string `json:"type"`
|
||||
Data ReplyData `json:"data"`
|
||||
Type string `json:"type"`
|
||||
Data ReplyMessageData `json:"data"`
|
||||
}
|
||||
|
||||
// 回复消息数据结构体
|
||||
type ReplyData struct {
|
||||
type ReplyMessageData struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterMessageType(TypeReply, func() CQMessage {
|
||||
return &ReplyMessage{Type: TypeReply}
|
||||
})
|
||||
}
|
||||
|
||||
func (msg *ReplyMessage) SetData(data json.RawMessage) error {
|
||||
return json.Unmarshal(data, &msg.Data)
|
||||
}
|
||||
|
||||
func (msg *ReplyMessage) ToCQString() string {
|
||||
return fmt.Sprintf(`\[CQ:reply,id=%d\]`, msg.Data.ID)
|
||||
return fmt.Sprintf("[CQ:reply,id=%d]", msg.Data.ID)
|
||||
}
|
||||
|
||||
func (msg *ReplyMessage) ParseMessage(data string) error {
|
||||
// 使用正则表达式提取ID
|
||||
re := regexp.MustCompile(`\[CQ:reply,id=(\d+)\]`)
|
||||
matches := re.FindStringSubmatch(data)
|
||||
if len(matches) < 2 {
|
||||
return fmt.Errorf("数据格式不正确")
|
||||
return fmt.Errorf("回复消息格式不正确")
|
||||
}
|
||||
|
||||
id, _ := strconv.Atoi(matches[1])
|
||||
|
||||
// 返回解析后的结构体
|
||||
msg.Data = ReplyData{
|
||||
ID: id,
|
||||
id := 0
|
||||
_, err := fmt.Sscanf(matches[1], "%d", &id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("解析回复ID失败: %v", err)
|
||||
}
|
||||
msg.Data.ID = id
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user