59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package message
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"regexp"
|
|
)
|
|
|
|
// FileMessage 文件消息
|
|
type FileMessage struct {
|
|
Type string `json:"type"`
|
|
Data FileMessageData `json:"data"`
|
|
}
|
|
|
|
type FileMessageData struct {
|
|
File string `json:"file"` // 文件路径
|
|
Name string `json:"name,omitempty"` // 文件名
|
|
URL string `json:"url,omitempty"` // 文件URL
|
|
Path string `json:"path,omitempty"` // 文件路径
|
|
FileID string `json:"file_id,omitempty"` // 文件ID
|
|
FileSize string `json:"file_size,omitempty"` // 文件大小
|
|
FileUnique string `json:"file_unique,omitempty"` // 文件唯一标识
|
|
}
|
|
|
|
func init() {
|
|
RegisterMessageType(TypeFile, func() CQMessage {
|
|
return NewFileMessage()
|
|
})
|
|
}
|
|
|
|
func NewFileMessage() *FileMessage {
|
|
return &FileMessage{Type: TypeFile}
|
|
}
|
|
|
|
func (msg *FileMessage) SetData(data json.RawMessage) error {
|
|
return json.Unmarshal(data, &msg.Data)
|
|
}
|
|
|
|
func (msg *FileMessage) ToCQString() string {
|
|
base := fmt.Sprintf("[CQ:file,file=%s", msg.Data.File)
|
|
if msg.Data.Name != "" {
|
|
base += fmt.Sprintf(",name=%s", msg.Data.Name)
|
|
}
|
|
return base + "]"
|
|
}
|
|
|
|
func (msg *FileMessage) ParseMessage(data string) error {
|
|
re := regexp.MustCompile(`\[CQ:file,file=(.*?)(?:,name=(.*?))?\]`)
|
|
matches := re.FindStringSubmatch(data)
|
|
if len(matches) < 2 {
|
|
return fmt.Errorf("文件消息格式不正确")
|
|
}
|
|
msg.Data.File = matches[1]
|
|
if len(matches) > 2 {
|
|
msg.Data.Name = matches[2]
|
|
}
|
|
return nil
|
|
}
|