1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-06-19 22:15:04 +08:00

Merge pull request #4 from Mrs4s/master

pull
This commit is contained in:
wdvxdr1123 2020-08-29 16:15:19 +08:00 committed by GitHub
commit 38b6fab496
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 328 additions and 89 deletions

View File

@ -26,5 +26,5 @@ jobs:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }} goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }} goarch: ${{ matrix.goarch }}
ldflags: -w -s -X "github.com/Mrs4s/go-cqhttp/coolq.version=${{ env.RELEASE_VERSION }}" ldflags: -w -s -X "github.com/Mrs4s/go-cqhttp/coolq.Version=${{ env.RELEASE_VERSION }}"

1
.gitignore vendored
View File

@ -1 +1,2 @@
vendor/ vendor/
.idea

View File

@ -16,7 +16,7 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
var version = "unknown" var Version = "unknown"
// https://cqhttp.cc/docs/4.15/#/API?id=get_login_info-%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E5%8F%B7%E4%BF%A1%E6%81%AF // https://cqhttp.cc/docs/4.15/#/API?id=get_login_info-%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E5%8F%B7%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetLoginInfo() MSG { func (bot *CQBot) CQGetLoginInfo() MSG {
@ -590,7 +590,7 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
"plugin_build_configuration": "release", "plugin_build_configuration": "release",
"runtime_version": runtime.Version(), "runtime_version": runtime.Version(),
"runtime_os": runtime.GOOS, "runtime_os": runtime.GOOS,
"version": version, "version": Version,
}) })
} }

View File

@ -5,17 +5,19 @@ import (
"encoding/gob" "encoding/gob"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/xujiajun/nutsdb"
"hash/crc32" "hash/crc32"
"path" "path"
"sync" "sync"
"time" "time"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/xujiajun/nutsdb"
) )
type CQBot struct { type CQBot struct {
@ -27,10 +29,13 @@ type CQBot struct {
invitedReqCache sync.Map invitedReqCache sync.Map
joinReqCache sync.Map joinReqCache sync.Map
tempMsgCache sync.Map tempMsgCache sync.Map
oneWayMsgCache sync.Map
} }
type MSG map[string]interface{} type MSG map[string]interface{}
var ForceFragmented = false
func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot { func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot {
bot := &CQBot{ bot := &CQBot{
Client: cli, Client: cli,
@ -65,15 +70,20 @@ func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot {
bot.Client.OnGroupInvited(bot.groupInvitedEvent) bot.Client.OnGroupInvited(bot.groupInvitedEvent)
bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent) bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent)
go func() { go func() {
i := conf.HeartbeatInterval
if i < 1 {
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
return
}
for { for {
time.Sleep(time.Second * 5) time.Sleep(time.Second * i)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(MSG{
"time": time.Now().Unix(), "time": time.Now().Unix(),
"self_id": bot.Client.Uin, "self_id": bot.Client.Uin,
"post_type": "meta_event", "post_type": "meta_event",
"meta_event_type": "heartbeat", "meta_event_type": "heartbeat",
"status": nil, "status": nil,
"interval": 5000, "interval": 1000 * i,
}) })
} }
}() }()
@ -128,7 +138,7 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
newElem = append(newElem, elem) newElem = append(newElem, elem)
} }
m.Elements = newElem m.Elements = newElem
ret := bot.Client.SendGroupMessage(groupId, m) ret := bot.Client.SendGroupMessage(groupId, m, ForceFragmented)
if ret == nil || ret.Id == -1 { if ret == nil || ret.Id == -1 {
log.Warnf("群消息发送失败: 账号可能被风控.") log.Warnf("群消息发送失败: 账号可能被风控.")
return -1 return -1
@ -157,12 +167,15 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
if msg != nil { if msg != nil {
id = msg.Id id = msg.Id
} }
} else { } else if code, ok := bot.tempMsgCache.Load(target); ok {
if code, ok := bot.tempMsgCache.Load(target); ok {
msg := bot.Client.SendTempMessage(code.(int64), target, m) msg := bot.Client.SendTempMessage(code.(int64), target, m)
if msg != nil { if msg != nil {
id = msg.Id id = msg.Id
} }
} else if _, ok := bot.oneWayMsgCache.Load(target); ok {
msg := bot.Client.SendPrivateMessage(target, m)
if msg != nil {
id = msg.Id
} }
} }
if id == -1 { if id == -1 {

View File

@ -6,11 +6,6 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"io/ioutil" "io/ioutil"
"net/url" "net/url"
"path" "path"
@ -18,12 +13,20 @@ import (
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`) var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`)
var typeReg = regexp.MustCompile(`\[CQ:(\w+)`) var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`) var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
var IgnoreInvalidCQCode = false
func ToArrayMessage(e []message.IMessageElement, code int64, raw ...bool) (r []MSG) { func ToArrayMessage(e []message.IMessageElement, code int64, raw ...bool) (r []MSG) {
ur := false ur := false
if len(raw) != 0 { if len(raw) != 0 {
@ -198,8 +201,12 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
} }
elem, err := bot.ToElement(t, d, group) elem, err := bot.ToElement(t, d, group)
if err != nil { if err != nil {
log.Warnf("转换CQ码到MiraiGo Element时出现错误: %v 将原样发送.", err) if !IgnoreInvalidCQCode {
log.Warnf("转换CQ码 %v 到MiraiGo Element时出现错误: %v 将原样发送.", code, err)
r = append(r, message.NewText(code)) r = append(r, message.NewText(code))
} else {
log.Warnf("转换CQ码 %v 到MiraiGo Element时出现错误: %v 将忽略.", code, err)
}
continue continue
} }
r = append(r, elem) r = append(r, elem)
@ -360,12 +367,18 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
if group { if group {
rsp, err := bot.Client.QueryGroupImage(1, hash, size) rsp, err := bot.Client.QueryGroupImage(1, hash, size)
if err != nil { if err != nil {
if url != "" {
return bot.ToElement(t, map[string]string{"file": url}, group)
}
return nil, err return nil, err
} }
return rsp, nil return rsp, nil
} }
rsp, err := bot.Client.QueryFriendImage(1, hash, size) rsp, err := bot.Client.QueryFriendImage(1, hash, size)
if err != nil { if err != nil {
if url != "" {
return bot.ToElement(t, map[string]string{"file": url}, group)
}
return nil, err return nil, err
} }
return rsp, nil return rsp, nil
@ -445,7 +458,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
if len(aid) < 2 { if len(aid) < 2 {
return nil, errors.New("song error") return nil, errors.New("song error")
} }
xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="https://i.y.qq.com/v8/playsong.html?_wv=1&songid=%s&souce=qqshare&source=qqshare&ADTAG=qqshare" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="http://imgcache.qq.com/music/photo/album_500/%s/500_albumpic_%s_0.jpg" src="%s" /><title>%s</title><summary>%s</summary></item><source name="QQ音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>`, xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="https://i.y.qq.com/v8/playsong.html?_wv=1&amp;songid=%s&amp;souce=qqshare&amp;source=qqshare&amp;ADTAG=qqshare" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="http://imgcache.qq.com/music/photo/album_500/%s/500_albumpic_%s_0.jpg" src="%s" /><title>%s</title><summary>%s</summary></item><source name="QQ音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>`,
name, d["id"], aid[:len(aid)-2], aid, name, "", info.Get("track_info.singer.name").Str) name, d["id"], aid[:len(aid)-2], aid, name, "", info.Get("track_info.singer.name").Str)
return &message.ServiceElement{ return &message.ServiceElement{
Id: 60, Id: 60,
@ -453,6 +466,27 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
SubType: "music", SubType: "music",
}, nil }, nil
} }
if d["type"] == "163" {
info, err := global.NeteaseMusicSongInfo(d["id"])
if err != nil {
return nil, err
}
if !info.Exists() {
return nil, errors.New("song not found")
}
name := info.Get("name").Str
artistName := ""
if info.Get("artists.0").Exists() {
artistName = info.Get("artists.0.name").Str
}
xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="http://music.163.com/m/song/%s" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="%s?param=90y90" src="https://music.163.com/song/media/outer/url?id=%s.mp3" /><title>%s</title><summary>%s</summary></item><source name="网易云音乐" icon="https://pic.rmb.bdstatic.com/911423bee2bef937975b29b265d737b3.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=100495085" action="app" a_actionData="com.netease.cloudmusic" i_actionData="tencent100495085://" appid="100495085" /></msg>`,
name, d["id"], info.Get("album.picUrl").Str, d["id"], name, artistName)
return &message.ServiceElement{
Id: 60,
Content: xml,
SubType: "music",
}, nil
}
if d["type"] == "custom" { if d["type"] == "custom" {
xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="%s" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="%s" src="%s"/><title>%s</title><summary>%s</summary></item><source name="音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>`, xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="%s" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="%s" src="%s"/><title>%s</title><summary>%s</summary></item><source name="音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>`,
d["title"], d["url"], d["image"], d["audio"], d["title"], d["content"]) d["title"], d["url"], d["image"], d["audio"], d["title"], d["content"])
@ -463,6 +497,13 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
}, nil }, nil
} }
return nil, errors.New("unsupported music type: " + d["type"]) return nil, errors.New("unsupported music type: " + d["type"])
case "xml":
resId := d["resid"]
template := CQCodeEscapeValue(d["data"])
//println(template)
i, _ := strconv.ParseInt(resId, 10, 64)
msg := global.NewXmlMsg(template, i)
return msg, nil
default: default:
return nil, errors.New("unsupported cq code: " + t) return nil, errors.New("unsupported cq code: " + t)
} }

View File

@ -32,6 +32,9 @@ func ToFormattedMessage(e []message.IMessageElement, code int64, raw ...bool) (r
func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) { func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) {
bot.checkMedia(m.Elements) bot.checkMedia(m.Elements)
cqm := ToStringMessage(m.Elements, 0, true) cqm := ToStringMessage(m.Elements, 0, true)
if !m.Sender.IsFriend {
bot.oneWayMsgCache.Store(m.Sender.Uin, "")
}
log.Infof("收到好友 %v(%v) 的消息: %v", m.Sender.DisplayName(), m.Sender.Uin, cqm) log.Infof("收到好友 %v(%v) 的消息: %v", m.Sender.DisplayName(), m.Sender.Uin, cqm)
fm := MSG{ fm := MSG{
"post_type": "message", "post_type": "message",

View File

@ -22,15 +22,21 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
"password_encrypted": "", "password_encrypted": "",
"enable_db": true, "enable_db": true,
"access_token": "", "access_token": "",
"relogin": false, "relogin": {
"relogin_delay": 0, "enabled": true,
"relogin_delay": 3,
"max_relogin_times": 0
},
"post_message_format": "string", "post_message_format": "string",
"ignore_invalid_cqcode": false,
"force_fragmented": true,
"heartbeat_interval": 5,
"http_config": { "http_config": {
"enabled": true, "enabled": true,
"host": "0.0.0.0", "host": "0.0.0.0",
"port": 5700, "port": 5700,
"timeout": 5, "timeout": 5,
"post_urls": {"url:port": "secret"}, "post_urls": {"url:port": "secret"}
}, },
"ws_config": { "ws_config": {
"enabled": true, "enabled": true,
@ -59,10 +65,20 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
| access_token | string | 同CQHTTP的 `access_token` 用于身份验证 | | access_token | string | 同CQHTTP的 `access_token` 用于身份验证 |
| relogin | bool | 是否自动重新登录 | | relogin | bool | 是否自动重新登录 |
| relogin_delay | int | 重登录延时(秒) | | relogin_delay | int | 重登录延时(秒) |
| max_relogin_times | uint | 最大重登录次数若0则不设置上限 |
| post_message_format | string | 上报信息类型 |
| ignore_invalid_cqcode| bool | 是否忽略错误的CQ码 |
| force_fragmented | bool | 是否强制分片发送群长消息 |
| heartbeat_interval | int64 | 心跳间隔时间单位秒若0则关闭心跳 |
| http_config | object | HTTP API配置 | | http_config | object | HTTP API配置 |
| ws_config | object | Websocket API 配置 | | ws_config | object | Websocket API 配置 |
| ws_reverse_servers | object[] | 反向 Websocket API 配置 | | ws_reverse_servers | object[] | 反向 Websocket API 配置 |
| log_level | string | 指定日志收集级别,将收集的日志单独存放到固定文件中,便于查看日志线索 当前支持 warn,error|
> 注: 开启密码加密后程序将在每次启动时要求输入解密密钥, 密钥错误会导致登录时提示密码错误. > 注: 开启密码加密后程序将在每次启动时要求输入解密密钥, 密钥错误会导致登录时提示密码错误.
> 解密后密码将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取. > 解密后密码将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取.
> 解密密钥在使用完成后并不会留存在内存中, 所以可用相对简单的字符串作为密钥 > 解密密钥在使用完成后并不会留存在内存中, 所以可用相对简单的字符串作为密钥
> 注2: 分片发送为原酷Q发送长消息的老方案, 发送速度更优/兼容性更好。关闭后将优先使用新方案, 能发送更长的消息, 但发送速度更慢,在部分老客户端将无法解析.
> 注3关闭心跳服务可能引起断线请谨慎关闭

View File

@ -119,6 +119,51 @@ Type: `node`
] ]
```` ````
### xml支持
Type: `xml`
范围: **发送**
参数:
| 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ |
| data | string | xml内容xml中的value部分记得实体化处理|
| resid | int32 | 可以不填|
示例: `[CQ:xml,data=xxxx]`
####一些xml样例
####ps:重要xml中的value部分记得html实体化处理后再打加入到cq码中
#### qq音乐
```xml
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="&#91;分享&#93; 十年" sourceMsgId="0" url="https://i.y.qq.com/v8/playsong.html?_wv=1&amp;songid=4830342&amp;souce=qqshare&amp;source=qqshare&amp;ADTAG=qqshare" flag="0" adverSign="0" multiMsgFlag="0" ><item layout="2"><audio cover="http://imgcache.qq.com/music/photo/album_500/26/500_albumpic_89526_0.jpg" src="http://ws.stream.qqmusic.qq.com/C400003mAan70zUy5O.m4a?guid=1535153710&amp;vkey=D5315B8C0603653592AD4879A8A3742177F59D582A7A86546E24DD7F282C3ACF81526C76E293E57EA1E42CF19881C561275D919233333ADE&amp;uin=&amp;fromtag=3" /><title>十年</title><summary>陈奕迅</summary></item><source name="QQ音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>
```
#### 网易音乐
```xml
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="&#91;分享&#93; 十年" sourceMsgId="0" url="http://music.163.com/m/song/409650368" flag="0" adverSign="0" multiMsgFlag="0" ><item layout="2"><audio cover="http://p2.music.126.net/g-Qgb9ibk9Wp_0HWra0xQQ==/16636710440565853.jpg?param=90y90" src="https://music.163.com/song/media/outer/url?id=409650368.mp3" /><title>十年</title><summary>黄梦之</summary></item><source name="网易云音乐" icon="https://pic.rmb.bdstatic.com/911423bee2bef937975b29b265d737b3.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.netease.cloudmusic" i_actionData="tencent100495085://" appid="100495085" /></msg>
```
#### 卡片消息1
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<msg serviceID="1">
<item><title>生死8秒女司机高速急刹他一个操作救下一车性命</title></item>
<source name="官方认证消息" icon="https://qzs.qq.com/ac/qzone_v5/client/auth_icon.png" action="" appid="-1" />
</msg>
```
#### 卡片消息2
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<msg serviceID="1">
<item layout="4">
<title>test title</title>
<picture cover="http://url.cn/5CEwIUy"/>
</item>
</msg>
```
## API ## API

View File

@ -2,6 +2,8 @@ package global
import ( import (
"encoding/json" "encoding/json"
"time"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -12,13 +14,20 @@ type JsonConfig struct {
PasswordEncrypted string `json:"password_encrypted"` PasswordEncrypted string `json:"password_encrypted"`
EnableDB bool `json:"enable_db"` EnableDB bool `json:"enable_db"`
AccessToken string `json:"access_token"` AccessToken string `json:"access_token"`
ReLogin bool `json:"relogin"` ReLogin struct {
Enabled bool `json:"enabled"`
ReLoginDelay int `json:"relogin_delay"` ReLoginDelay int `json:"relogin_delay"`
MaxReloginTimes uint `json:"max_relogin_times"`
} `json:"relogin"`
IgnoreInvalidCQCode bool `json:"ignore_invalid_cqcode"`
ForceFragmented bool `json:"force_fragmented"`
HeartbeatInterval time.Duration `json:"heartbeat_interval"`
HttpConfig *GoCQHttpConfig `json:"http_config"` HttpConfig *GoCQHttpConfig `json:"http_config"`
WSConfig *GoCQWebsocketConfig `json:"ws_config"` WSConfig *GoCQWebsocketConfig `json:"ws_config"`
ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"` ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"`
PostMessageFormat string `json:"post_message_format"` PostMessageFormat string `json:"post_message_format"`
Debug bool `json:"debug"` Debug bool `json:"debug"`
LogLevel string `json:"log_level"`
} }
type CQHttpApiConfig struct { type CQHttpApiConfig struct {
@ -65,9 +74,17 @@ type GoCQReverseWebsocketConfig struct {
func DefaultConfig() *JsonConfig { func DefaultConfig() *JsonConfig {
return &JsonConfig{ return &JsonConfig{
EnableDB: true, EnableDB: true,
ReLogin: true, ReLogin: struct {
Enabled bool `json:"enabled"`
ReLoginDelay int `json:"relogin_delay"`
MaxReloginTimes uint `json:"max_relogin_times"`
}{
Enabled: true,
ReLoginDelay: 3, ReLoginDelay: 3,
MaxReloginTimes: 0,
},
PostMessageFormat: "string", PostMessageFormat: "string",
ForceFragmented: true,
HttpConfig: &GoCQHttpConfig{ HttpConfig: &GoCQHttpConfig{
Enabled: true, Enabled: true,
Host: "0.0.0.0", Host: "0.0.0.0",

View File

@ -3,10 +3,14 @@ package global
import ( import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"github.com/tidwall/gjson" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strconv"
"strings" "strings"
"github.com/Mrs4s/MiraiGo/message"
"github.com/tidwall/gjson"
) )
func GetBytes(url string) ([]byte, error) { func GetBytes(url string) ([]byte, error) {
@ -41,3 +45,27 @@ func QQMusicSongInfo(id string) (gjson.Result, error) {
} }
return gjson.ParseBytes(d).Get("songinfo.data"), nil return gjson.ParseBytes(d).Get("songinfo.data"), nil
} }
func NeteaseMusicSongInfo(id string) (gjson.Result, error) {
d, err := GetBytes(fmt.Sprintf("http://music.163.com/api/song/detail/?id=%s&ids=%%5B%s%%5D", id, id))
if err != nil {
return gjson.Result{}, err
}
return gjson.ParseBytes(d).Get("songs.0"), nil
}
func NewXmlMsg(template string, ResId int64) *message.ServiceElement {
var serviceid string
if ResId == 0 {
serviceid = "2" //默认值2
} else {
serviceid = strconv.FormatInt(ResId, 10)
}
//println(serviceid)
return &message.ServiceElement{
Id: int32(ResId),
Content: template,
ResId: serviceid,
SubType: "xml",
}
}

3
go.mod
View File

@ -3,7 +3,7 @@ module github.com/Mrs4s/go-cqhttp
go 1.14 go 1.14
require ( require (
github.com/Mrs4s/MiraiGo v0.0.0-20200823184203-93de1f445681 github.com/Mrs4s/MiraiGo v0.0.0-20200827182935-51e155ef20da
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
github.com/gin-gonic/gin v1.6.3 github.com/gin-gonic/gin v1.6.3
github.com/gorilla/websocket v1.4.2 github.com/gorilla/websocket v1.4.2
@ -13,6 +13,7 @@ require (
github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible
github.com/lestrrat-go/strftime v1.0.1 // indirect github.com/lestrrat-go/strftime v1.0.1 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.6.0 github.com/sirupsen/logrus v1.6.0
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
github.com/tebeka/strftime v0.1.5 // indirect github.com/tebeka/strftime v0.1.5 // indirect

8
go.sum
View File

@ -1,9 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Mrs4s/MiraiGo v0.0.0-20200823075559-507fe33e842d h1:F7ssNQDHqB7NZVwTeADRY+AxKT3eeSlBzfzeZYTUfxM= github.com/Mrs4s/MiraiGo v0.0.0-20200827182935-51e155ef20da h1:T2Qz4w6sMrBxw+oiwbUa/c996jWYulCAtM+x1L0l3R8=
github.com/Mrs4s/MiraiGo v0.0.0-20200823075559-507fe33e842d/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM= github.com/Mrs4s/MiraiGo v0.0.0-20200827182935-51e155ef20da/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
github.com/Mrs4s/MiraiGo v0.0.0-20200823184203-93de1f445681 h1:hnaJH7BGD+Sb2Xb59SLpRy+f8B3Rx29Qy53ZM0AbIsE=
github.com/Mrs4s/MiraiGo v0.0.0-20200823184203-93de1f445681/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
@ -78,6 +76,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 h1:mZHayPoR0lNmnHyvtYjDeq0zlVHn9K/ZXoy17ylucdo=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5/go.mod h1:GEXHk5HgEKCvEIIrSpFI3ozzG5xOKA2DVlEX/gGnewM=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=

98
main.go
View File

@ -7,15 +7,6 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/server"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
log "github.com/sirupsen/logrus"
easy "github.com/t-tomalak/logrus-easy-formatter"
asciiart "github.com/yinghau76/go-ascii-art"
"image" "image"
"io" "io"
"io/ioutil" "io/ioutil"
@ -25,6 +16,18 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/server"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
easy "github.com/t-tomalak/logrus-easy-formatter"
asciiart "github.com/yinghau76/go-ascii-art"
) )
func init() { func init() {
@ -133,6 +136,46 @@ func main() {
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
return return
} }
// log classified by level
// Collect all records up to the specified level (default level: warn)
logLevel := conf.LogLevel
if logLevel != "" {
date := time.Now().Format("2006-01-02")
var logPathMap lfshook.PathMap
switch conf.LogLevel {
case "warn":
logPathMap = lfshook.PathMap{
log.WarnLevel: path.Join("logs", date+"-warn.log"),
log.ErrorLevel: path.Join("logs", date+"-warn.log"),
log.FatalLevel: path.Join("logs", date+"-warn.log"),
log.PanicLevel: path.Join("logs", date+"-warn.log"),
}
case "error":
logPathMap = lfshook.PathMap{
log.ErrorLevel: path.Join("logs", date+"-error.log"),
log.FatalLevel: path.Join("logs", date+"-error.log"),
log.PanicLevel: path.Join("logs", date+"-error.log"),
}
default:
logPathMap = lfshook.PathMap{
log.WarnLevel: path.Join("logs", date+"-warn.log"),
log.ErrorLevel: path.Join("logs", date+"-warn.log"),
log.FatalLevel: path.Join("logs", date+"-warn.log"),
log.PanicLevel: path.Join("logs", date+"-warn.log"),
}
}
log.AddHook(lfshook.NewHook(
logPathMap,
&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "[%time%] [%lvl%]: %msg% \n",
},
))
}
log.Info("当前版本:", coolq.Version)
if conf.Debug { if conf.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
log.Warnf("已开启Debug模式.") log.Warnf("已开启Debug模式.")
@ -171,6 +214,16 @@ func main() {
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
log.Info("开始尝试登录并同步消息...") log.Info("开始尝试登录并同步消息...")
cli := client.NewClient(conf.Uin, conf.Password) cli := client.NewClient(conf.Uin, conf.Password)
cli.OnLog(func(c *client.QQClient, e *client.LogEvent) {
switch e.Type {
case "INFO":
log.Info("Protocol -> " + e.Message)
case "ERROR":
log.Error("Protocol -> " + e.Message)
case "DEBUG":
log.Debug("Protocol -> " + e.Message)
}
})
rsp, err := cli.Login() rsp, err := cli.Login()
for { for {
global.Check(err) global.Check(err)
@ -210,6 +263,8 @@ func main() {
} else { } else {
coolq.SetMessageFormat(conf.PostMessageFormat) coolq.SetMessageFormat(conf.PostMessageFormat)
} }
coolq.IgnoreInvalidCQCode = conf.IgnoreInvalidCQCode
coolq.ForceFragmented = conf.ForceFragmented
if conf.HttpConfig != nil && conf.HttpConfig.Enabled { if conf.HttpConfig != nil && conf.HttpConfig.Enabled {
server.HttpServer.Run(fmt.Sprintf("%s:%d", conf.HttpConfig.Host, conf.HttpConfig.Port), conf.AccessToken, b) server.HttpServer.Run(fmt.Sprintf("%s:%d", conf.HttpConfig.Host, conf.HttpConfig.Port), conf.AccessToken, b)
for k, v := range conf.HttpConfig.PostUrls { for k, v := range conf.HttpConfig.PostUrls {
@ -225,12 +280,22 @@ func main() {
log.Info("资源初始化完成, 开始处理信息.") log.Info("资源初始化完成, 开始处理信息.")
log.Info("アトリは、高性能ですから!") log.Info("アトリは、高性能ですから!")
cli.OnDisconnected(func(bot *client.QQClient, e *client.ClientDisconnectedEvent) { cli.OnDisconnected(func(bot *client.QQClient, e *client.ClientDisconnectedEvent) {
if conf.ReLogin { if conf.ReLogin.Enabled {
log.Warnf("Bot已离线 (%v),将在 %v 秒后尝试重连.", e.Message, conf.ReLoginDelay) var times uint = 1
time.Sleep(time.Second * time.Duration(conf.ReLoginDelay)) for {
if conf.ReLogin.MaxReloginTimes == 0 {
} else if times > conf.ReLogin.MaxReloginTimes {
break
}
log.Warnf("Bot已离线 (%v),将在 %v 秒后尝试重连. 重连次数:%v",
e.Message, conf.ReLogin.ReLoginDelay, times)
times++
time.Sleep(time.Second * time.Duration(conf.ReLogin.ReLoginDelay))
rsp, err := cli.Login() rsp, err := cli.Login()
if err != nil { if err != nil {
log.Fatalf("重连失败: %v", err) log.Errorf("重连失败: %v", err)
continue
} }
if !rsp.Success { if !rsp.Success {
switch rsp.Error { switch rsp.Error {
@ -239,10 +304,15 @@ func main() {
case client.UnsafeDeviceError: case client.UnsafeDeviceError:
log.Fatalf("重连失败: 设备锁") log.Fatalf("重连失败: 设备锁")
default: default:
log.Fatalf("重连失败: %v", rsp.ErrorMessage) log.Errorf("重连失败: %v", rsp.ErrorMessage)
continue
} }
} }
log.Info("重连成功")
return return
}
log.Fatal("重连失败: 重连次数达到设置的上限值")
} }
b.Release() b.Release()
log.Fatalf("Bot已离线%v", e.Message) log.Fatalf("Bot已离线%v", e.Message)

View File

@ -400,6 +400,7 @@ func getParamOrDefault(c *gin.Context, k, def string) string {
return def return def
} }
func getParam(c *gin.Context, k string) string { func getParam(c *gin.Context, k string) string {
p, _ := getParamWithType(c, k) p, _ := getParamWithType(c, k)
return p return p

View File

@ -319,6 +319,7 @@ func (s *websocketServer) onBotPushEvent(m coolq.MSG) {
for i, l := 0, len(s.eventConn); i < l; i++ { for i, l := 0, len(s.eventConn); i < l; i++ {
conn := s.eventConn[i] conn := s.eventConn[i]
log.Debugf("向WS客户端 %v 推送Event: %v", conn.RemoteAddr().String(), m.ToJson()) log.Debugf("向WS客户端 %v 推送Event: %v", conn.RemoteAddr().String(), m.ToJson())
conn.Lock()
if err := conn.WriteMessage(websocket.TextMessage, []byte(m.ToJson())); err != nil { if err := conn.WriteMessage(websocket.TextMessage, []byte(m.ToJson())); err != nil {
_ = conn.Close() _ = conn.Close()
next := i + 1 next := i + 1
@ -330,7 +331,9 @@ func (s *websocketServer) onBotPushEvent(m coolq.MSG) {
i-- i--
l-- l--
conn = nil conn = nil
continue
} }
conn.Unlock()
} }
} }