46 lines
915 B
Go
46 lines
915 B
Go
package message
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"regexp"
|
|
)
|
|
|
|
// JsonMessage JSON消息
|
|
type JsonMessage struct {
|
|
Type string `json:"type"`
|
|
Data JsonMessageData `json:"data"`
|
|
}
|
|
|
|
type JsonMessageData struct {
|
|
Data string `json:"data"` // JSON数据
|
|
}
|
|
|
|
func init() {
|
|
RegisterMessageType(TypeJson, func() CQMessage {
|
|
return NewJsonMessage()
|
|
})
|
|
}
|
|
|
|
func NewJsonMessage() *JsonMessage {
|
|
return &JsonMessage{Type: TypeJson}
|
|
}
|
|
|
|
func (msg *JsonMessage) SetData(data json.RawMessage) error {
|
|
return json.Unmarshal(data, &msg.Data)
|
|
}
|
|
|
|
func (msg *JsonMessage) ToCQString() string {
|
|
return fmt.Sprintf("[CQ:json,data=%s]", msg.Data.Data)
|
|
}
|
|
|
|
func (msg *JsonMessage) ParseMessage(data string) error {
|
|
re := regexp.MustCompile(`\[CQ:json,data=(.*?)\]`)
|
|
matches := re.FindStringSubmatch(data)
|
|
if len(matches) < 2 {
|
|
return fmt.Errorf("JSON消息格式不正确")
|
|
}
|
|
msg.Data.Data = matches[1]
|
|
return nil
|
|
}
|