qq_bot/message/location.go

58 lines
1.4 KiB
Go

package message
import (
"encoding/json"
"fmt"
"regexp"
)
// LocationMessage 位置消息
type LocationMessage struct {
Type string `json:"type"`
Data LocationMessageData `json:"data"`
}
type LocationMessageData struct {
Lat float64 `json:"lat"` // 纬度
Lon float64 `json:"lon"` // 经度
Title string `json:"title"` // 标题
Content string `json:"content"` // 内容(地址)
}
func init() {
RegisterMessageType(TypeLocation, func() CQMessage {
return &LocationMessage{Type: TypeLocation}
})
}
func (msg *LocationMessage) SetData(data json.RawMessage) error {
return json.Unmarshal(data, &msg.Data)
}
func (msg *LocationMessage) ToCQString() string {
return fmt.Sprintf("[CQ:location,lat=%f,lon=%f,title=%s,content=%s]",
msg.Data.Lat, msg.Data.Lon, msg.Data.Title, msg.Data.Content)
}
func (msg *LocationMessage) ParseMessage(data string) error {
re := regexp.MustCompile(`\[CQ:location,lat=([\d.]+),lon=([\d.]+),title=(.*?),content=(.*?)\]`)
matches := re.FindStringSubmatch(data)
if len(matches) < 5 {
return fmt.Errorf("位置消息格式不正确")
}
_, err := fmt.Sscanf(matches[1], "%f", &msg.Data.Lat)
if err != nil {
return fmt.Errorf("解析纬度失败: %v", err)
}
_, err = fmt.Sscanf(matches[2], "%f", &msg.Data.Lon)
if err != nil {
return fmt.Errorf("解析经度失败: %v", err)
}
msg.Data.Title = matches[3]
msg.Data.Content = matches[4]
return nil
}