qq_bot/message/music.go

72 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package message
import (
"encoding/json"
"fmt"
"regexp"
)
// MusicMessage 音乐分享消息
type MusicMessage struct {
Type string `json:"type"`
Data MusicMessageData `json:"data"`
}
type MusicMessageData struct {
Type string `json:"type"` // 音乐平台类型(qq、163、kugou、migu、kuwo)
ID string `json:"id,omitempty"` // 音乐ID
URL string `json:"url,omitempty"` // 音乐URL自定义音乐
Audio string `json:"audio,omitempty"` // 音频URL自定义音乐
Title string `json:"title,omitempty"` // 标题(自定义音乐)
Singer string `json:"singer,omitempty"` // 歌手(自定义音乐)
Image string `json:"image,omitempty"` // 封面图(自定义音乐)
}
func init() {
RegisterMessageType(TypeMusic, func() CQMessage {
return NewMusicMessage()
})
}
func NewMusicMessage() *MusicMessage {
return &MusicMessage{Type: TypeMusic}
}
func (msg *MusicMessage) SetData(data json.RawMessage) error {
return json.Unmarshal(data, &msg.Data)
}
func (msg *MusicMessage) ToCQString() string {
if msg.Data.Type == "custom" {
return fmt.Sprintf("[CQ:music,type=custom,url=%s,audio=%s,title=%s,singer=%s,image=%s]",
msg.Data.URL, msg.Data.Audio, msg.Data.Title, msg.Data.Singer, msg.Data.Image)
}
return fmt.Sprintf("[CQ:music,type=%s,id=%s]", msg.Data.Type, msg.Data.ID)
}
func (msg *MusicMessage) ParseMessage(data string) error {
// 解析自定义音乐
customRe := regexp.MustCompile(`\[CQ:music,type=custom,url=(.*?),audio=(.*?),title=(.*?),singer=(.*?),image=(.*?)\]`)
matches := customRe.FindStringSubmatch(data)
if len(matches) == 6 {
msg.Data.Type = "custom"
msg.Data.URL = matches[1]
msg.Data.Audio = matches[2]
msg.Data.Title = matches[3]
msg.Data.Singer = matches[4]
msg.Data.Image = matches[5]
return nil
}
// 解析平台音乐
platformRe := regexp.MustCompile(`\[CQ:music,type=(qq|163|kugou|migu|kuwo),id=(\d+)\]`)
matches = platformRe.FindStringSubmatch(data)
if len(matches) == 3 {
msg.Data.Type = matches[1]
msg.Data.ID = matches[2]
return nil
}
return fmt.Errorf("音乐分享消息格式不正确")
}