mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-05-04 19:17:37 +08:00
Merge branch 'dev' into patch-1
This commit is contained in:
commit
2ce0d145e8
14
.github/workflows/ci.yml
vendored
14
.github/workflows/ci.yml
vendored
@ -27,15 +27,12 @@ jobs:
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
fail-fast: true
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Setup Go environment
|
||||
uses: actions/setup-go@v2.1.3
|
||||
with:
|
||||
go-version: 1.15
|
||||
|
||||
- name: Build binary file
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
@ -47,7 +44,6 @@ jobs:
|
||||
export BINARY_NAME="$BINARY_PREFIX$GOOS_$GOARCH$BINARY_SUFFIX"
|
||||
export CGO_ENABLED=0
|
||||
go build -o "output/$BINARY_NAME" -ldflags "$LD_FLAGS" .
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
if: ${{ !github.head_ref }}
|
||||
@ -55,4 +51,12 @@ jobs:
|
||||
name: ${{ matrix.goos }}_${{ matrix.goarch }}
|
||||
path: output/
|
||||
|
||||
|
||||
golangci:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
with:
|
||||
version: v1.29
|
||||
|
17
README.md
17
README.md
@ -6,7 +6,8 @@
|
||||
|
||||
# go-cqhttp
|
||||
|
||||
_✨ 基于 [Mirai](https://github.com/mamoe/mirai) 以及 [MiraiGo](https://github.com/Mrs4s/MiraiGo) 的 [cqhttp](https://github.com/howmanybots/onebot/blob/master/README.md) golang 原生实现 ✨_
|
||||
_✨ 基于 [Mirai](https://github.com/mamoe/mirai) 以及 [MiraiGo](https://github.com/Mrs4s/MiraiGo) 的 [OneBot](https://github.com/howmanybots/onebot/blob/master/README.md) Golang 原生实现 ✨_
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
@ -23,23 +24,21 @@ _✨ 基于 [Mirai](https://github.com/mamoe/mirai) 以及 [MiraiGo](https://git
|
||||
<a href="https://github.com/Mrs4s/go-cqhttp/actions">
|
||||
<img src="https://github.com/Mrs4s/go-cqhttp/workflows/CI/badge.svg" alt="action">
|
||||
</a>
|
||||
<a href="https://goreportcard.com/report/github.com/Mrs4s/go-cqhttp">
|
||||
<img src="https://goreportcard.com/badge/github.com/Mrs4s/go-cqhttp" alt="GoReportCard">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="http://ishkong.github.io/go-cqhttp-docs">文档</a>
|
||||
<a href="https://docs.go-cqhttp.org/">文档</a>
|
||||
·
|
||||
<a href="https://github.com/Mrs4s/go-cqhttp/releases">下载</a>
|
||||
·
|
||||
<a href="https://ishkong.github.io/go-cqhttp-docs/guide/quick_start.html">开始使用</a>
|
||||
<a href="https://docs.go-cqhttp.org/guide/quick_start.html">开始使用</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
go-cqhttp 在[原版 cqhttp](https://github.com/richardchien/coolq-http-api)的基础上做了部分修改和拓展.
|
||||
|
||||
---
|
||||
|
||||
## 兼容性
|
||||
go-cqhttp兼容[OneBot-v11](https://github.com/howmanybots/onebot/tree/master/v11/specs)绝大多数内容,并在其基础上做了一些扩展,详情请看go-cqhttp的文档
|
||||
|
||||
### 接口
|
||||
|
||||
|
528
coolq/api.go
528
coolq/api.go
@ -4,6 +4,7 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@ -20,14 +21,19 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// Version go-cqhttp的版本信息,在编译时使用ldfalgs进行覆盖
|
||||
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
|
||||
// CQGetLoginInfo 获取登录号信息
|
||||
//
|
||||
// https://git.io/Jtz1I
|
||||
func (bot *CQBot) CQGetLoginInfo() MSG {
|
||||
return OK(MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname})
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=get_friend_list-%E8%8E%B7%E5%8F%96%E5%A5%BD%E5%8F%8B%E5%88%97%E8%A1%A8
|
||||
// CQGetFriendList 获取好友列表
|
||||
//
|
||||
// https://git.io/Jtz1L
|
||||
func (bot *CQBot) CQGetFriendList() MSG {
|
||||
fs := make([]MSG, 0)
|
||||
for _, f := range bot.Client.FriendList {
|
||||
@ -40,7 +46,9 @@ func (bot *CQBot) CQGetFriendList() MSG {
|
||||
return OK(fs)
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=get_group_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%88%97%E8%A1%A8
|
||||
// CQGetGroupList 获取群列表
|
||||
//
|
||||
// https://git.io/Jtz1t
|
||||
func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
|
||||
gs := make([]MSG, 0)
|
||||
if noCache {
|
||||
@ -57,15 +65,32 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
|
||||
return OK(gs)
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=get_group_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetGroupInfo(groupId int64, noCache bool) MSG {
|
||||
group := bot.Client.FindGroup(groupId)
|
||||
// CQGetGroupInfo 获取群信息
|
||||
//
|
||||
// https://git.io/Jtz1O
|
||||
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
if group == nil {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
gid := strconv.FormatInt(groupID, 10)
|
||||
info, err := bot.Client.SearchGroupByKeyword(gid)
|
||||
if err != nil {
|
||||
return Failed(100, "GROUP_SEARCH_ERROR", "群聊搜索失败")
|
||||
}
|
||||
for _, g := range info {
|
||||
if g.Code == groupID {
|
||||
return OK(MSG{
|
||||
"group_id": g.Code,
|
||||
"group_name": g.Name,
|
||||
"max_member_count": 0,
|
||||
"member_count": 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在失败")
|
||||
}
|
||||
if noCache {
|
||||
var err error
|
||||
group, err = bot.Client.GetGroupInfo(groupId)
|
||||
group, err = bot.Client.GetGroupInfo(groupID)
|
||||
if err != nil {
|
||||
return Failed(100, "GET_GROUP_INFO_API_ERROR", err.Error())
|
||||
}
|
||||
@ -78,58 +103,68 @@ func (bot *CQBot) CQGetGroupInfo(groupId int64, noCache bool) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=get_group_member_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%88%90%E5%91%98%E5%88%97%E8%A1%A8
|
||||
func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG {
|
||||
group := bot.Client.FindGroup(groupId)
|
||||
// CQGetGroupMemberList 获取群成员列表
|
||||
//
|
||||
// https://git.io/Jtz13
|
||||
func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
if group == nil {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
if noCache {
|
||||
t, err := bot.Client.GetGroupMembers(group)
|
||||
if err != nil {
|
||||
log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err)
|
||||
log.Warnf("刷新群 %v 成员列表失败: %v", groupID, err)
|
||||
return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
|
||||
}
|
||||
group.Members = t
|
||||
}
|
||||
members := make([]MSG, 0)
|
||||
for _, m := range group.Members {
|
||||
members = append(members, convertGroupMemberInfo(groupId, m))
|
||||
members = append(members, convertGroupMemberInfo(groupID, m))
|
||||
}
|
||||
return OK(members)
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=get_group_member_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%88%90%E5%91%98%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetGroupMemberInfo(groupId, userId int64) MSG {
|
||||
group := bot.Client.FindGroup(groupId)
|
||||
// CQGetGroupMemberInfo 获取群成员信息
|
||||
//
|
||||
// https://git.io/Jtz1s
|
||||
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64) MSG {
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
if group == nil {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
member := group.FindMember(userId)
|
||||
member := group.FindMember(userID)
|
||||
if member == nil {
|
||||
return Failed(100, "MEMBER_NOT_FOUND", "群员不存在")
|
||||
}
|
||||
return OK(convertGroupMemberInfo(groupId, member))
|
||||
return OK(convertGroupMemberInfo(groupID, member))
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetGroupFileSystemInfo(groupId int64) MSG {
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupId)
|
||||
// CQGetGroupFileSystemInfo 扩展API-获取群文件系统信息
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) MSG {
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupID)
|
||||
if err != nil {
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
|
||||
}
|
||||
return OK(fs)
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetGroupRootFiles(groupId int64) MSG {
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupId)
|
||||
// CQGetGroupRootFiles 扩展API-获取群根目录文件列表
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%A0%B9%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
|
||||
func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG {
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupID)
|
||||
if err != nil {
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
|
||||
}
|
||||
files, folders, err := fs.Root()
|
||||
if err != nil {
|
||||
log.Errorf("获取群 %v 根目录文件失败: %v", groupId, err)
|
||||
log.Errorf("获取群 %v 根目录文件失败: %v", groupID, err)
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
|
||||
}
|
||||
return OK(MSG{
|
||||
@ -138,15 +173,18 @@ func (bot *CQBot) CQGetGroupRootFiles(groupId int64) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetGroupFilesByFolderId(groupId int64, folderId string) MSG {
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupId)
|
||||
// CQGetGroupFilesByFolderID 扩展API-获取群子目录文件列表
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%AD%90%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
|
||||
func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG {
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupID)
|
||||
if err != nil {
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
|
||||
}
|
||||
files, folders, err := fs.GetFilesByFolder(folderId)
|
||||
files, folders, err := fs.GetFilesByFolder(folderID)
|
||||
if err != nil {
|
||||
log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupId, folderId, err)
|
||||
log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupID, folderID, err)
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
|
||||
}
|
||||
return OK(MSG{
|
||||
@ -155,8 +193,11 @@ func (bot *CQBot) CQGetGroupFilesByFolderId(groupId int64, folderId string) MSG
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) MSG {
|
||||
url := bot.Client.GetGroupFileUrl(groupId, fileId, busId)
|
||||
// CQGetGroupFileURL 扩展API-获取群文件资源链接
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E8%B5%84%E6%BA%90%E9%93%BE%E6%8E%A5
|
||||
func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) MSG {
|
||||
url := bot.Client.GetGroupFileUrl(groupID, fileID, busID)
|
||||
if url == "" {
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR")
|
||||
}
|
||||
@ -165,6 +206,32 @@ func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) M
|
||||
})
|
||||
}
|
||||
|
||||
// CQUploadGroupFile 扩展API-上传群文件
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E4%B8%8A%E4%BC%A0%E7%BE%A4%E6%96%87%E4%BB%B6
|
||||
func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) MSG {
|
||||
if !global.PathExists(file) {
|
||||
log.Errorf("上传群文件 %v 失败: 文件不存在", file)
|
||||
return Failed(100, "FILE_NOT_FOUND", "文件不存在")
|
||||
}
|
||||
fs, err := bot.Client.GetGroupFileSystem(groupID)
|
||||
if err != nil {
|
||||
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
|
||||
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
|
||||
}
|
||||
if folder == "" {
|
||||
folder = "/"
|
||||
}
|
||||
if err = fs.UploadFile(file, name, folder); err != nil {
|
||||
log.Errorf("上传群 %v 文件 %v 失败: %v", groupID, file, err)
|
||||
return Failed(100, "FILE_SYSTEM_UPLOAD_API_ERROR", err.Error())
|
||||
}
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// CQGetWordSlices 隐藏API-获取中文分词
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E4%B8%AD%E6%96%87%E5%88%86%E8%AF%8D-%E9%9A%90%E8%97%8F-api
|
||||
func (bot *CQBot) CQGetWordSlices(content string) MSG {
|
||||
slices, err := bot.Client.GetWordSegmentation(content)
|
||||
if err != nil {
|
||||
@ -176,14 +243,16 @@ func (bot *CQBot) CQGetWordSlices(content string) MSG {
|
||||
return OK(MSG{"slices": slices})
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=send_group_msg-%E5%8F%91%E9%80%81%E7%BE%A4%E6%B6%88%E6%81%AF
|
||||
func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bool) MSG {
|
||||
// CQSendGroupMessage 发送群消息
|
||||
//
|
||||
// https://git.io/Jtz1c
|
||||
func (bot *CQBot) CQSendGroupMessage(groupID int64, i interface{}, autoEscape bool) MSG {
|
||||
var str string
|
||||
fixAt := func(elem []message.IMessageElement) {
|
||||
for _, e := range elem {
|
||||
if at, ok := e.(*message.AtElement); ok && at.Target != 0 {
|
||||
at.Display = "@" + func() string {
|
||||
mem := bot.Client.FindGroup(groupId).FindMember(at.Target)
|
||||
mem := bot.Client.FindGroup(groupID).FindMember(at.Target)
|
||||
if mem != nil {
|
||||
return mem.DisplayName()
|
||||
}
|
||||
@ -196,11 +265,11 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
|
||||
if m.Type == gjson.JSON {
|
||||
elem := bot.ConvertObjectMessage(m, true)
|
||||
fixAt(elem)
|
||||
mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem})
|
||||
mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
|
||||
if mid == -1 {
|
||||
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
|
||||
}
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(m.String()), mid)
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupID, groupID, limitedString(m.String()), mid)
|
||||
return OK(MSG{"message_id": mid})
|
||||
}
|
||||
str = func() string {
|
||||
@ -223,15 +292,18 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
|
||||
elem = bot.ConvertStringMessage(str, true)
|
||||
}
|
||||
fixAt(elem)
|
||||
mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem})
|
||||
mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
|
||||
if mid == -1 {
|
||||
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
|
||||
}
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(str), mid)
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupID, groupID, limitedString(str), mid)
|
||||
return OK(MSG{"message_id": mid})
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQSendGroupForwardMessage(groupId int64, m gjson.Result) MSG {
|
||||
// CQSendGroupForwardMessage 扩展API-发送合并转发(群)
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-%E7%BE%A4
|
||||
func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
|
||||
if m.Type != gjson.JSON {
|
||||
return Failed(100)
|
||||
}
|
||||
@ -298,7 +370,7 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupId int64, m gjson.Result) MSG {
|
||||
SenderId: uin,
|
||||
SenderName: name,
|
||||
Time: int32(msgTime),
|
||||
Message: []message.IMessageElement{bot.Client.UploadGroupForwardMessage(groupId, &message.ForwardMessage{Nodes: taowa})},
|
||||
Message: []message.IMessageElement{bot.Client.UploadGroupForwardMessage(groupID, &message.ForwardMessage{Nodes: taowa})},
|
||||
})
|
||||
return
|
||||
}
|
||||
@ -308,18 +380,18 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupId int64, m gjson.Result) MSG {
|
||||
var newElem []message.IMessageElement
|
||||
for _, elem := range content {
|
||||
if img, ok := elem.(*LocalImageElement); ok {
|
||||
gm, err := bot.UploadLocalImageAsGroup(groupId, img)
|
||||
gm, err := bot.UploadLocalImageAsGroup(groupID, img)
|
||||
if err != nil {
|
||||
log.Warnf("警告:群 %v 图片上传失败: %v", groupId, err)
|
||||
log.Warnf("警告:群 %v 图片上传失败: %v", groupID, err)
|
||||
continue
|
||||
}
|
||||
newElem = append(newElem, gm)
|
||||
continue
|
||||
}
|
||||
if video, ok := elem.(*LocalVideoElement); ok {
|
||||
gm, err := bot.UploadLocalVideo(groupId, video)
|
||||
gm, err := bot.UploadLocalVideo(groupID, video)
|
||||
if err != nil {
|
||||
log.Warnf("警告:群 %v 视频上传失败: %v", groupId, err)
|
||||
log.Warnf("警告:群 %v 视频上传失败: %v", groupID, err)
|
||||
continue
|
||||
}
|
||||
newElem = append(newElem, gm)
|
||||
@ -346,7 +418,7 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupId int64, m gjson.Result) MSG {
|
||||
sendNodes = convert(m)
|
||||
}
|
||||
if len(sendNodes) > 0 {
|
||||
gm := bot.Client.SendGroupForwardMessage(groupId, &message.ForwardMessage{Nodes: sendNodes})
|
||||
gm := bot.Client.SendGroupForwardMessage(groupID, &message.ForwardMessage{Nodes: sendNodes})
|
||||
return OK(MSG{
|
||||
"message_id": bot.InsertGroupMessage(gm),
|
||||
})
|
||||
@ -354,17 +426,19 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupId int64, m gjson.Result) MSG {
|
||||
return Failed(100)
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=send_private_msg-%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF
|
||||
func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape bool) MSG {
|
||||
// CQSendPrivateMessage 发送私聊消息
|
||||
//
|
||||
// https://git.io/Jtz1l
|
||||
func (bot *CQBot) CQSendPrivateMessage(userID int64, i interface{}, autoEscape bool) MSG {
|
||||
var str string
|
||||
if m, ok := i.(gjson.Result); ok {
|
||||
if m.Type == gjson.JSON {
|
||||
elem := bot.ConvertObjectMessage(m, false)
|
||||
mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem})
|
||||
mid := bot.SendPrivateMessage(userID, &message.SendingMessage{Elements: elem})
|
||||
if mid == -1 {
|
||||
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
|
||||
}
|
||||
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(m.String()), mid)
|
||||
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(m.String()), mid)
|
||||
return OK(MSG{"message_id": mid})
|
||||
}
|
||||
str = func() string {
|
||||
@ -385,18 +459,20 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
|
||||
} else {
|
||||
elem = bot.ConvertStringMessage(str, false)
|
||||
}
|
||||
mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem})
|
||||
mid := bot.SendPrivateMessage(userID, &message.SendingMessage{Elements: elem})
|
||||
if mid == -1 {
|
||||
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
|
||||
}
|
||||
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(str), mid)
|
||||
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(str), mid)
|
||||
return OK(MSG{"message_id": mid})
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_card-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%90%8D%E7%89%87%EF%BC%88%E7%BE%A4%E5%A4%87%E6%B3%A8%EF%BC%89
|
||||
func (bot *CQBot) CQSetGroupCard(groupId, userId int64, card string) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
if m := g.FindMember(userId); m != nil {
|
||||
// CQSetGroupCard 设置群名片(群备注)
|
||||
//
|
||||
// https://git.io/Jtz1B
|
||||
func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
if m := g.FindMember(userID); m != nil {
|
||||
m.EditCard(card)
|
||||
return OK(nil)
|
||||
}
|
||||
@ -404,10 +480,12 @@ func (bot *CQBot) CQSetGroupCard(groupId, userId int64, card string) MSG {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94
|
||||
func (bot *CQBot) CQSetGroupSpecialTitle(groupId, userId int64, title string) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
if m := g.FindMember(userId); m != nil {
|
||||
// CQSetGroupSpecialTitle 设置群组专属头衔
|
||||
//
|
||||
// https://git.io/Jtz10
|
||||
func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
if m := g.FindMember(userID); m != nil {
|
||||
m.EditSpecialTitle(title)
|
||||
return OK(nil)
|
||||
}
|
||||
@ -415,65 +493,91 @@ func (bot *CQBot) CQSetGroupSpecialTitle(groupId, userId int64, title string) MS
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
// CQSetGroupName 设置群名
|
||||
//
|
||||
// https://git.io/Jtz12
|
||||
func (bot *CQBot) CQSetGroupName(groupID int64, name string) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
g.UpdateName(name)
|
||||
return OK(nil)
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
// CQSetGroupMemo 扩展API-发送群公告
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%BE%A4%E5%85%AC%E5%91%8A
|
||||
func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
g.UpdateMemo(msg)
|
||||
return OK(nil)
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA
|
||||
func (bot *CQBot) CQSetGroupKick(groupId, userId int64, msg string, block bool) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
if m := g.FindMember(userId); m != nil {
|
||||
m.Kick(msg, block)
|
||||
// CQSetGroupKick 群组踢人
|
||||
//
|
||||
// https://git.io/Jtz1V
|
||||
func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
if m := g.FindMember(userID); m != nil {
|
||||
err := m.Kick(msg, block)
|
||||
if err != nil {
|
||||
return Failed(100, "NOT_MANAGEABLE", "机器人权限不足")
|
||||
}
|
||||
return OK(nil)
|
||||
}
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80
|
||||
func (bot *CQBot) CQSetGroupBan(groupId, userId int64, duration uint32) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
if m := g.FindMember(userId); m != nil {
|
||||
m.Mute(duration)
|
||||
// CQSetGroupBan 群组单人禁言
|
||||
//
|
||||
// https://git.io/Jtz1w
|
||||
func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
if m := g.FindMember(userID); m != nil {
|
||||
err := m.Mute(duration)
|
||||
if err != nil {
|
||||
if duration >= 2592000 {
|
||||
return Failed(100, "DURATION_IS_NOT_IN_RANGE", "非法的禁言时长")
|
||||
}
|
||||
return Failed(100, "NOT_MANAGEABLE", "机器人权限不足")
|
||||
}
|
||||
return OK(nil)
|
||||
}
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80
|
||||
func (bot *CQBot) CQSetGroupWholeBan(groupId int64, enable bool) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
// CQSetGroupWholeBan 群组全员禁言
|
||||
//
|
||||
// https://git.io/Jtz1o
|
||||
func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
g.MuteAll(enable)
|
||||
return OK(nil)
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84
|
||||
func (bot *CQBot) CQSetGroupLeave(groupId int64) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
// CQSetGroupLeave 退出群组
|
||||
//
|
||||
// https://git.io/Jtz1K
|
||||
func (bot *CQBot) CQSetGroupLeave(groupID int64) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
g.Quit()
|
||||
return OK(nil)
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetAtAllRemain(groupId int64) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
i, err := bot.Client.GetAtAllRemain(groupId)
|
||||
// CQGetAtAllRemain 扩展API-获取群 @全体成员 剩余次数
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4-%E5%85%A8%E4%BD%93%E6%88%90%E5%91%98-%E5%89%A9%E4%BD%99%E6%AC%A1%E6%95%B0
|
||||
func (bot *CQBot) CQGetAtAllRemain(groupID int64) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
i, err := bot.Client.GetAtAllRemain(groupID)
|
||||
if err != nil {
|
||||
return Failed(100, "GROUP_REMAIN_API_ERROR", err.Error())
|
||||
}
|
||||
@ -482,7 +586,9 @@ func (bot *CQBot) CQGetAtAllRemain(groupId int64) MSG {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82
|
||||
// CQProcessFriendRequest 处理加好友请求
|
||||
//
|
||||
// https://git.io/Jtz11
|
||||
func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
|
||||
req, ok := bot.friendReqCache.Load(flag)
|
||||
if !ok {
|
||||
@ -496,7 +602,9 @@ func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%EF%BC%8F%E9%82%80%E8%AF%B7
|
||||
// CQProcessGroupRequest 处理加群请求/邀请
|
||||
//
|
||||
// https://git.io/Jtz1D
|
||||
func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) MSG {
|
||||
msgs, err := bot.Client.GetGroupSystemMessages()
|
||||
if err != nil {
|
||||
@ -538,52 +646,59 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
|
||||
return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF
|
||||
func (bot *CQBot) CQDeleteMessage(messageId int32) MSG {
|
||||
msg := bot.GetMessage(messageId)
|
||||
// CQDeleteMessage 撤回消息
|
||||
//
|
||||
// https:// git.io/Jtz1y
|
||||
func (bot *CQBot) CQDeleteMessage(messageID int32) MSG {
|
||||
msg := bot.GetMessage(messageID)
|
||||
if msg == nil {
|
||||
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
|
||||
}
|
||||
if _, ok := msg["group"]; ok {
|
||||
if err := bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
|
||||
log.Warnf("撤回 %v 失败: %v", messageId, err)
|
||||
log.Warnf("撤回 %v 失败: %v", messageID, err)
|
||||
return Failed(100, "RECALL_API_ERROR", err.Error())
|
||||
}
|
||||
} else {
|
||||
if msg["sender"].(message.Sender).Uin != bot.Client.Uin {
|
||||
log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageId)
|
||||
log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageID)
|
||||
return Failed(100, "CANNOT_RECALL_FRIEND_MSG", "无法撤回对方消息")
|
||||
}
|
||||
if err := bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
|
||||
log.Warnf("撤回 %v 失败: %v", messageId, err)
|
||||
log.Warnf("撤回 %v 失败: %v", messageID, err)
|
||||
return Failed(100, "RECALL_API_ERROR", err.Error())
|
||||
}
|
||||
}
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_admin-%E7%BE%A4%E7%BB%84%E8%AE%BE%E7%BD%AE%E7%AE%A1%E7%90%86%E5%91%98
|
||||
func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG {
|
||||
group := bot.Client.FindGroup(groupId)
|
||||
// CQSetGroupAdmin 群组设置管理员
|
||||
//
|
||||
// https://git.io/Jtz1S
|
||||
func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) MSG {
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
if group == nil || group.OwnerUin != bot.Client.Uin {
|
||||
return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足")
|
||||
}
|
||||
mem := group.FindMember(userId)
|
||||
mem := group.FindMember(userID)
|
||||
if mem == nil {
|
||||
return Failed(100, "GROUP_MEMBER_NOT_FOUND", "群成员不存在")
|
||||
}
|
||||
mem.SetAdmin(enable)
|
||||
t, err := bot.Client.GetGroupMembers(group)
|
||||
if err != nil {
|
||||
log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err)
|
||||
log.Warnf("刷新群 %v 成员列表失败: %v", groupID, err)
|
||||
return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
|
||||
}
|
||||
group.Members = t
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetVipInfo(userId int64) MSG {
|
||||
vip, err := bot.Client.GetVipInfo(userId)
|
||||
// CQGetVipInfo 扩展API-获取VIP信息
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96vip%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetVipInfo(userID int64) MSG {
|
||||
vip, err := bot.Client.GetVipInfo(userID)
|
||||
if err != nil {
|
||||
return Failed(100, "VIP_API_ERROR", err.Error())
|
||||
}
|
||||
@ -599,9 +714,11 @@ func (bot *CQBot) CQGetVipInfo(userId int64) MSG {
|
||||
return OK(msg)
|
||||
}
|
||||
|
||||
// https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_group_honor_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E8%8D%A3%E8%AA%89%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetGroupHonorInfo(groupId int64, t string) MSG {
|
||||
msg := MSG{"group_id": groupId}
|
||||
// CQGetGroupHonorInfo 获取群荣誉信息
|
||||
//
|
||||
// https://git.io/Jtz1H
|
||||
func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG {
|
||||
msg := MSG{"group_id": groupID}
|
||||
convertMem := func(memList []client.HonorMemberInfo) (ret []MSG) {
|
||||
for _, mem := range memList {
|
||||
ret = append(ret, MSG{
|
||||
@ -614,7 +731,7 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupId int64, t string) MSG {
|
||||
return
|
||||
}
|
||||
if t == "talkative" || t == "all" {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupId, client.Talkative); err == nil {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Talkative); err == nil {
|
||||
if honor.CurrentTalkative.Uin != 0 {
|
||||
msg["current_talkative"] = MSG{
|
||||
"user_id": honor.CurrentTalkative.Uin,
|
||||
@ -628,25 +745,25 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupId int64, t string) MSG {
|
||||
}
|
||||
|
||||
if t == "performer" || t == "all" {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupId, client.Performer); err == nil {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Performer); err == nil {
|
||||
msg["performer_lis"] = convertMem(honor.ActorList)
|
||||
}
|
||||
}
|
||||
|
||||
if t == "legend" || t == "all" {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupId, client.Legend); err == nil {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Legend); err == nil {
|
||||
msg["legend_list"] = convertMem(honor.LegendList)
|
||||
}
|
||||
}
|
||||
|
||||
if t == "strong_newbie" || t == "all" {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupId, client.StrongNewbie); err == nil {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.StrongNewbie); err == nil {
|
||||
msg["strong_newbie_list"] = convertMem(honor.StrongNewbieList)
|
||||
}
|
||||
}
|
||||
|
||||
if t == "emotion" || t == "all" {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupId, client.Emotion); err == nil {
|
||||
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Emotion); err == nil {
|
||||
msg["emotion_list"] = convertMem(honor.EmotionList)
|
||||
}
|
||||
}
|
||||
@ -654,9 +771,11 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupId int64, t string) MSG {
|
||||
return OK(msg)
|
||||
}
|
||||
|
||||
// https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_stranger_info-%E8%8E%B7%E5%8F%96%E9%99%8C%E7%94%9F%E4%BA%BA%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG {
|
||||
info, err := bot.Client.GetSummaryInfo(userId)
|
||||
// CQGetStrangerInfo 获取陌生人信息
|
||||
//
|
||||
// https://git.io/Jtz17
|
||||
func (bot *CQBot) CQGetStrangerInfo(userID int64) MSG {
|
||||
info, err := bot.Client.GetSummaryInfo(userID)
|
||||
if err != nil {
|
||||
return Failed(100, "SUMMARY_API_ERROR", err.Error())
|
||||
}
|
||||
@ -667,8 +786,11 @@ func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG {
|
||||
"sex": func() string {
|
||||
if info.Sex == 1 {
|
||||
return "female"
|
||||
}
|
||||
} else if info.Sex == 0 {
|
||||
return "male"
|
||||
}
|
||||
// unknown = 0x2
|
||||
return "unknown"
|
||||
}(),
|
||||
"age": info.Age,
|
||||
"level": info.Level,
|
||||
@ -676,8 +798,9 @@ func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// https://cqhttp.cc/docs/4.15/#/API?id=-handle_quick_operation-%E5%AF%B9%E4%BA%8B%E4%BB%B6%E6%89%A7%E8%A1%8C%E5%BF%AB%E9%80%9F%E6%93%8D%E4%BD%9C
|
||||
// https://github.com/richardchien/coolq-http-api/blob/master/src/cqhttp/plugins/web/http.cpp#L376
|
||||
// CQHandleQuickOperation 隐藏API-对事件执行快速操作
|
||||
//
|
||||
// https://git.io/Jtz15
|
||||
func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
|
||||
postType := context.Get("post_type").Str
|
||||
switch postType {
|
||||
@ -734,11 +857,15 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// CQGetImage 获取图片(修改自OneBot)
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%9B%BE%E7%89%87%E4%BF%A1%E6%81%AF
|
||||
func (bot *CQBot) CQGetImage(file string) MSG {
|
||||
if !global.PathExists(path.Join(global.ImagePath, file)) {
|
||||
return Failed(100)
|
||||
}
|
||||
if b, err := ioutil.ReadFile(path.Join(global.ImagePath, file)); err == nil {
|
||||
b, err := ioutil.ReadFile(path.Join(global.ImagePath, file))
|
||||
if err == nil {
|
||||
r := binary.NewReader(b)
|
||||
r.ReadBytes(16)
|
||||
msg := MSG{
|
||||
@ -754,11 +881,13 @@ func (bot *CQBot) CQGetImage(file string) MSG {
|
||||
}
|
||||
msg["file"] = local
|
||||
return OK(msg)
|
||||
} else {
|
||||
}
|
||||
return Failed(100, "LOAD_FILE_ERROR", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// CQDownloadFile 扩展API-下载文件到缓存目录
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6%E5%88%B0%E7%BC%93%E5%AD%98%E7%9B%AE%E5%BD%95
|
||||
func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCount int) MSG {
|
||||
hash := md5.Sum([]byte(url))
|
||||
file := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache")
|
||||
@ -778,8 +907,11 @@ func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCo
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
|
||||
m := bot.Client.GetForwardMessage(resId)
|
||||
// CQGetForwardMessage 获取合并转发消息
|
||||
//
|
||||
// https://git.io/Jtz1F
|
||||
func (bot *CQBot) CQGetForwardMessage(resID string) MSG {
|
||||
m := bot.Client.GetForwardMessage(resID)
|
||||
if m == nil {
|
||||
return Failed(100, "MSG_NOT_FOUND", "消息不存在")
|
||||
}
|
||||
@ -800,8 +932,11 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetMessage(messageId int32) MSG {
|
||||
msg := bot.GetMessage(messageId)
|
||||
// CQGetMessage 获取消息
|
||||
//
|
||||
// https://git.io/Jtz1b
|
||||
func (bot *CQBot) CQGetMessage(messageID int32) MSG {
|
||||
msg := bot.GetMessage(messageID)
|
||||
if msg == nil {
|
||||
return Failed(100, "MSG_NOT_FOUND", "消息不存在")
|
||||
}
|
||||
@ -809,7 +944,7 @@ func (bot *CQBot) CQGetMessage(messageId int32) MSG {
|
||||
gid, isGroup := msg["group"]
|
||||
raw := msg["message"].(string)
|
||||
return OK(MSG{
|
||||
"message_id": messageId,
|
||||
"message_id": messageID,
|
||||
"real_id": msg["message-id"],
|
||||
"message_seq": msg["message-id"],
|
||||
"group": isGroup,
|
||||
@ -835,6 +970,9 @@ func (bot *CQBot) CQGetMessage(messageId int32) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// CQGetGroupSystemMessages 扩展API-获取群文件系统消息
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E7%B3%BB%E7%BB%9F%E6%B6%88%E6%81%AF
|
||||
func (bot *CQBot) CQGetGroupSystemMessages() MSG {
|
||||
msg, err := bot.Client.GetGroupSystemMessages()
|
||||
if err != nil {
|
||||
@ -844,11 +982,21 @@ func (bot *CQBot) CQGetGroupSystemMessages() MSG {
|
||||
return OK(msg)
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQGetGroupMessageHistory(groupId int64, seq int64) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g == nil {
|
||||
// CQGetGroupMessageHistory 获取群消息历史记录
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%B6%88%E6%81%AF%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95
|
||||
func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g == nil {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
msg, err := bot.Client.GetGroupMessages(groupId, seq-19, seq)
|
||||
if seq == 0 {
|
||||
g, err := bot.Client.GetGroupInfo(groupID)
|
||||
if err != nil {
|
||||
return Failed(100, "GROUP_INFO_API_ERROR", err.Error())
|
||||
}
|
||||
seq = g.LastMsgSeq
|
||||
}
|
||||
msg, err := bot.Client.GetGroupMessages(groupID, int64(math.Max(float64(seq-19), 1)), seq)
|
||||
if err != nil {
|
||||
log.Warnf("获取群历史消息失败: %v", err)
|
||||
return Failed(100, "MESSAGES_API_ERROR", err.Error())
|
||||
@ -856,6 +1004,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupId int64, seq int64) MSG {
|
||||
var ms []MSG
|
||||
for _, m := range msg {
|
||||
id := m.Id
|
||||
bot.checkMedia(m.Elements)
|
||||
if bot.db != nil {
|
||||
id = bot.InsertGroupMessage(m)
|
||||
}
|
||||
@ -868,6 +1017,9 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupId int64, seq int64) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// CQGetOnlineClients 扩展API-获取当前账号在线客户端列表
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E8%B4%A6%E5%8F%B7%E5%9C%A8%E7%BA%BF%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%88%97%E8%A1%A8
|
||||
func (bot *CQBot) CQGetOnlineClients(noCache bool) MSG {
|
||||
if noCache {
|
||||
if err := bot.Client.RefreshStatus(); err != nil {
|
||||
@ -888,16 +1040,25 @@ func (bot *CQBot) CQGetOnlineClients(noCache bool) MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// CQCanSendImage 检查是否可以发送图片(此处永远返回true)
|
||||
//
|
||||
// https://git.io/Jtz1N
|
||||
func (bot *CQBot) CQCanSendImage() MSG {
|
||||
return OK(MSG{"yes": true})
|
||||
}
|
||||
|
||||
// CQCanSendRecord 检查是否可以发送语音(此处永远返回true)
|
||||
//
|
||||
// https://git.io/Jtz1x
|
||||
func (bot *CQBot) CQCanSendRecord() MSG {
|
||||
return OK(MSG{"yes": true})
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQOcrImage(imageId string) MSG {
|
||||
img, err := bot.makeImageOrVideoElem(map[string]string{"file": imageId}, false, true)
|
||||
// CQOcrImage 扩展API-图片OCR
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E5%9B%BE%E7%89%87-ocr
|
||||
func (bot *CQBot) CQOcrImage(imageID string) MSG {
|
||||
img, err := bot.makeImageOrVideoElem(map[string]string{"file": imageID}, false, true)
|
||||
if err != nil {
|
||||
log.Warnf("load image error: %v", err)
|
||||
return Failed(100, "LOAD_FILE_ERROR", err.Error())
|
||||
@ -910,13 +1071,19 @@ func (bot *CQBot) CQOcrImage(imageId string) MSG {
|
||||
return OK(rsp)
|
||||
}
|
||||
|
||||
// CQReloadEventFilter 扩展API-重载事件过滤器
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E9%87%8D%E8%BD%BD%E4%BA%8B%E4%BB%B6%E8%BF%87%E6%BB%A4%E5%99%A8
|
||||
func (bot *CQBot) CQReloadEventFilter() MSG {
|
||||
global.BootFilter()
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQSetGroupPortrait(groupId int64, file, cache string) MSG {
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
// CQSetGroupPortrait 扩展API-设置群头像
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F
|
||||
func (bot *CQBot) CQSetGroupPortrait(groupID int64, file, cache string) MSG {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
img, err := global.FindFile(file, cache, global.ImagePath)
|
||||
if err != nil {
|
||||
log.Warnf("set group portrait error: %v", err)
|
||||
@ -928,11 +1095,14 @@ func (bot *CQBot) CQSetGroupPortrait(groupId int64, file, cache string) MSG {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
func (bot *CQBot) CQSetGroupAnonymousBan(groupId int64, flag string, duration int32) MSG {
|
||||
// CQSetGroupAnonymousBan 群组匿名用户禁言
|
||||
//
|
||||
// https://git.io/Jtz1p
|
||||
func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration int32) MSG {
|
||||
if flag == "" {
|
||||
return Failed(100, "INVALID_FLAG", "无效的flag")
|
||||
}
|
||||
if g := bot.Client.FindGroup(groupId); g != nil {
|
||||
if g := bot.Client.FindGroup(groupID); g != nil {
|
||||
s := strings.SplitN(flag, "|", 2)
|
||||
if len(s) != 2 {
|
||||
return Failed(100, "INVALID_FLAG", "无效的flag")
|
||||
@ -948,7 +1118,9 @@ func (bot *CQBot) CQSetGroupAnonymousBan(groupId int64, flag string, duration in
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_status-%E8%8E%B7%E5%8F%96%E8%BF%90%E8%A1%8C%E7%8A%B6%E6%80%81
|
||||
// CQGetStatus 获取运行状态
|
||||
//
|
||||
// https://git.io/JtzMe
|
||||
func (bot *CQBot) CQGetStatus() MSG {
|
||||
return OK(MSG{
|
||||
"app_initialized": true,
|
||||
@ -961,6 +1133,86 @@ func (bot *CQBot) CQGetStatus() MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// CQSetEssenceMessage 扩展API-设置精华消息
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF
|
||||
func (bot *CQBot) CQSetEssenceMessage(messageID int32) MSG {
|
||||
msg := bot.GetMessage(messageID)
|
||||
if msg == nil {
|
||||
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
|
||||
}
|
||||
if _, ok := msg["group"]; ok {
|
||||
if err := bot.Client.SetEssenceMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
|
||||
log.Warnf("设置精华消息 %v 失败: %v", messageID, err)
|
||||
return Failed(100, "SET_ESSENCE_MSG_ERROR", err.Error())
|
||||
}
|
||||
} else {
|
||||
log.Warnf("设置精华消息 %v 失败: 非群聊", messageID)
|
||||
return Failed(100, "SET_ESSENCE_MSG_ERROR", "非群聊")
|
||||
}
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// CQDeleteEssenceMessage 扩展API-移出精华消息
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E7%A7%BB%E5%87%BA%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF
|
||||
func (bot *CQBot) CQDeleteEssenceMessage(messageID int32) MSG {
|
||||
msg := bot.GetMessage(messageID)
|
||||
if msg == nil {
|
||||
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
|
||||
}
|
||||
if _, ok := msg["group"]; ok {
|
||||
if err := bot.Client.DeleteEssenceMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
|
||||
log.Warnf("移出精华消息 %v 失败: %v", messageID, err)
|
||||
return Failed(100, "DEL_ESSENCE_MSG_ERROR", err.Error())
|
||||
}
|
||||
} else {
|
||||
log.Warnf("移出精华消息 %v 失败: 非群聊", messageID)
|
||||
return Failed(100, "DEL_ESSENCE_MSG_ERROR", "非群聊")
|
||||
}
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// CQGetEssenceMessageList 扩展API-获取精华消息列表
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF%E5%88%97%E8%A1%A8
|
||||
func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
|
||||
g := bot.Client.FindGroup(groupCode)
|
||||
if g == nil {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
msgList, err := bot.Client.GetGroupEssenceMsgList(groupCode)
|
||||
if err != nil {
|
||||
return Failed(100, "GET_ESSENCE_LIST_FOUND", err.Error())
|
||||
}
|
||||
list := make([]MSG, 0)
|
||||
for _, m := range msgList {
|
||||
var msg = MSG{
|
||||
"sender_nick": m.SenderNick,
|
||||
"sender_time": m.SenderTime,
|
||||
"operator_time": m.AddDigestTime,
|
||||
"operator_nick": m.AddDigestNick,
|
||||
}
|
||||
msg["sender_id"], _ = strconv.ParseUint(m.SenderUin, 10, 64)
|
||||
msg["operator_id"], _ = strconv.ParseUint(m.AddDigestUin, 10, 64)
|
||||
msg["message_id"] = toGlobalID(groupCode, int32(m.MessageID))
|
||||
list = append(list, msg)
|
||||
}
|
||||
return OK(list)
|
||||
}
|
||||
|
||||
// CQCheckURLSafely 扩展API-检查链接安全性
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E6%A3%80%E6%9F%A5%E9%93%BE%E6%8E%A5%E5%AE%89%E5%85%A8%E6%80%A7
|
||||
func (bot *CQBot) CQCheckURLSafely(url string) MSG {
|
||||
return OK(MSG{
|
||||
"level": bot.Client.CheckUrlSafely(url),
|
||||
})
|
||||
}
|
||||
|
||||
// CQGetVersionInfo 获取版本信息
|
||||
//
|
||||
// https://git.io/JtwUs
|
||||
func (bot *CQBot) CQGetVersionInfo() MSG {
|
||||
wd, _ := os.Getwd()
|
||||
return OK(MSG{
|
||||
@ -990,10 +1242,12 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
|
||||
})
|
||||
}
|
||||
|
||||
// OK 生成成功返回值
|
||||
func OK(data interface{}) MSG {
|
||||
return MSG{"data": data, "retcode": 0, "status": "ok"}
|
||||
}
|
||||
|
||||
// Failed 生成失败返回值
|
||||
func Failed(code int, msg ...string) MSG {
|
||||
m := ""
|
||||
w := ""
|
||||
@ -1006,13 +1260,21 @@ func Failed(code int, msg ...string) MSG {
|
||||
return MSG{"data": nil, "retcode": code, "msg": m, "wording": w, "status": "failed"}
|
||||
}
|
||||
|
||||
func convertGroupMemberInfo(groupId int64, m *client.GroupMemberInfo) MSG {
|
||||
func convertGroupMemberInfo(groupID int64, m *client.GroupMemberInfo) MSG {
|
||||
return MSG{
|
||||
"group_id": groupId,
|
||||
"group_id": groupID,
|
||||
"user_id": m.Uin,
|
||||
"nickname": m.Nickname,
|
||||
"card": m.CardName,
|
||||
"sex": "unknown",
|
||||
"sex": func() string {
|
||||
if m.Gender == 1 {
|
||||
return "female"
|
||||
} else if m.Gender == 0 {
|
||||
return "male"
|
||||
}
|
||||
// unknown = 0xff
|
||||
return "unknown"
|
||||
}(),
|
||||
"age": 0,
|
||||
"area": "",
|
||||
"join_time": m.JoinTime,
|
||||
|
161
coolq/bot.go
161
coolq/bot.go
@ -28,6 +28,7 @@ import (
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
// CQBot CQBot结构体,存储Bot实例相关配置
|
||||
type CQBot struct {
|
||||
Client *client.QQClient
|
||||
|
||||
@ -38,10 +39,13 @@ type CQBot struct {
|
||||
oneWayMsgCache sync.Map
|
||||
}
|
||||
|
||||
// MSG 消息Map
|
||||
type MSG map[string]interface{}
|
||||
|
||||
// ForceFragmented 是否启用强制分片
|
||||
var ForceFragmented = false
|
||||
|
||||
// NewQQBot 初始化一个QQBot实例
|
||||
func NewQQBot(cli *client.QQClient, conf *global.JSONConfig) *CQBot {
|
||||
bot := &CQBot{
|
||||
Client: cli,
|
||||
@ -78,6 +82,7 @@ func NewQQBot(cli *client.QQClient, conf *global.JSONConfig) *CQBot {
|
||||
bot.Client.OnGroupInvited(bot.groupInvitedEvent)
|
||||
bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent)
|
||||
bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent)
|
||||
bot.Client.OnGroupDigest(bot.groupEssenceMsg)
|
||||
go func() {
|
||||
i := conf.HeartbeatInterval
|
||||
if i < 0 {
|
||||
@ -102,10 +107,12 @@ func NewQQBot(cli *client.QQClient, conf *global.JSONConfig) *CQBot {
|
||||
return bot
|
||||
}
|
||||
|
||||
// OnEventPush 注册事件上报函数
|
||||
func (bot *CQBot) OnEventPush(f func(m MSG)) {
|
||||
bot.events = append(bot.events, f)
|
||||
}
|
||||
|
||||
// GetMessage 获取给定消息id对应的消息
|
||||
func (bot *CQBot) GetMessage(mid int32) MSG {
|
||||
if bot.db != nil {
|
||||
m := MSG{}
|
||||
@ -123,6 +130,7 @@ func (bot *CQBot) GetMessage(mid int32) MSG {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UploadLocalImageAsGroup 上传本地图片至群聊
|
||||
func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElement) (*message.GroupImageElement, error) {
|
||||
if img.Stream != nil {
|
||||
return bot.Client.UploadGroupImage(groupCode, img.Stream)
|
||||
@ -130,6 +138,7 @@ func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElemen
|
||||
return bot.Client.UploadGroupImageByFile(groupCode, img.File)
|
||||
}
|
||||
|
||||
// UploadLocalVideo 上传本地短视频至群聊
|
||||
func (bot *CQBot) UploadLocalVideo(target int64, v *LocalVideoElement) (*message.ShortVideoElement, error) {
|
||||
if v.File != "" {
|
||||
video, err := os.Open(v.File)
|
||||
@ -146,9 +155,10 @@ func (bot *CQBot) UploadLocalVideo(target int64, v *LocalVideoElement) (*message
|
||||
return &v.ShortVideoElement, nil
|
||||
}
|
||||
|
||||
func (bot *CQBot) UploadLocalImageAsPrivate(userId int64, img *LocalImageElement) (*message.FriendImageElement, error) {
|
||||
// UploadLocalImageAsPrivate 上传本地图片至私聊
|
||||
func (bot *CQBot) UploadLocalImageAsPrivate(userID int64, img *LocalImageElement) (*message.FriendImageElement, error) {
|
||||
if img.Stream != nil {
|
||||
return bot.Client.UploadPrivateImage(userId, img.Stream)
|
||||
return bot.Client.UploadPrivateImage(userID, img.Stream)
|
||||
}
|
||||
// need update.
|
||||
f, err := os.Open(img.File)
|
||||
@ -156,41 +166,42 @@ func (bot *CQBot) UploadLocalImageAsPrivate(userId int64, img *LocalImageElement
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return bot.Client.UploadPrivateImage(userId, f)
|
||||
return bot.Client.UploadPrivateImage(userID, f)
|
||||
}
|
||||
|
||||
func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int32 {
|
||||
// SendGroupMessage 发送群消息
|
||||
func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) int32 {
|
||||
var newElem []message.IMessageElement
|
||||
for _, elem := range m.Elements {
|
||||
if i, ok := elem.(*LocalImageElement); ok {
|
||||
gm, err := bot.UploadLocalImageAsGroup(groupId, i)
|
||||
gm, err := bot.UploadLocalImageAsGroup(groupID, i)
|
||||
if err != nil {
|
||||
log.Warnf("警告: 群 %v 消息图片上传失败: %v", groupId, err)
|
||||
log.Warnf("警告: 群 %v 消息图片上传失败: %v", groupID, err)
|
||||
continue
|
||||
}
|
||||
newElem = append(newElem, gm)
|
||||
continue
|
||||
}
|
||||
if i, ok := elem.(*message.VoiceElement); ok {
|
||||
gv, err := bot.Client.UploadGroupPtt(groupId, bytes.NewReader(i.Data))
|
||||
gv, err := bot.Client.UploadGroupPtt(groupID, bytes.NewReader(i.Data))
|
||||
if err != nil {
|
||||
log.Warnf("警告: 群 %v 消息语音上传失败: %v", groupId, err)
|
||||
log.Warnf("警告: 群 %v 消息语音上传失败: %v", groupID, err)
|
||||
continue
|
||||
}
|
||||
newElem = append(newElem, gv)
|
||||
continue
|
||||
}
|
||||
if i, ok := elem.(*LocalVideoElement); ok {
|
||||
gv, err := bot.UploadLocalVideo(groupId, i)
|
||||
gv, err := bot.UploadLocalVideo(groupID, i)
|
||||
if err != nil {
|
||||
log.Warnf("警告: 群 %v 消息短视频上传失败: %v", groupId, err)
|
||||
log.Warnf("警告: 群 %v 消息短视频上传失败: %v", groupID, err)
|
||||
continue
|
||||
}
|
||||
newElem = append(newElem, gv)
|
||||
continue
|
||||
}
|
||||
if i, ok := elem.(*PokeElement); ok {
|
||||
if group := bot.Client.FindGroup(groupId); group != nil {
|
||||
if group := bot.Client.FindGroup(groupID); group != nil {
|
||||
if mem := group.FindMember(i.Target); mem != nil {
|
||||
mem.Poke()
|
||||
return 0
|
||||
@ -198,66 +209,13 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
|
||||
}
|
||||
}
|
||||
if i, ok := elem.(*GiftElement); ok {
|
||||
bot.Client.SendGroupGift(uint64(groupId), uint64(i.Target), i.GiftId)
|
||||
bot.Client.SendGroupGift(uint64(groupID), uint64(i.Target), i.GiftID)
|
||||
return 0
|
||||
}
|
||||
if i, ok := elem.(*QQMusicElement); ok {
|
||||
var msgStyle uint32 = 4
|
||||
if i.MusicUrl == "" {
|
||||
msgStyle = 0 // fix vip song
|
||||
}
|
||||
ret, err := bot.Client.SendGroupRichMessage(groupId, 100497308, 1, msgStyle, client.RichClientInfo{
|
||||
Platform: 1,
|
||||
SdkVersion: "0.0.0",
|
||||
PackageName: "com.tencent.qqmusic",
|
||||
Signature: "cbd27cd7c861227d013a25b2d10f0799",
|
||||
}, &message.RichMessage{
|
||||
Title: i.Title,
|
||||
Summary: i.Summary,
|
||||
Url: i.Url,
|
||||
PictureUrl: i.PictureUrl,
|
||||
MusicUrl: i.MusicUrl,
|
||||
})
|
||||
if i, ok := elem.(*message.MusicShareElement); ok {
|
||||
ret, err := bot.Client.SendGroupMusicShare(groupID, i)
|
||||
if err != nil {
|
||||
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err)
|
||||
return -1
|
||||
}
|
||||
return bot.InsertGroupMessage(ret)
|
||||
}
|
||||
if i, ok := elem.(*CloudMusicElement); ok {
|
||||
ret, err := bot.Client.SendGroupRichMessage(groupId, 100495085, 1, 4, client.RichClientInfo{
|
||||
Platform: 1,
|
||||
SdkVersion: "0.0.0",
|
||||
PackageName: "com.netease.cloudmusic",
|
||||
Signature: "da6b069da1e2982db3e386233f68d76d",
|
||||
}, &message.RichMessage{
|
||||
Title: i.Title,
|
||||
Summary: i.Summary,
|
||||
Url: i.Url,
|
||||
PictureUrl: i.PictureUrl,
|
||||
MusicUrl: i.MusicUrl,
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err)
|
||||
return -1
|
||||
}
|
||||
return bot.InsertGroupMessage(ret)
|
||||
}
|
||||
if i, ok := elem.(*MiguMusicElement); ok {
|
||||
ret, err := bot.Client.SendGroupRichMessage(groupId, 1101053067, 1, 4, client.RichClientInfo{
|
||||
Platform: 1,
|
||||
SdkVersion: "0.0.0",
|
||||
PackageName: "cmccwm.mobilemusic",
|
||||
Signature: "6cdc72a439cef99a3418d2a78aa28c73",
|
||||
}, &message.RichMessage{
|
||||
Title: i.Title,
|
||||
Summary: i.Summary,
|
||||
Url: i.Url,
|
||||
PictureUrl: i.PictureUrl,
|
||||
MusicUrl: i.MusicUrl,
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err)
|
||||
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupID, err)
|
||||
return -1
|
||||
}
|
||||
return bot.InsertGroupMessage(ret)
|
||||
@ -270,7 +228,7 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
|
||||
}
|
||||
m.Elements = newElem
|
||||
bot.checkMedia(newElem)
|
||||
ret := bot.Client.SendGroupMessage(groupId, m, ForceFragmented)
|
||||
ret := bot.Client.SendGroupMessage(groupID, m, ForceFragmented)
|
||||
if ret == nil || ret.Id == -1 {
|
||||
log.Warnf("群消息发送失败: 账号可能被风控.")
|
||||
return -1
|
||||
@ -278,6 +236,7 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
|
||||
return bot.InsertGroupMessage(ret)
|
||||
}
|
||||
|
||||
// SendPrivateMessage 发送私聊消息
|
||||
func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) int32 {
|
||||
var newElem []message.IMessageElement
|
||||
for _, elem := range m.Elements {
|
||||
@ -312,53 +271,8 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
|
||||
newElem = append(newElem, gv)
|
||||
continue
|
||||
}
|
||||
if i, ok := elem.(*QQMusicElement); ok {
|
||||
var msgStyle uint32 = 4
|
||||
if i.MusicUrl == "" {
|
||||
msgStyle = 0 // fix vip song
|
||||
}
|
||||
bot.Client.SendFriendRichMessage(target, 100497308, 1, msgStyle, client.RichClientInfo{
|
||||
Platform: 1,
|
||||
SdkVersion: "0.0.0",
|
||||
PackageName: "com.tencent.qqmusic",
|
||||
Signature: "cbd27cd7c861227d013a25b2d10f0799",
|
||||
}, &message.RichMessage{
|
||||
Title: i.Title,
|
||||
Summary: i.Summary,
|
||||
Url: i.Url,
|
||||
PictureUrl: i.PictureUrl,
|
||||
MusicUrl: i.MusicUrl,
|
||||
})
|
||||
return 0
|
||||
}
|
||||
if i, ok := elem.(*CloudMusicElement); ok {
|
||||
bot.Client.SendFriendRichMessage(target, 100495085, 1, 4, client.RichClientInfo{
|
||||
Platform: 1,
|
||||
SdkVersion: "0.0.0",
|
||||
PackageName: "com.netease.cloudmusic",
|
||||
Signature: "da6b069da1e2982db3e386233f68d76d",
|
||||
}, &message.RichMessage{
|
||||
Title: i.Title,
|
||||
Summary: i.Summary,
|
||||
Url: i.Url,
|
||||
PictureUrl: i.PictureUrl,
|
||||
MusicUrl: i.MusicUrl,
|
||||
})
|
||||
return 0
|
||||
}
|
||||
if i, ok := elem.(*MiguMusicElement); ok {
|
||||
bot.Client.SendFriendRichMessage(target, 1101053067, 1, 4, client.RichClientInfo{
|
||||
Platform: 1,
|
||||
SdkVersion: "0.0.0",
|
||||
PackageName: "cmccwm.mobilemusic",
|
||||
Signature: "6cdc72a439cef99a3418d2a78aa28c73",
|
||||
}, &message.RichMessage{
|
||||
Title: i.Title,
|
||||
Summary: i.Summary,
|
||||
Url: i.Url,
|
||||
PictureUrl: i.PictureUrl,
|
||||
MusicUrl: i.MusicUrl,
|
||||
})
|
||||
if i, ok := elem.(*message.MusicShareElement); ok {
|
||||
bot.Client.SendFriendMusicShare(target, i)
|
||||
return 0
|
||||
}
|
||||
newElem = append(newElem, elem)
|
||||
@ -392,6 +306,7 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
|
||||
return id
|
||||
}
|
||||
|
||||
// InsertGroupMessage 群聊消息入数据库
|
||||
func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
|
||||
val := MSG{
|
||||
"message-id": m.Id,
|
||||
@ -402,7 +317,7 @@ func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
|
||||
"time": m.Time,
|
||||
"message": ToStringMessage(m.Elements, m.GroupCode, true),
|
||||
}
|
||||
id := ToGlobalId(m.GroupCode, m.Id)
|
||||
id := toGlobalID(m.GroupCode, m.Id)
|
||||
if bot.db != nil {
|
||||
buf := new(bytes.Buffer)
|
||||
if err := gob.NewEncoder(buf).Encode(val); err != nil {
|
||||
@ -417,6 +332,7 @@ func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
|
||||
return id
|
||||
}
|
||||
|
||||
// InsertPrivateMessage 私聊消息入数据库
|
||||
func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 {
|
||||
val := MSG{
|
||||
"message-id": m.Id,
|
||||
@ -426,7 +342,7 @@ func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 {
|
||||
"time": m.Time,
|
||||
"message": ToStringMessage(m.Elements, m.Sender.Uin, true),
|
||||
}
|
||||
id := ToGlobalId(m.Sender.Uin, m.Id)
|
||||
id := toGlobalID(m.Sender.Uin, m.Id)
|
||||
if bot.db != nil {
|
||||
buf := new(bytes.Buffer)
|
||||
if err := gob.NewEncoder(buf).Encode(val); err != nil {
|
||||
@ -441,10 +357,12 @@ func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 {
|
||||
return id
|
||||
}
|
||||
|
||||
func ToGlobalId(code int64, msgId int32) int32 {
|
||||
return int32(crc32.ChecksumIEEE([]byte(fmt.Sprintf("%d-%d", code, msgId))))
|
||||
// toGlobalID 构建`code`-`msgID`的字符串并返回其CRC32 Checksum的值
|
||||
func toGlobalID(code int64, msgID int32) int32 {
|
||||
return int32(crc32.ChecksumIEEE([]byte(fmt.Sprintf("%d-%d", code, msgID))))
|
||||
}
|
||||
|
||||
// Release 释放Bot实例
|
||||
func (bot *CQBot) Release() {
|
||||
if bot.db != nil {
|
||||
_ = bot.db.Close()
|
||||
@ -535,7 +453,8 @@ func formatMemberName(mem *client.GroupMemberInfo) string {
|
||||
return fmt.Sprintf("%s(%d)", mem.DisplayName(), mem.Uin)
|
||||
}
|
||||
|
||||
func (m MSG) ToJson() string {
|
||||
// ToJSON 生成JSON字符串
|
||||
func (m MSG) ToJSON() string {
|
||||
b, _ := json.Marshal(m)
|
||||
return string(b)
|
||||
}
|
||||
|
214
coolq/cqcode.go
214
coolq/cqcode.go
@ -34,67 +34,53 @@ var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
|
||||
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
|
||||
*/
|
||||
|
||||
// IgnoreInvalidCQCode 是否忽略无效CQ码
|
||||
var IgnoreInvalidCQCode = false
|
||||
var SplitUrl = false
|
||||
|
||||
// SplitURL 是否分割URL
|
||||
var SplitURL = false
|
||||
|
||||
const maxImageSize = 1024 * 1024 * 30 // 30MB
|
||||
const maxVideoSize = 1024 * 1024 * 100 // 100MB
|
||||
|
||||
// PokeElement 拍一拍
|
||||
type PokeElement struct {
|
||||
Target int64
|
||||
}
|
||||
|
||||
// GiftElement 礼物
|
||||
type GiftElement struct {
|
||||
Target int64
|
||||
GiftId message.GroupGift
|
||||
}
|
||||
|
||||
type MusicElement struct {
|
||||
Title string
|
||||
Summary string
|
||||
Url string
|
||||
PictureUrl string
|
||||
MusicUrl string
|
||||
}
|
||||
|
||||
type QQMusicElement struct {
|
||||
MusicElement
|
||||
}
|
||||
|
||||
type CloudMusicElement struct {
|
||||
MusicElement
|
||||
}
|
||||
|
||||
type MiguMusicElement struct {
|
||||
MusicElement
|
||||
GiftID message.GroupGift
|
||||
}
|
||||
|
||||
// LocalImageElement 本地图片
|
||||
type LocalImageElement struct {
|
||||
message.ImageElement
|
||||
Stream io.ReadSeeker
|
||||
File string
|
||||
}
|
||||
|
||||
// LocalVoiceElement 本地语音
|
||||
type LocalVoiceElement struct {
|
||||
message.VoiceElement
|
||||
Stream io.ReadSeeker
|
||||
}
|
||||
|
||||
// LocalVideoElement 本地视频
|
||||
type LocalVideoElement struct {
|
||||
message.ShortVideoElement
|
||||
File string
|
||||
thumb io.ReadSeeker
|
||||
}
|
||||
|
||||
// Type 获取元素类型ID
|
||||
func (e *GiftElement) Type() message.ElementType {
|
||||
// Make message.IMessageElement Happy
|
||||
return message.At
|
||||
}
|
||||
|
||||
func (e *MusicElement) Type() message.ElementType {
|
||||
return message.Service
|
||||
}
|
||||
|
||||
var GiftId = [...]message.GroupGift{
|
||||
// GiftID 礼物ID数组
|
||||
var GiftID = [...]message.GroupGift{
|
||||
message.SweetWink,
|
||||
message.HappyCola,
|
||||
message.LuckyBracelet,
|
||||
@ -111,15 +97,18 @@ var GiftId = [...]message.GroupGift{
|
||||
message.LoveMask,
|
||||
}
|
||||
|
||||
// Type 获取元素类型ID
|
||||
func (e *PokeElement) Type() message.ElementType {
|
||||
// Make message.IMessageElement Happy
|
||||
return message.At
|
||||
}
|
||||
|
||||
func ToArrayMessage(e []message.IMessageElement, code int64, raw ...bool) (r []MSG) {
|
||||
// ToArrayMessage 将消息元素数组转为MSG数组以用于消息上报
|
||||
func ToArrayMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r []MSG) {
|
||||
r = []MSG{}
|
||||
ur := false
|
||||
if len(raw) != 0 {
|
||||
ur = raw[0]
|
||||
if len(isRaw) != 0 {
|
||||
ur = isRaw[0]
|
||||
}
|
||||
m := &message.SendingMessage{Elements: e}
|
||||
reply := m.FirstOrNil(func(e message.IMessageElement) bool {
|
||||
@ -129,7 +118,7 @@ func ToArrayMessage(e []message.IMessageElement, code int64, raw ...bool) (r []M
|
||||
if reply != nil {
|
||||
r = append(r, MSG{
|
||||
"type": "reply",
|
||||
"data": map[string]string{"id": fmt.Sprint(ToGlobalId(code, reply.(*message.ReplyElement).ReplySeq))},
|
||||
"data": map[string]string{"id": fmt.Sprint(toGlobalID(id, reply.(*message.ReplyElement).ReplySeq))},
|
||||
})
|
||||
}
|
||||
for _, elem := range e {
|
||||
@ -266,10 +255,11 @@ func ToArrayMessage(e []message.IMessageElement, code int64, raw ...bool) (r []M
|
||||
return
|
||||
}
|
||||
|
||||
func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r string) {
|
||||
// ToStringMessage 将消息元素数组转为字符串以用于消息上报
|
||||
func ToStringMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r string) {
|
||||
ur := false
|
||||
if len(raw) != 0 {
|
||||
ur = raw[0]
|
||||
if len(isRaw) != 0 {
|
||||
ur = isRaw[0]
|
||||
}
|
||||
// 方便
|
||||
m := &message.SendingMessage{Elements: e}
|
||||
@ -278,7 +268,7 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
|
||||
return ok
|
||||
})
|
||||
if reply != nil {
|
||||
r += fmt.Sprintf("[CQ:reply,id=%d]", ToGlobalId(code, reply.(*message.ReplyElement).ReplySeq))
|
||||
r += fmt.Sprintf("[CQ:reply,id=%d]", toGlobalID(id, reply.(*message.ReplyElement).ReplySeq))
|
||||
}
|
||||
for _, elem := range e {
|
||||
switch o := elem.(type) {
|
||||
@ -344,7 +334,8 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMessageElement) {
|
||||
// ConvertStringMessage 将消息字符串转为消息元素数组
|
||||
func (bot *CQBot) ConvertStringMessage(msg string, isGroup bool) (r []message.IMessageElement) {
|
||||
index := 0
|
||||
stat := 0
|
||||
rMsg := []rune(msg)
|
||||
@ -369,7 +360,7 @@ func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMes
|
||||
}
|
||||
saveTempText := func() {
|
||||
if len(tempText) != 0 {
|
||||
if SplitUrl {
|
||||
if SplitURL {
|
||||
for _, t := range global.SplitURL(CQCodeUnescapeValue(string(tempText))) {
|
||||
r = append(r, message.NewText(t))
|
||||
}
|
||||
@ -421,7 +412,7 @@ func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMes
|
||||
ReplySeq: org["message-id"].(int32),
|
||||
Sender: org["sender"].(message.Sender).Uin,
|
||||
Time: org["time"].(int32),
|
||||
Elements: bot.ConvertStringMessage(org["message"].(string), group),
|
||||
Elements: bot.ConvertStringMessage(org["message"].(string), isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
@ -441,7 +432,7 @@ func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMes
|
||||
ReplySeq: int32(0),
|
||||
Sender: sender,
|
||||
Time: int32(msgTime),
|
||||
Elements: bot.ConvertStringMessage(customText, group),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
@ -453,7 +444,7 @@ func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMes
|
||||
return
|
||||
}
|
||||
}
|
||||
elem, err := bot.ToElement(t, params, group)
|
||||
elem, err := bot.ToElement(t, params, isGroup)
|
||||
if err != nil {
|
||||
org := "[CQ:" + string(cqCode) + "]"
|
||||
if !IgnoreInvalidCQCode {
|
||||
@ -500,10 +491,11 @@ func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMes
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *CQBot) ConvertObjectMessage(m gjson.Result, group bool) (r []message.IMessageElement) {
|
||||
// ConvertObjectMessage 将消息JSON对象转为消息元素数组
|
||||
func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []message.IMessageElement) {
|
||||
convertElem := func(e gjson.Result) {
|
||||
t := e.Get("type").Str
|
||||
if t == "reply" && group {
|
||||
if t == "reply" && isGroup {
|
||||
if len(r) > 0 {
|
||||
if _, ok := r[0].(*message.ReplyElement); ok {
|
||||
log.Warnf("警告: 一条信息只能包含一个 Reply 元素.")
|
||||
@ -520,7 +512,7 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, group bool) (r []message.
|
||||
ReplySeq: org["message-id"].(int32),
|
||||
Sender: org["sender"].(message.Sender).Uin,
|
||||
Time: org["time"].(int32),
|
||||
Elements: bot.ConvertStringMessage(org["message"].(string), group),
|
||||
Elements: bot.ConvertStringMessage(org["message"].(string), isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
@ -540,7 +532,7 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, group bool) (r []message.
|
||||
ReplySeq: int32(0),
|
||||
Sender: sender,
|
||||
Time: int32(msgTime),
|
||||
Elements: bot.ConvertStringMessage(customText, group),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
@ -555,7 +547,7 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, group bool) (r []message.
|
||||
d[key.Str] = value.String()
|
||||
return true
|
||||
})
|
||||
elem, err := bot.ToElement(t, d, group)
|
||||
elem, err := bot.ToElement(t, d, isGroup)
|
||||
if err != nil {
|
||||
log.Warnf("转换CQ码到MiraiGo Element时出现错误: %v 将忽略本段CQ码.", err)
|
||||
return
|
||||
@ -568,7 +560,7 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, group bool) (r []message.
|
||||
}
|
||||
}
|
||||
if m.Type == gjson.String {
|
||||
return bot.ConvertStringMessage(m.Str, group)
|
||||
return bot.ConvertStringMessage(m.Str, isGroup)
|
||||
}
|
||||
if m.IsArray() {
|
||||
for _, e := range m.Array() {
|
||||
@ -582,12 +574,14 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, group bool) (r []message.
|
||||
}
|
||||
|
||||
// ToElement 将解码后的CQCode转换为Element.
|
||||
//
|
||||
// 返回 interface{} 存在三种类型
|
||||
//
|
||||
// message.IMessageElement []message.IMessageElement nil
|
||||
func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interface{}, err error) {
|
||||
func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m interface{}, err error) {
|
||||
switch t {
|
||||
case "text":
|
||||
if SplitUrl {
|
||||
if SplitURL {
|
||||
var ret []message.IMessageElement
|
||||
for _, text := range global.SplitURL(d["text"]) {
|
||||
ret = append(ret, message.NewText(text))
|
||||
@ -596,7 +590,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
}
|
||||
return message.NewText(d["text"]), nil
|
||||
case "image":
|
||||
img, err := bot.makeImageOrVideoElem(d, false, group)
|
||||
img, err := bot.makeImageOrVideoElem(d, false, isGroup)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -605,7 +599,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
return img, nil
|
||||
}
|
||||
if i, ok := img.(*LocalImageElement); ok { // 秀图,闪照什么的就直接传了吧
|
||||
if group {
|
||||
if isGroup {
|
||||
img, err = bot.UploadLocalImageAsGroup(1, i)
|
||||
} else {
|
||||
img, err = bot.UploadLocalImageAsPrivate(1, i)
|
||||
@ -637,7 +631,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
t, _ := strconv.ParseInt(d["qq"], 10, 64)
|
||||
return &PokeElement{Target: t}, nil
|
||||
case "gift":
|
||||
if !group {
|
||||
if !isGroup {
|
||||
return nil, errors.New("private gift unsupported") // no free private gift
|
||||
}
|
||||
t, _ := strconv.ParseInt(d["qq"], 10, 64)
|
||||
@ -645,7 +639,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
if id < 0 || id >= 14 {
|
||||
return nil, errors.New("invalid gift id")
|
||||
}
|
||||
return &GiftElement{Target: t, GiftId: GiftId[id]}, nil
|
||||
return &GiftElement{Target: t, GiftID: GiftID[id]}, nil
|
||||
case "tts":
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
@ -699,27 +693,28 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
return nil, errors.New("song not found")
|
||||
}
|
||||
aid := strconv.FormatInt(info.Get("track_info.album.id").Int(), 10)
|
||||
name := info.Get("track_info.name").Str + " - " + info.Get("track_info.singer.0.name").Str
|
||||
name := info.Get("track_info.name").Str
|
||||
mid := info.Get("track_info.mid").Str
|
||||
albumMid := info.Get("track_info.album.mid").Str
|
||||
pinfo, _ := global.GetBytes("http://u.y.qq.com/cgi-bin/musicu.fcg?g_tk=2034008533&uin=0&format=json&data={\"comm\":{\"ct\":23,\"cv\":0},\"url_mid\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"guid\":\"4311206557\",\"songmid\":[\"" + mid + "\"],\"songtype\":[0],\"uin\":\"0\",\"loginflag\":1,\"platform\":\"23\"}}}&_=1599039471576")
|
||||
jumpUrl := "https://i.y.qq.com/v8/playsong.html?platform=11&appshare=android_qq&appversion=10030010&hosteuin=oKnlNenz7i-s7c**&songmid=" + mid + "&type=0&appsongtype=1&_wv=1&source=qq&ADTAG=qfshare"
|
||||
jumpURL := "https://i.y.qq.com/v8/playsong.html?platform=11&appshare=android_qq&appversion=10030010&hosteuin=oKnlNenz7i-s7c**&songmid=" + mid + "&type=0&appsongtype=1&_wv=1&source=qq&ADTAG=qfshare"
|
||||
purl := gjson.ParseBytes(pinfo).Get("url_mid.data.midurlinfo.0.purl").Str
|
||||
preview := "http://y.gtimg.cn/music/photo_new/T002R180x180M000" + albumMid + ".jpg"
|
||||
if len(aid) < 2 {
|
||||
return nil, errors.New("song error")
|
||||
}
|
||||
content := "来自go-cqhttp"
|
||||
content := info.Get("track_info.singer.0.name").Str
|
||||
if d["content"] != "" {
|
||||
content = d["content"]
|
||||
}
|
||||
return &QQMusicElement{MusicElement: MusicElement{
|
||||
return &message.MusicShareElement{
|
||||
MusicType: message.QQMusic,
|
||||
Title: name,
|
||||
Summary: content,
|
||||
Url: jumpUrl,
|
||||
Url: jumpURL,
|
||||
PictureUrl: preview,
|
||||
MusicUrl: purl,
|
||||
}}, nil
|
||||
}, nil
|
||||
}
|
||||
if d["type"] == "163" {
|
||||
info, err := global.NeteaseMusicSongInfo(d["id"])
|
||||
@ -730,51 +725,46 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
return nil, errors.New("song not found")
|
||||
}
|
||||
name := info.Get("name").Str
|
||||
jumpUrl := "https://y.music.163.com/m/song/" + d["id"]
|
||||
musicUrl := "http://music.163.com/song/media/outer/url?id=" + d["id"]
|
||||
picUrl := info.Get("album.picUrl").Str
|
||||
jumpURL := "https://y.music.163.com/m/song/" + d["id"]
|
||||
musicURL := "http://music.163.com/song/media/outer/url?id=" + d["id"]
|
||||
picURL := info.Get("album.picUrl").Str
|
||||
artistName := ""
|
||||
if info.Get("artists.0").Exists() {
|
||||
artistName = info.Get("artists.0.name").Str
|
||||
}
|
||||
return &CloudMusicElement{MusicElement{
|
||||
return &message.MusicShareElement{
|
||||
MusicType: message.CloudMusic,
|
||||
Title: name,
|
||||
Summary: artistName,
|
||||
Url: jumpUrl,
|
||||
PictureUrl: picUrl,
|
||||
MusicUrl: musicUrl,
|
||||
}}, nil
|
||||
Url: jumpURL,
|
||||
PictureUrl: picURL,
|
||||
MusicUrl: musicURL,
|
||||
}, nil
|
||||
}
|
||||
if d["type"] == "custom" {
|
||||
if d["subtype"] == "qq" {
|
||||
return &QQMusicElement{MusicElement{
|
||||
Title: d["title"],
|
||||
Summary: d["content"],
|
||||
Url: d["url"],
|
||||
PictureUrl: d["image"],
|
||||
MusicUrl: d["purl"],
|
||||
}}, nil
|
||||
if d["subtype"] != "" {
|
||||
var subtype = map[string]int{
|
||||
"qq": message.QQMusic,
|
||||
"163": message.CloudMusic,
|
||||
"migu": message.MiguMusic,
|
||||
"kugou": message.KugouMusic,
|
||||
"kuwo": message.KuwoMusic,
|
||||
}
|
||||
if d["subtype"] == "163" {
|
||||
return &CloudMusicElement{MusicElement{
|
||||
Title: d["title"],
|
||||
Summary: d["content"],
|
||||
Url: d["url"],
|
||||
PictureUrl: d["image"],
|
||||
MusicUrl: d["purl"],
|
||||
}}, nil
|
||||
var musicType = 0
|
||||
if tp, ok := subtype[d["subtype"]]; ok {
|
||||
musicType = tp
|
||||
}
|
||||
if d["subtype"] == "migu" {
|
||||
return &MiguMusicElement{MusicElement{
|
||||
return &message.MusicShareElement{
|
||||
MusicType: musicType,
|
||||
Title: d["title"],
|
||||
Summary: d["content"],
|
||||
Url: d["url"],
|
||||
PictureUrl: d["image"],
|
||||
MusicUrl: d["purl"],
|
||||
}}, nil
|
||||
}, nil
|
||||
}
|
||||
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>`,
|
||||
XmlEscape(d["title"]), d["url"], d["image"], d["audio"], XmlEscape(d["title"]), XmlEscape(d["content"]))
|
||||
XMLEscape(d["title"]), d["url"], d["image"], d["audio"], XMLEscape(d["title"]), XMLEscape(d["content"]))
|
||||
return &message.ServiceElement{
|
||||
Id: 60,
|
||||
Content: xml,
|
||||
@ -783,14 +773,14 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
}
|
||||
return nil, errors.New("unsupported music type: " + d["type"])
|
||||
case "xml":
|
||||
resId := d["resid"]
|
||||
resID := d["resid"]
|
||||
template := CQCodeEscapeValue(d["data"])
|
||||
i, _ := strconv.ParseInt(resId, 10, 64)
|
||||
i, _ := strconv.ParseInt(resID, 10, 64)
|
||||
msg := message.NewRichXml(template, i)
|
||||
return msg, nil
|
||||
case "json":
|
||||
resId := d["resid"]
|
||||
i, _ := strconv.ParseInt(resId, 10, 64)
|
||||
resID := d["resid"]
|
||||
i, _ := strconv.ParseInt(resID, 10, 64)
|
||||
if i == 0 {
|
||||
// 默认情况下走小程序通道
|
||||
msg := message.NewLightApp(CQCodeUnescapeValue(d["data"]))
|
||||
@ -818,17 +808,17 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
if maxHeight == 0 {
|
||||
maxHeight = 1000
|
||||
}
|
||||
img, err := bot.makeImageOrVideoElem(d, false, group)
|
||||
img, err := bot.makeImageOrVideoElem(d, false, isGroup)
|
||||
if err != nil {
|
||||
return nil, errors.New("send cardimage faild")
|
||||
}
|
||||
return bot.makeShowPic(img, source, icon, minWidth, minHeight, maxWidth, maxHeight, group)
|
||||
return bot.makeShowPic(img, source, icon, minWidth, minHeight, maxWidth, maxHeight, isGroup)
|
||||
case "video":
|
||||
cache := d["cache"]
|
||||
if cache == "" {
|
||||
cache = "1"
|
||||
}
|
||||
file, err := bot.makeImageOrVideoElem(d, true, group)
|
||||
file, err := bot.makeImageOrVideoElem(d, true, isGroup)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -876,12 +866,22 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func XmlEscape(c string) string {
|
||||
// XMLEscape 将字符串c转义为XML字符串
|
||||
func XMLEscape(c string) string {
|
||||
buf := new(bytes.Buffer)
|
||||
_ = xml2.EscapeText(buf, []byte(c))
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
/*CQCodeEscapeText 将字符串raw中部分字符转义
|
||||
|
||||
& -> &
|
||||
|
||||
[ -> [
|
||||
|
||||
] -> ]
|
||||
|
||||
*/
|
||||
func CQCodeEscapeText(raw string) string {
|
||||
ret := raw
|
||||
ret = strings.ReplaceAll(ret, "&", "&")
|
||||
@ -890,12 +890,26 @@ func CQCodeEscapeText(raw string) string {
|
||||
return ret
|
||||
}
|
||||
|
||||
/*CQCodeEscapeValue 将字符串value中部分字符转义
|
||||
|
||||
, -> ,
|
||||
|
||||
*/
|
||||
func CQCodeEscapeValue(value string) string {
|
||||
ret := CQCodeEscapeText(value)
|
||||
ret = strings.ReplaceAll(ret, ",", ",")
|
||||
return ret
|
||||
}
|
||||
|
||||
/*CQCodeUnescapeText 将字符串content中部分字符反转义
|
||||
|
||||
& -> &
|
||||
|
||||
[ -> [
|
||||
|
||||
] -> ]
|
||||
|
||||
*/
|
||||
func CQCodeUnescapeText(content string) string {
|
||||
ret := content
|
||||
ret = strings.ReplaceAll(ret, "[", "[")
|
||||
@ -904,13 +918,18 @@ func CQCodeUnescapeText(content string) string {
|
||||
return ret
|
||||
}
|
||||
|
||||
/*CQCodeUnescapeValue 将字符串content中部分字符反转义
|
||||
|
||||
, -> ,
|
||||
|
||||
*/
|
||||
func CQCodeUnescapeValue(content string) string {
|
||||
ret := strings.ReplaceAll(content, ",", ",")
|
||||
ret = CQCodeUnescapeText(ret)
|
||||
return ret
|
||||
}
|
||||
|
||||
// 图片 elem 生成器,单独拎出来,用于公用
|
||||
// makeImageOrVideoElem 图片 elem 生成器,单独拎出来,用于公用
|
||||
func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (message.IMessageElement, error) {
|
||||
f := d["file"]
|
||||
if strings.HasPrefix(f, "http") || strings.HasPrefix(f, "https") {
|
||||
@ -986,9 +1005,8 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
|
||||
Name: r.ReadString(),
|
||||
Uuid: r.ReadAvailable(),
|
||||
}}, nil
|
||||
} else {
|
||||
return &LocalVideoElement{File: rawPath}, nil
|
||||
}
|
||||
return &LocalVideoElement{File: rawPath}, nil
|
||||
}
|
||||
if strings.HasPrefix(f, "base64") {
|
||||
b, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(f, "base64://", ""))
|
||||
|
2
coolq/doc.go
Normal file
2
coolq/doc.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package coolq 包含CQBot实例,CQ码处理,消息发送,消息处理等的相关函数与结构体
|
||||
package coolq
|
@ -23,11 +23,11 @@ func SetMessageFormat(f string) {
|
||||
}
|
||||
|
||||
// ToFormattedMessage 将给定[]message.IMessageElement转换为通过coolq.SetMessageFormat所定义的消息上报格式
|
||||
func ToFormattedMessage(e []message.IMessageElement, id int64, raw ...bool) (r interface{}) {
|
||||
func ToFormattedMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r interface{}) {
|
||||
if format == "string" {
|
||||
r = ToStringMessage(e, id, raw...)
|
||||
r = ToStringMessage(e, id, isRaw...)
|
||||
} else if format == "array" {
|
||||
r = ToArrayMessage(e, id, raw...)
|
||||
r = ToArrayMessage(e, id, isRaw...)
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -164,7 +164,7 @@ func (bot *CQBot) groupMutedEvent(c *client.QQClient, e *client.GroupMuteEvent)
|
||||
|
||||
func (bot *CQBot) groupRecallEvent(c *client.QQClient, e *client.GroupMessageRecalledEvent) {
|
||||
g := c.FindGroup(e.GroupCode)
|
||||
gid := ToGlobalId(e.GroupCode, e.MessageId)
|
||||
gid := toGlobalID(e.GroupCode, e.MessageId)
|
||||
log.Infof("群 %v 内 %v 撤回了 %v 的消息: %v.",
|
||||
formatGroupName(g), formatMemberName(g.FindMember(e.OperatorUin)), formatMemberName(g.FindMember(e.AuthorUin)), gid)
|
||||
bot.dispatchEventMessage(MSG{
|
||||
@ -258,7 +258,7 @@ func (bot *CQBot) friendNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
|
||||
|
||||
func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageRecalledEvent) {
|
||||
f := c.FindFriend(e.FriendUin)
|
||||
gid := ToGlobalId(e.FriendUin, e.MessageId)
|
||||
gid := toGlobalID(e.FriendUin, e.MessageId)
|
||||
if f != nil {
|
||||
log.Infof("好友 %v(%v) 撤回了消息: %v", f.Nickname, f.Uin, gid)
|
||||
} else {
|
||||
@ -422,8 +422,8 @@ func (bot *CQBot) otherClientStatusChangedEvent(c *client.QQClient, e *client.Ot
|
||||
bot.dispatchEventMessage(MSG{
|
||||
"post_type": "notice",
|
||||
"notice_type": "client_status",
|
||||
"client": MSG{
|
||||
"online": e.Online,
|
||||
"client": MSG{
|
||||
"app_id": e.Client.AppId,
|
||||
"device_name": e.Client.DeviceName,
|
||||
"device_kind": e.Client.DeviceKind,
|
||||
@ -431,7 +431,47 @@ func (bot *CQBot) otherClientStatusChangedEvent(c *client.QQClient, e *client.Ot
|
||||
"self_id": c.Uin,
|
||||
"time": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent) {
|
||||
g := c.FindGroup(e.GroupCode)
|
||||
gid := toGlobalID(e.GroupCode, e.MessageID)
|
||||
if e.OperationType == 1 {
|
||||
log.Infof(
|
||||
"群 %v 内 %v 将 %v 的消息(%v)设为了精华消息.",
|
||||
formatGroupName(g),
|
||||
formatMemberName(g.FindMember(e.OperatorUin)),
|
||||
formatMemberName(g.FindMember(e.SenderUin)),
|
||||
gid,
|
||||
)
|
||||
} else {
|
||||
log.Infof(
|
||||
"群 %v 内 %v 将 %v 的消息(%v)移出了精华消息.",
|
||||
formatGroupName(g),
|
||||
formatMemberName(g.FindMember(e.OperatorUin)),
|
||||
formatMemberName(g.FindMember(e.SenderUin)),
|
||||
gid,
|
||||
)
|
||||
}
|
||||
if e.OperatorUin == bot.Client.Uin {
|
||||
return
|
||||
}
|
||||
bot.dispatchEventMessage(MSG{
|
||||
"post_type": "notice",
|
||||
"group_id": e.GroupCode,
|
||||
"notice_type": "essence",
|
||||
"sub_type": func() string {
|
||||
if e.OperationType == 1 {
|
||||
return "add"
|
||||
}
|
||||
return "delete"
|
||||
}(),
|
||||
"self_id": c.Uin,
|
||||
"sender_id": e.SenderUin,
|
||||
"operator_id": e.OperatorUin,
|
||||
"time": time.Now().Unix(),
|
||||
"message_id": gid,
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) MSG {
|
||||
|
218
docs/cqhttp.md
218
docs/cqhttp.md
@ -42,6 +42,9 @@
|
||||
- [设置群名](#设置群名)
|
||||
- [获取用户VIP信息](#获取用户vip信息)
|
||||
- [发送群公告](#发送群公告)
|
||||
- [设置精华消息](#设置精华消息)
|
||||
- [移出精华消息](#移出精华消息)
|
||||
- [获取精华消息列表](#获取精华消息列表)
|
||||
- [重载事件过滤器](#重载事件过滤器)
|
||||
|
||||
##### 事件
|
||||
@ -53,6 +56,7 @@
|
||||
- [群成员荣誉变更提示](#群成员荣誉变更提示)
|
||||
- [群成员名片更新](#群成员名片更新)
|
||||
- [接收到离线文件](#接收到离线文件)
|
||||
- [群精华消息](#精华消息)
|
||||
|
||||
</p>
|
||||
</details>
|
||||
@ -68,7 +72,7 @@ Type : `image`
|
||||
参数:
|
||||
|
||||
| 参数名 | 可能的值 | 说明 |
|
||||
| ------- | --------------- | --------------------------------------------------------------- |
|
||||
| ------- | --------------- | ---------------------------------------------------------------------- |
|
||||
| `file` | - | 图片文件名 |
|
||||
| `type` | `flash`,`show` | 图片类型,`flash` 表示闪照,`show` 表示秀图,默认普通图片 |
|
||||
| `url` | - | 图片 URL |
|
||||
@ -102,7 +106,7 @@ Type : `reply`
|
||||
参数:
|
||||
|
||||
| 参数名 | 类型 | 说明 |
|
||||
| ------ | ---- | ------------------------------------- |
|
||||
| ------ | ------ | --------------------------------------------------- |
|
||||
| `id` | int | 回复时所引用的消息id, 必须为本群消息. |
|
||||
| `text` | string | 自定义回复的信息 |
|
||||
| `qq` | int64 | 自定义回复时的自定义QQ, 如果使用自定义信息必须指定. |
|
||||
@ -114,6 +118,54 @@ Type : `reply`
|
||||
\
|
||||
自定义回复示例: `[CQ:reply,text=Hello World,qq=10086,time=3376656000]`
|
||||
|
||||
### 音乐分享 <Badge text="发"/>
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "music",
|
||||
"data": {
|
||||
"type": "163",
|
||||
"id": "28949129"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
[CQ:music,type=163,id=28949129]
|
||||
```
|
||||
|
||||
| 参数名 | 收 | 发 | 可能的值 | 说明 |
|
||||
| ------ | --- | --- | ---------- | -------------------------------- |
|
||||
| `type` | | ✓ | `qq` `163` | 分别表示使用 QQ 音乐、网易云音乐 |
|
||||
| `id` | | ✓ | - | 歌曲 ID |
|
||||
|
||||
### 音乐自定义分享 <Badge text="发"/>
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "music",
|
||||
"data": {
|
||||
"type": "custom",
|
||||
"url": "http://baidu.com",
|
||||
"audio": "http://baidu.com/1.mp3",
|
||||
"title": "音乐标题"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
[CQ:music,type=custom,url=http://baidu.com,audio=http://baidu.com/1.mp3,title=音乐标题]
|
||||
```
|
||||
|
||||
| 参数名 | 收 | 发 | 可能的值 | 说明 |
|
||||
| --------- | --- | --- | ------------------------ | ----------------------------------------------------- |
|
||||
| `type` | | ✓ | `custom` | 表示音乐自定义分享 |
|
||||
| `subtype` | | ✓ | `qq,163,migu,kugou,kuwo` | 表示分享类型,不填写发送为xml卡片,推荐填写提高稳定性 |
|
||||
| `url` | | ✓ | - | 点击后跳转目标 URL |
|
||||
| `audio` | | ✓ | - | 音乐 URL |
|
||||
| `title` | | ✓ | - | 标题 |
|
||||
| `content` | | ✓ | - | 内容描述 |
|
||||
| `image` | | ✓ | - | 图片 URL |
|
||||
|
||||
### 红包
|
||||
|
||||
@ -192,7 +244,7 @@ Type: `forward`
|
||||
参数:
|
||||
|
||||
| 参数名 | 类型 | 说明 |
|
||||
| ------ | ------ | ------------------------------------------------------------ |
|
||||
| ------ | ------ | ------------------------------------------------------------- |
|
||||
| `id` | string | 合并转发ID, 需要通过 `/get_forward_msg` API获取转发的具体内容 |
|
||||
|
||||
示例: `[CQ:forward,id=xxxx]`
|
||||
@ -206,7 +258,7 @@ Type: `node`
|
||||
参数:
|
||||
|
||||
| 参数名 | 类型 | 说明 | 特殊说明 |
|
||||
| --------- | ------- | -------------- | ------------------------------------------------------------ |
|
||||
| --------- | ------- | -------------- | -------------------------------------------------------------------------------------- |
|
||||
| `id` | int32 | 转发消息id | 直接引用他人的消息合并转发, 实际查看顺序为原消息发送顺序 **与下面的自定义消息二选一** |
|
||||
| `name` | string | 发送者显示名字 | 用于自定义消息 (自定义消息并合并转发,实际查看顺序为自定义消息段顺序) |
|
||||
| `uin` | int64 | 发送者QQ号 | 用于自定义消息 |
|
||||
@ -293,7 +345,7 @@ Type: `video`
|
||||
参数:
|
||||
|
||||
| 参数名 | 类型 | 说明 |
|
||||
| ------- | ------ | ------------------------------------------------|
|
||||
| ------- | ------- | ---------------------------------------------------------------------- |
|
||||
| `file` | string | 支持http和file发送 |
|
||||
| `cover` | string | 视频封面,支持http,file和base64发送,格式必须为jpg |
|
||||
| `c` | `2` `3` | 通过网络下载视频时的线程数, 默认单线程. (在资源不支持并发时会自动处理) |
|
||||
@ -575,11 +627,63 @@ Type: `tts`
|
||||
| -------- | -------- | ---- |
|
||||
| `slices` | string[] | 词组 |
|
||||
|
||||
### 设置精华消息
|
||||
|
||||
终结点: `/set_essence_msg`
|
||||
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------ | ----- | ------ |
|
||||
| `message_id` | int32 | 消息ID |
|
||||
|
||||
**响应数据**
|
||||
|
||||
无
|
||||
|
||||
### 移出精华消息
|
||||
|
||||
终结点: `/delete_essence_msg`
|
||||
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------ | ----- | ------ |
|
||||
| `message_id` | int32 | 消息ID |
|
||||
|
||||
**响应数据**
|
||||
|
||||
无
|
||||
|
||||
### 获取精华消息列表
|
||||
|
||||
终结点: `/get_essence_msg_list`
|
||||
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ----- | ---- |
|
||||
| `group_id` | int64 | 群号 |
|
||||
|
||||
**响应数据**
|
||||
|
||||
响应内容为 JSON 数组,每个元素如下:
|
||||
|
||||
| 字段名 | 数据类型 | 说明 |
|
||||
| --------------- | -------- | ------------ |
|
||||
| `sender_id` | int64 | 发送者QQ 号 |
|
||||
| `sender_nick` | string | 发送者昵称 |
|
||||
| `sender_time` | int64 | 消息发送时间 |
|
||||
| `operator_id` | int64 | 发送者QQ 号 |
|
||||
| `operator_nick` | string | 发送者昵称 |
|
||||
| `operator_time` | int64 | 消息发送时间 |
|
||||
| `message_id` | int32 | 消息ID |
|
||||
|
||||
### 图片OCR
|
||||
|
||||
> 注意: 目前图片OCR接口仅支持接受的图片
|
||||
|
||||
终结点: `/.ocr_image`
|
||||
终结点: `/ocr_image`
|
||||
|
||||
**参数**
|
||||
|
||||
@ -745,6 +849,22 @@ Type: `tts`
|
||||
| `creator_name` | string | 创建者名字 |
|
||||
| `total_file_count` | int32 | 子文件数量 |
|
||||
|
||||
### 上传群文件
|
||||
|
||||
终结点: `/upload_group_file`
|
||||
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ------ | ------------------------- |
|
||||
| `group_id` | int64 | 群号 |
|
||||
| `file` | string | 本地文件路径 |
|
||||
| `name` | string | 储存名称 |
|
||||
| `folder` | string | 父目录ID |
|
||||
|
||||
> 在不提供 `folder` 参数的情况下默认上传到根目录
|
||||
> 只能上传本地文件, 需要上传 `http` 文件的话请先调用 `download_file` API下载
|
||||
|
||||
### 获取状态
|
||||
|
||||
终结点: `/get_status`
|
||||
@ -783,13 +903,13 @@ Type: `tts`
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ------ | ------------------------- |
|
||||
| ---------- | ----- | ---- |
|
||||
| `group_id` | int64 | 群号 |
|
||||
|
||||
**响应数据**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------------------------- | ---------- | ------------------------------- |
|
||||
| ------------------------------- | ----- | --------------------------------- |
|
||||
| `can_at_all` | bool | 是否可以@全体成员 |
|
||||
| `remain_at_all_count_for_group` | int16 | 群内所有管理当天剩余@全体成员次数 |
|
||||
| `remain_at_all_count_for_uin` | int16 | BOT当天剩余@全体成员次数 |
|
||||
@ -801,7 +921,7 @@ Type: `tts`
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ------ | ------------------------- |
|
||||
| -------------- | --------------- | ------------ |
|
||||
| `url` | string | 链接地址 |
|
||||
| `thread_count` | int32 | 下载线程数 |
|
||||
| `headers` | string or array | 自定义请求头 |
|
||||
@ -828,7 +948,7 @@ JSON数组:
|
||||
**响应数据**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ---------- | ------------ |
|
||||
| ------ | ------ | -------------------- |
|
||||
| `file` | string | 下载文件的*绝对路径* |
|
||||
|
||||
> 通过这个API下载的文件能直接放入CQ码作为图片或语音发送
|
||||
@ -841,18 +961,58 @@ JSON数组:
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ------ | ------------------------- |
|
||||
| `message_seq` | int64 | 起始消息序号, 可通过 `get_msg` 的 `real_id` 获得 |
|
||||
| ------------- | ----- | ----------------------------------- |
|
||||
| `message_seq` | int64 | 起始消息序号, 可通过 `get_msg` 获得 |
|
||||
| `group_id` | int64 | 群号 |
|
||||
|
||||
**响应数据**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ---------- | ------------ |
|
||||
| ---------- | --------- | -------------------------- |
|
||||
| `messages` | []Message | 从起始序号开始的前19条消息 |
|
||||
|
||||
> 不提供起始序号将默认获取最新的消息
|
||||
|
||||
### 获取当前账号在线客户端列表
|
||||
|
||||
终结点:`/get_online_clients`
|
||||
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ---- | ------------ |
|
||||
| `no_cache` | bool | 是否无视缓存 |
|
||||
|
||||
**响应数据**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --------- | -------- | -------------- |
|
||||
| `clients` | []Device | 在线客户端列表 |
|
||||
|
||||
**Device**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------- | ------ | -------- |
|
||||
| `app_id` | int64 | 客户端ID |
|
||||
| `device_name` | string | 设备名称 |
|
||||
| `device_kind` | string | 设备类型 |
|
||||
|
||||
### 检查链接安全性
|
||||
|
||||
终结点:`/check_url_safely`
|
||||
|
||||
**参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ------ | ------------------------- |
|
||||
| `url` | string | 需要检查的链接 |
|
||||
|
||||
**响应数据**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ---------- | ------------ |
|
||||
| `level` | int | 安全等级, 1: 安全 2: 未知 3: 危险 |
|
||||
|
||||
### 获取用户VIP信息
|
||||
|
||||
终结点:`/_get_vip_info`
|
||||
@ -860,13 +1020,13 @@ JSON数组:
|
||||
**参数**
|
||||
|
||||
| 字段名 | 数据类型 | 默认值 | 说明 |
|
||||
| ----- | ------- | ----- | --- |
|
||||
| --------- | -------- | ------ | ----- |
|
||||
| `user_id` | int64 | | QQ 号 |
|
||||
|
||||
**响应数据**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------------ | ------- | ---------- |
|
||||
| ------------------ | ------- | ------------ |
|
||||
| `user_id` | int64 | QQ 号 |
|
||||
| `nickname` | string | 用户昵称 |
|
||||
| `level` | int64 | QQ 等级 |
|
||||
@ -882,7 +1042,7 @@ JSON数组:
|
||||
**参数**
|
||||
|
||||
| 字段名 | 数据类型 | 默认值 | 说明 |
|
||||
| ---------- | ------- | ----- | ------ |
|
||||
| ---------- | -------- | ------ | -------- |
|
||||
| `group_id` | int64 | | 群号 |
|
||||
| `content` | string | | 公告内容 |
|
||||
|
||||
@ -926,7 +1086,7 @@ JSON数组:
|
||||
**事件数据**
|
||||
|
||||
| 字段名 | 数据类型 | 可能的值 | 说明 |
|
||||
| ------------- | ------ | -------- | --- |
|
||||
| ------------- | -------- | -------- | ------------ |
|
||||
| `post_type` | string | `notice` | 上报类型 |
|
||||
| `notice_type` | string | `notify` | 消息类型 |
|
||||
| `sub_type` | string | `poke` | 提示类型 |
|
||||
@ -1016,3 +1176,27 @@ JSON数组:
|
||||
| `name` | string | | 文件名 |
|
||||
| `size` | int64 | | 文件大小 |
|
||||
| `url` | string | | 下载链接 |
|
||||
|
||||
### 其他客户端在线状态变更
|
||||
|
||||
**上报数据**
|
||||
|
||||
| 字段 | 类型 | 可能的值 | 说明 |
|
||||
| ------------- | ------ | --------------- | ------------ |
|
||||
| `post_type` | string | `notice` | 上报类型 |
|
||||
| `notice_type` | string | `client_status` | 消息类型 |
|
||||
| `client` | Device | | 客户端信息 |
|
||||
| `online` | bool | | 当前是否在线 |
|
||||
|
||||
### 精华消息
|
||||
|
||||
**上报数据**
|
||||
|
||||
| 字段 | 类型 | 可能的值 | 说明 |
|
||||
| ------------- | ------ | -------------- | -------------------------- |
|
||||
| `post_type` | string | `notice` | 上报类型 |
|
||||
| `notice_type` | string | `essence` | 消息类型 |
|
||||
| `sub_type` | string | `add`,`delete` | 添加为`add`,移出为`delete` |
|
||||
| `sender_id` | int64 | | 消息发送者ID |
|
||||
| `operator_id` | int64 | | 操作者ID |
|
||||
| `message_id` | int32 | | 消息ID |
|
||||
|
@ -2,37 +2,21 @@ package global
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os/exec"
|
||||
"path"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global/codec"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var useSilkCodec = true
|
||||
|
||||
//InitCodec 初始化Silk编码器
|
||||
func InitCodec() {
|
||||
log.Info("正在加载silk编码器...")
|
||||
err := codec.Init()
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
useSilkCodec = false
|
||||
}
|
||||
}
|
||||
|
||||
// EncoderSilk 将音频编码为Silk
|
||||
func EncoderSilk(data []byte) ([]byte, error) {
|
||||
if !useSilkCodec {
|
||||
return nil, errors.New("no silk encoder")
|
||||
}
|
||||
h := md5.New()
|
||||
_, err := h.Write(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.Wrap(err, "calc md5 failed")
|
||||
}
|
||||
tempName := fmt.Sprintf("%x", h.Sum(nil))
|
||||
if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) {
|
||||
@ -40,7 +24,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
|
||||
}
|
||||
slk, err := codec.EncodeToSilk(data, tempName, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.Wrap(err, "encode silk failed")
|
||||
}
|
||||
return slk, nil
|
||||
}
|
||||
@ -51,7 +35,7 @@ func EncodeMP4(src string, dst string) error { // -y 覆盖文件
|
||||
err := cmd1.Run()
|
||||
if err != nil {
|
||||
cmd2 := exec.Command("ffmpeg", "-i", src, "-y", "-c:v", "h264", "-c:a", "mp3", dst)
|
||||
return cmd2.Run()
|
||||
return errors.Wrap(cmd2.Run(), "convert mp4 failed")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@ -59,5 +43,5 @@ func EncodeMP4(src string, dst string) error { // -y 覆盖文件
|
||||
// ExtractCover 获取给定视频文件的Cover
|
||||
func ExtractCover(src string, target string) error {
|
||||
cmd := exec.Command("ffmpeg", "-i", src, "-y", "-r", "1", "-f", "image2", target)
|
||||
return cmd.Run()
|
||||
return errors.Wrap(cmd.Run(), "extract video cover failed")
|
||||
}
|
||||
|
@ -1,69 +1,30 @@
|
||||
// +build linux windows darwin
|
||||
// +build linux windows,!arm darwin
|
||||
// +build 386 amd64 arm arm64
|
||||
|
||||
// Package codec Slik编码核心模块
|
||||
package codec
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"runtime"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/wdvxdr1123/go-silk"
|
||||
)
|
||||
|
||||
const (
|
||||
silkCachePath = "data/cache"
|
||||
encoderPath = "codec"
|
||||
)
|
||||
|
||||
func downloadCodec(url string) (err error) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = ioutil.WriteFile(getEncoderFilePath(), body, os.ModePerm)
|
||||
return
|
||||
}
|
||||
|
||||
func getEncoderFilePath() string {
|
||||
encoderFile := path.Join(encoderPath, runtime.GOOS+"-"+runtime.GOARCH+"-encoder")
|
||||
if runtime.GOOS == "windows" {
|
||||
encoderFile = encoderFile + ".exe"
|
||||
}
|
||||
return encoderFile
|
||||
}
|
||||
|
||||
//Init 下载Silk编码器
|
||||
func Init() error {
|
||||
if !fileExist(silkCachePath) {
|
||||
_ = os.MkdirAll(silkCachePath, os.ModePerm)
|
||||
}
|
||||
if !fileExist(encoderPath) {
|
||||
_ = os.MkdirAll(encoderPath, os.ModePerm)
|
||||
}
|
||||
p := getEncoderFilePath()
|
||||
if !fileExist(p) {
|
||||
if err := downloadCodec("https://cdn.jsdelivr.net/gh/wdvxdr1123/tosilk/codec/" + runtime.GOOS + "-" + runtime.GOARCH + "-encoder"); err != nil {
|
||||
return errors.New("下载依赖失败")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//EncodeToSilk 将音频编码为Silk
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) {
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte, err error) {
|
||||
// 1. 写入缓存文件
|
||||
rawPath := path.Join(silkCachePath, tempName+".wav")
|
||||
err := ioutil.WriteFile(rawPath, record, os.ModePerm)
|
||||
err = ioutil.WriteFile(rawPath, record, os.ModePerm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.Wrap(err, "write temp file error")
|
||||
}
|
||||
defer os.Remove(rawPath)
|
||||
|
||||
@ -71,27 +32,22 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error)
|
||||
pcmPath := path.Join(silkCachePath, tempName+".pcm")
|
||||
cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath)
|
||||
if err = cmd.Run(); err != nil {
|
||||
return nil, err
|
||||
return nil, errors.Wrap(err, "convert pcm file error")
|
||||
}
|
||||
defer os.Remove(pcmPath)
|
||||
|
||||
// 3. 转silk
|
||||
pcm, err := ioutil.ReadFile(pcmPath)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read pcm file err")
|
||||
}
|
||||
silkWav, err = silk.EncodePcmBuffToSilk(pcm, 24000, 24000, true)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "silk encode error")
|
||||
}
|
||||
if useCache {
|
||||
silkPath := path.Join(silkCachePath, tempName+".silk")
|
||||
cmd = exec.Command(getEncoderFilePath(), pcmPath, silkPath, "-rate", "24000", "-quiet", "-tencent")
|
||||
if err = cmd.Run(); err != nil {
|
||||
return nil, err
|
||||
err = ioutil.WriteFile(silkPath, silkWav, 0666)
|
||||
}
|
||||
if !useCache {
|
||||
defer os.Remove(silkPath)
|
||||
}
|
||||
return ioutil.ReadFile(silkPath)
|
||||
}
|
||||
|
||||
// FileExist 检查文件是否存在
|
||||
func fileExist(path string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
path = path + ".exe"
|
||||
}
|
||||
_, err := os.Lstat(path)
|
||||
return !os.IsNotExist(err)
|
||||
return
|
||||
}
|
||||
|
8
global/codec/codec__windows_arm.go
Normal file
8
global/codec/codec__windows_arm.go
Normal file
@ -0,0 +1,8 @@
|
||||
package codec
|
||||
|
||||
import "errors"
|
||||
|
||||
//EncodeToSilk 将音频编码为Silk
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) {
|
||||
return nil, errors.New("not supported now")
|
||||
}
|
@ -1,15 +1,10 @@
|
||||
// +build !386,!arm64,!amd64,!arm
|
||||
// +build !arm,!arm64,!amd64,!386
|
||||
|
||||
package codec
|
||||
|
||||
import "errors"
|
||||
|
||||
//Init 下载silk编码器
|
||||
func Init() error {
|
||||
return errors.New("Unsupport arch now")
|
||||
}
|
||||
|
||||
//EncodeToSilk 将音频编码为Silk
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) {
|
||||
return nil, errors.New("Unsupport arch now")
|
||||
return nil, errors.New("not supported now")
|
||||
}
|
||||
|
@ -4,12 +4,7 @@ package codec
|
||||
|
||||
import "errors"
|
||||
|
||||
//Init 下载silk编码器
|
||||
func Init() error {
|
||||
return errors.New("not support now")
|
||||
}
|
||||
|
||||
//EncodeToSilk 将音频编码为Silk
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) {
|
||||
return nil, errors.New("not support now")
|
||||
return nil, errors.New("not supported now")
|
||||
}
|
||||
|
@ -119,8 +119,8 @@ var DefaultConfigWithComments = `
|
||||
use_sso_address: false
|
||||
// 是否启用 DEBUG
|
||||
debug: false
|
||||
// 日志等级
|
||||
log_level: ""
|
||||
// 日志等级 trace,debug,info,warn,error
|
||||
log_level: "info"
|
||||
// WebUi 设置
|
||||
web_ui: {
|
||||
// 是否启用 WebUi
|
||||
@ -135,6 +135,9 @@ var DefaultConfigWithComments = `
|
||||
}
|
||||
`
|
||||
|
||||
// PasswordHash 存储QQ密码哈希供登录使用
|
||||
var PasswordHash [16]byte
|
||||
|
||||
// JSONConfig Config对应的结构体
|
||||
type JSONConfig struct {
|
||||
Uin int64 `json:"uin"`
|
||||
@ -274,8 +277,8 @@ func DefaultConfig() *JSONConfig {
|
||||
}
|
||||
}
|
||||
|
||||
//Load 加载配置文件
|
||||
func Load(p string) *JSONConfig {
|
||||
// LoadConfig 加载配置文件
|
||||
func LoadConfig(p string) *JSONConfig {
|
||||
if !PathExists(p) {
|
||||
log.Warnf("尝试加载配置文件 %v 失败: 文件不存在", p)
|
||||
return nil
|
||||
|
2
global/doc.go
Normal file
2
global/doc.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package global 包含文件下载,视频音频编码,本地文件缓存处理,消息过滤器,调用速率限制,gocq主配置等的相关函数与结构体
|
||||
package global
|
@ -25,12 +25,18 @@ func (m MSG) Get(s string) MSG {
|
||||
}
|
||||
return MSG{"__str__": v} // 用这个名字应该没问题吧
|
||||
}
|
||||
return MSG{}
|
||||
return nil // 不存在为空
|
||||
}
|
||||
|
||||
// String 将消息Map转化为String。若Map存在key "__str__",则返回此key对应的值,否则将输出整张消息Map对应的JSON字符串
|
||||
func (m MSG) String() string {
|
||||
if m == nil {
|
||||
return "" // 空 JSON
|
||||
}
|
||||
if str, ok := m["__str__"]; ok {
|
||||
if str == nil {
|
||||
return "" // 空 JSON
|
||||
}
|
||||
return fmt.Sprint(str)
|
||||
}
|
||||
str, _ := json.MarshalToString(m)
|
||||
@ -285,7 +291,7 @@ func Generate(opName string, argument gjson.Result) Filter {
|
||||
}
|
||||
|
||||
// EventFilter 初始化一个nil过滤器
|
||||
var EventFilter Filter = nil
|
||||
var EventFilter Filter
|
||||
|
||||
// BootFilter 启动事件过滤器
|
||||
func BootFilter() {
|
||||
|
165
global/log_hook.go
Normal file
165
global/log_hook.go
Normal file
@ -0,0 +1,165 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// LocalHook logrus本地钩子
|
||||
type LocalHook struct {
|
||||
lock *sync.Mutex
|
||||
levels []logrus.Level // hook级别
|
||||
formatter logrus.Formatter // 格式
|
||||
path string // 写入path
|
||||
writer io.Writer // io
|
||||
}
|
||||
|
||||
// Levels ref: logrus/hooks.go impl Hook interface
|
||||
func (hook *LocalHook) Levels() []logrus.Level {
|
||||
if len(hook.levels) == 0 {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
return hook.levels
|
||||
}
|
||||
|
||||
func (hook *LocalHook) ioWrite(entry *logrus.Entry) error {
|
||||
log, err := hook.formatter.Format(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = hook.writer.Write(log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hook *LocalHook) pathWrite(entry *logrus.Entry) error {
|
||||
dir := filepath.Dir(hook.path)
|
||||
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fd, err := os.OpenFile(hook.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fd.Close()
|
||||
|
||||
log, err := hook.formatter.Format(entry)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = fd.Write(log)
|
||||
return err
|
||||
}
|
||||
|
||||
// Fire ref: logrus/hooks.go impl Hook interface
|
||||
func (hook *LocalHook) Fire(entry *logrus.Entry) error {
|
||||
hook.lock.Lock()
|
||||
defer hook.lock.Unlock()
|
||||
|
||||
if hook.writer != nil {
|
||||
return hook.ioWrite(entry)
|
||||
}
|
||||
|
||||
if hook.path != "" {
|
||||
return hook.pathWrite(entry)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetFormatter 设置日志格式
|
||||
func (hook *LocalHook) SetFormatter(formatter logrus.Formatter) {
|
||||
hook.lock.Lock()
|
||||
defer hook.lock.Unlock()
|
||||
|
||||
if formatter == nil {
|
||||
// 用默认的
|
||||
formatter = &logrus.TextFormatter{DisableColors: true}
|
||||
} else {
|
||||
switch f := formatter.(type) {
|
||||
case *logrus.TextFormatter:
|
||||
textFormatter := f
|
||||
textFormatter.DisableColors = true
|
||||
default:
|
||||
// todo
|
||||
}
|
||||
}
|
||||
logrus.SetFormatter(formatter)
|
||||
hook.formatter = formatter
|
||||
}
|
||||
|
||||
// SetWriter 设置Writer
|
||||
func (hook *LocalHook) SetWriter(writer io.Writer) {
|
||||
hook.lock.Lock()
|
||||
defer hook.lock.Unlock()
|
||||
hook.writer = writer
|
||||
}
|
||||
|
||||
// SetPath 设置日志写入路径
|
||||
func (hook *LocalHook) SetPath(path string) {
|
||||
hook.lock.Lock()
|
||||
defer hook.lock.Unlock()
|
||||
hook.path = path
|
||||
}
|
||||
|
||||
// NewLocalHook 初始化本地日志钩子实现
|
||||
func NewLocalHook(args interface{}, formatter logrus.Formatter, levels ...logrus.Level) *LocalHook {
|
||||
hook := &LocalHook{
|
||||
lock: new(sync.Mutex),
|
||||
}
|
||||
hook.SetFormatter(formatter)
|
||||
hook.levels = append(hook.levels, levels...)
|
||||
|
||||
switch arg := args.(type) {
|
||||
case string:
|
||||
hook.SetPath(arg)
|
||||
case io.Writer:
|
||||
hook.SetWriter(arg)
|
||||
default:
|
||||
panic(fmt.Sprintf("unsupported type: %v", reflect.TypeOf(args)))
|
||||
}
|
||||
|
||||
return hook
|
||||
}
|
||||
|
||||
// GetLogLevel 获取日志等级
|
||||
//
|
||||
// 可能的值有
|
||||
//
|
||||
// "trace","debug","info","warn","warn","error"
|
||||
func GetLogLevel(level string) []logrus.Level {
|
||||
switch level {
|
||||
case "trace":
|
||||
return []logrus.Level{logrus.TraceLevel, logrus.DebugLevel,
|
||||
logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel}
|
||||
case "debug":
|
||||
return []logrus.Level{logrus.DebugLevel, logrus.InfoLevel,
|
||||
logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel}
|
||||
case "info":
|
||||
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel,
|
||||
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}
|
||||
case "warn":
|
||||
return []logrus.Level{logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel}
|
||||
case "error":
|
||||
return []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel,
|
||||
logrus.PanicLevel}
|
||||
default:
|
||||
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel,
|
||||
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}
|
||||
}
|
||||
}
|
13
go.mod
13
go.mod
@ -3,24 +3,27 @@ module github.com/Mrs4s/go-cqhttp
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210120152724-83f2eb02e6be
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210211030658-9f1cf68e0e7c
|
||||
github.com/dustin/go-humanize v1.0.0
|
||||
github.com/gin-contrib/pprof v1.3.0
|
||||
github.com/gin-gonic/gin v1.6.3
|
||||
github.com/gorilla/websocket v1.4.2
|
||||
github.com/guonaihong/gout v0.1.4
|
||||
github.com/guonaihong/gout v0.1.5
|
||||
github.com/hjson/hjson-go v3.1.0+incompatible
|
||||
github.com/json-iterator/go v1.1.10
|
||||
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
|
||||
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
|
||||
github.com/lestrrat-go/strftime v1.0.4 // indirect
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
|
||||
github.com/sirupsen/logrus v1.7.0
|
||||
github.com/syndtr/goleveldb v1.0.0
|
||||
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
|
||||
github.com/tidwall/gjson v1.6.7
|
||||
github.com/tidwall/gjson v1.6.8
|
||||
github.com/wdvxdr1123/go-silk v0.0.0-20210207032612-169bbdf8861d
|
||||
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
|
||||
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 // indirect
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c // indirect
|
||||
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf
|
||||
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
|
85
go.sum
85
go.sum
@ -1,17 +1,23 @@
|
||||
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/Mrs4s/MiraiGo v0.0.0-20210118164518-b007a4d0d68c h1:HNyjAEK3nj+h8EMqoFEARnE+G/rlJDlh1BFEIShA6lk=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210118164518-b007a4d0d68c/go.mod h1:9V7DdSwpEfCKQNvLZhRnFJFkelTU0tPLfwR5l6UFF1Y=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210120152724-83f2eb02e6be h1:S52Ht2a/fHLiZS83dC0ciygzm0TWzfzfOru6e1qpYGU=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210120152724-83f2eb02e6be/go.mod h1:9V7DdSwpEfCKQNvLZhRnFJFkelTU0tPLfwR5l6UFF1Y=
|
||||
github.com/LXY1226/fastrand v0.0.0-20210121160840-7a3db3e79031 h1:DnoCySrXUFvtngW2kSkuBeZoPfvOgctJXjTulCn7eV0=
|
||||
github.com/LXY1226/fastrand v0.0.0-20210121160840-7a3db3e79031/go.mod h1:mEFi4jHUsE2sqQGSJ7eQfXnO8esMzEYcftiCGG+L/OE=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210125093830-340977eb201f h1:v86jOk27ypxD3gT48KJDy/Y5w7PIaTvabZYdDszr3w0=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210125093830-340977eb201f/go.mod h1:JBm2meosyXAASbl8mZ+mFZEkE/2cC7zNZdIOBe7+QhY=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210206134348-800bf525ed0e h1:SnN+nyRdqN7sULnHUWCofP+Jxs3VJN/y8AlMpcz0nbk=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210206134348-800bf525ed0e/go.mod h1:yhqA0NyKxUf7I/0HR/1OMchveFggX8wde04gqdGrNfU=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210211030658-9f1cf68e0e7c h1:H5RT6SybX5six6VZpdQRmUOV8XcqoQQ4cZM0gZ0yeNo=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210211030658-9f1cf68e0e7c/go.mod h1:yhqA0NyKxUf7I/0HR/1OMchveFggX8wde04gqdGrNfU=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/gin-contrib/pprof v1.3.0 h1:G9eK6HnbkSqDZBYbzG4wrjCsA4e+cvYAHUZw6W+W9K0=
|
||||
github.com/gin-contrib/pprof v1.3.0/go.mod h1:waMjT1H9b179t3CxuG1cV3DHpga6ybizwfBaM5OXaB0=
|
||||
@ -21,6 +27,7 @@ github.com/gin-gonic/gin v1.6.0/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwv
|
||||
github.com/gin-gonic/gin v1.6.2/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
|
||||
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
@ -28,6 +35,8 @@ github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD87
|
||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
|
||||
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
|
||||
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
@ -43,20 +52,30 @@ github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw=
|
||||
github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/guonaihong/gout v0.1.4 h1:uBBoyztMX9okC27OQxqhn6bZ0ROkGyvnEIHwtp3TM4g=
|
||||
github.com/guonaihong/gout v0.1.4/go.mod h1:0rFYAYyzbcxEg11eY2qUbffJs7hHRPeugAnlVYSp8Ic=
|
||||
github.com/guonaihong/gout v0.1.5 h1:1FeFFJWWdWYApBW9d6vzMDB4eR4Zr8T/gaVrjDVcl5U=
|
||||
github.com/guonaihong/gout v0.1.5/go.mod h1:0rFYAYyzbcxEg11eY2qUbffJs7hHRPeugAnlVYSp8Ic=
|
||||
github.com/hjson/hjson-go v3.1.0+incompatible h1:DY/9yE8ey8Zv22bY+mHV1uk2yRy0h8tKhZ77hEdi0Aw=
|
||||
github.com/hjson/hjson-go v3.1.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio=
|
||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
|
||||
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
|
||||
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68=
|
||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
@ -65,6 +84,9 @@ github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALr
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
||||
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8=
|
||||
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is=
|
||||
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4=
|
||||
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA=
|
||||
@ -74,20 +96,27 @@ github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHX
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
|
||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
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/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/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
@ -95,24 +124,41 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
|
||||
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
|
||||
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 h1:J6v8awz+me+xeb/cUTotKgceAYouhIB3pjzgRd6IlGk=
|
||||
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816/go.mod h1:tzym/CEb5jnFI+Q0k4Qq3+LvRF4gO3E2pxS8fHP8jcA=
|
||||
github.com/tidwall/gjson v1.6.7 h1:Mb1M9HZCRWEcXQ8ieJo7auYyyiSux6w9XN3AdTpxJrE=
|
||||
github.com/tidwall/gjson v1.6.7/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI=
|
||||
github.com/tidwall/gjson v1.6.8 h1:CTmXMClGYPAmln7652e69B7OLXfTi5ABcPPwjIWUv7w=
|
||||
github.com/tidwall/gjson v1.6.8/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI=
|
||||
github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
|
||||
github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
|
||||
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go v1.2.4 h1:cTciPbZ/VSOzCLKclmssnfQ/jyoVyOcJ3aoJyUV1Urc=
|
||||
github.com/ugorji/go v1.2.4/go.mod h1:EuaSCk8iZMdIspsu6HXH7X2UGKw1ezO4wCfGszGmmo4=
|
||||
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
|
||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||
github.com/ugorji/go/codec v1.2.4 h1:C5VurWRRCKjuENsbM6GYVw8W++WVW9rSxoACKIvxzz8=
|
||||
github.com/ugorji/go/codec v1.2.4/go.mod h1:bWBu1+kIRWcF8uMklKaJrR6fTWQOwAlrIzX22pHwryA=
|
||||
github.com/wdvxdr1123/go-silk v0.0.0-20210207032612-169bbdf8861d h1:gJTKbjZtlMt/almOeFi/UpVtT3RHqRWscgEuDtnF5TU=
|
||||
github.com/wdvxdr1123/go-silk v0.0.0-20210207032612-169bbdf8861d/go.mod h1:twOxzexmM2Il1ReUu1fB5tnUotOq/dp56xjk/ZHwb1I=
|
||||
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 h1:4UJw9if55Fu3HOwbfcaQlJ27p3oeJU2JZqoeT3ITJQk=
|
||||
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189/go.mod h1:rIrm5geMiBhPQkdfUm8gDFi/WiHneOp1i9KjmJqc+9I=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY=
|
||||
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
@ -122,8 +168,11 @@ golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73r
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa h1:F+8P+gmewFQYRk6JoLQLwjBCTu3mcIURZfNkVweuRKA=
|
||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew=
|
||||
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@ -131,15 +180,24 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201126233918-771906719818 h1:f1CIuDlJhwANEC2MM87MBEVMr3jl5bifgsfj90XAF9c=
|
||||
golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf h1:MZ2shdL+ZM/XzY3ZGOnh4Nlpnxz5GSOhOmtHo3iPU6M=
|
||||
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2YxUgyZ7EFOSLIcSSpiwE=
|
||||
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@ -147,6 +205,7 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
@ -166,12 +225,26 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
|
||||
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=
|
||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
modernc.org/libc v1.7.6 h1:P0qDJAlSR6hSAuE8mQgz9eH/GzigfEd3IIn7HmTQgT0=
|
||||
modernc.org/libc v1.7.6/go.mod h1:U1eq8YWr/Kc1RWCMFUWEdkTg8OTcfLw2kY8EDwl039w=
|
||||
modernc.org/mathutil v1.1.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/mathutil v1.2.2 h1:+yFk8hBprV+4c0U9GjFtL+dV3N8hOJ8JCituQcMShFY=
|
||||
modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/memory v1.0.4 h1:utMBrFcpnQDdNsmM6asmyH/FM9TqLPS7XF7otpJmrwM=
|
||||
modernc.org/memory v1.0.4/go.mod h1:nV2OApxradM3/OVbs2/0OsP6nPfakXpi50C7dcoHXlc=
|
||||
|
289
main.go
289
main.go
@ -2,8 +2,11 @@ package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/aes"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
@ -22,6 +25,7 @@ import (
|
||||
"github.com/Mrs4s/go-cqhttp/server"
|
||||
"github.com/guonaihong/gout"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/binary"
|
||||
@ -30,42 +34,15 @@ import (
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
"github.com/rifflock/lfshook"
|
||||
log "github.com/sirupsen/logrus"
|
||||
easy "github.com/t-tomalak/logrus-easy-formatter"
|
||||
)
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
var conf *global.JSONConfig
|
||||
var isFastStart = false
|
||||
|
||||
func init() {
|
||||
log.SetFormatter(&easy.Formatter{
|
||||
TimestampFormat: "2006-01-02 15:04:05",
|
||||
LogFormat: "[%time%] [%lvl%]: %msg% \n",
|
||||
})
|
||||
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotatelogs.WithRotationTime(time.Hour*24))
|
||||
if err == nil {
|
||||
log.SetOutput(io.MultiWriter(os.Stderr, w))
|
||||
}
|
||||
if !global.PathExists(global.ImagePath) {
|
||||
if err := os.MkdirAll(global.ImagePath, 0755); err != nil {
|
||||
log.Fatalf("创建图片缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if !global.PathExists(global.VoicePath) {
|
||||
if err := os.MkdirAll(global.VoicePath, 0755); err != nil {
|
||||
log.Fatalf("创建语音缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if !global.PathExists(global.VideoPath) {
|
||||
if err := os.MkdirAll(global.VideoPath, 0755); err != nil {
|
||||
log.Fatalf("创建视频缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if !global.PathExists(global.CachePath) {
|
||||
if err := os.MkdirAll(global.CachePath, 0755); err != nil {
|
||||
log.Fatalf("创建发送图片缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if global.PathExists("cqhttp.json") {
|
||||
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
|
||||
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.hjson 文件.")
|
||||
@ -95,12 +72,54 @@ func init() {
|
||||
}
|
||||
_ = os.Remove("cqhttp.json")
|
||||
}
|
||||
|
||||
conf = getConfig()
|
||||
if conf == nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logFormatter := &easy.Formatter{
|
||||
TimestampFormat: "2006-01-02 15:04:05",
|
||||
LogFormat: "[%time%] [%lvl%]: %msg% \n",
|
||||
}
|
||||
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotatelogs.WithRotationTime(time.Hour*24))
|
||||
if err != nil {
|
||||
log.Errorf("rotatelogs init err: %v", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 在debug模式下,将在标准输出中打印当前执行行数
|
||||
if conf.Debug {
|
||||
log.SetReportCaller(true)
|
||||
}
|
||||
|
||||
log.AddHook(global.NewLocalHook(w, logFormatter, global.GetLogLevel(conf.LogLevel)...))
|
||||
|
||||
if !global.PathExists(global.ImagePath) {
|
||||
if err := os.MkdirAll(global.ImagePath, 0755); err != nil {
|
||||
log.Fatalf("创建图片缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if !global.PathExists(global.VoicePath) {
|
||||
if err := os.MkdirAll(global.VoicePath, 0755); err != nil {
|
||||
log.Fatalf("创建语音缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if !global.PathExists(global.VideoPath) {
|
||||
if err := os.MkdirAll(global.VideoPath, 0755); err != nil {
|
||||
log.Fatalf("创建视频缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
if !global.PathExists(global.CachePath) {
|
||||
if err := os.MkdirAll(global.CachePath, 0755); err != nil {
|
||||
log.Fatalf("创建发送图片缓存文件夹失败: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
var byteKey []byte
|
||||
var isFastStart = false
|
||||
arg := os.Args
|
||||
if len(arg) > 1 {
|
||||
for i := range arg {
|
||||
@ -122,93 +141,14 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
var conf *global.JSONConfig
|
||||
if global.PathExists("config.json") {
|
||||
conf = global.Load("config.json")
|
||||
_ = conf.Save("config.hjson")
|
||||
_ = os.Remove("config.json")
|
||||
} else if os.Getenv("UIN") != "" {
|
||||
log.Infof("将从环境变量加载配置.")
|
||||
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
|
||||
pwd := os.Getenv("PASS")
|
||||
post := os.Getenv("HTTP_POST")
|
||||
conf = &global.JSONConfig{
|
||||
Uin: uin,
|
||||
Password: pwd,
|
||||
HTTPConfig: &global.GoCQHTTPConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 5700,
|
||||
PostUrls: map[string]string{},
|
||||
},
|
||||
WSConfig: &global.GoCQWebSocketConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 6700,
|
||||
},
|
||||
PostMessageFormat: "string",
|
||||
Debug: os.Getenv("DEBUG") == "true",
|
||||
}
|
||||
if post != "" {
|
||||
conf.HTTPConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
|
||||
}
|
||||
} else {
|
||||
conf = global.Load("config.hjson")
|
||||
}
|
||||
if conf == nil {
|
||||
err := global.WriteAllText("config.hjson", global.DefaultConfigWithComments)
|
||||
if err != nil {
|
||||
log.Fatalf("创建默认配置文件时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
log.Infof("默认配置文件已生成, 请编辑 config.hjson 后重启程序.")
|
||||
time.Sleep(time.Second * 5)
|
||||
return
|
||||
}
|
||||
if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") {
|
||||
log.Warnf("请修改 config.hjson 以添加账号密码.")
|
||||
if !isFastStart {
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
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 {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
@ -233,15 +173,11 @@ func main() {
|
||||
}
|
||||
if conf.EncryptPassword && conf.PasswordEncrypted == "" {
|
||||
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
|
||||
byteKey, _ := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
key := md5.Sum(byteKey)
|
||||
if encrypted := EncryptPwd(conf.Password, key[:]); encrypted != "" {
|
||||
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
|
||||
global.PasswordHash = md5.Sum([]byte(conf.Password))
|
||||
conf.Password = ""
|
||||
conf.PasswordEncrypted = encrypted
|
||||
conf.PasswordEncrypted = "AES:" + PasswordHashEncrypt(global.PasswordHash[:], byteKey)
|
||||
_ = conf.Save("config.hjson")
|
||||
} else {
|
||||
log.Warnf("加密时出现问题.")
|
||||
}
|
||||
}
|
||||
if conf.PasswordEncrypted != "" {
|
||||
if len(byteKey) == 0 {
|
||||
@ -262,8 +198,25 @@ func main() {
|
||||
} else {
|
||||
log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.")
|
||||
}
|
||||
key := md5.Sum(byteKey)
|
||||
conf.Password = DecryptPwd(conf.PasswordEncrypted, key[:])
|
||||
|
||||
// 升级客户端密码加密方案,MD5+TEA 加密密码 -> PBKDF2+AES 加密 MD5
|
||||
// 升级后的 PasswordEncrypted 字符串以"AES:"开始,其后为 Hex 编码的16字节加密 MD5
|
||||
if !strings.HasPrefix(conf.PasswordEncrypted, "AES:") {
|
||||
password := OldPasswordDecrypt(conf.PasswordEncrypted, byteKey)
|
||||
passwordHash := md5.Sum([]byte(password))
|
||||
newPasswordHash := PasswordHashEncrypt(passwordHash[:], byteKey)
|
||||
conf.PasswordEncrypted = "AES:" + newPasswordHash
|
||||
_ = conf.Save("config.hjson")
|
||||
log.Debug("密码加密方案升级完成")
|
||||
}
|
||||
|
||||
ph, err := PasswordHashDecrypt(conf.PasswordEncrypted[4:], byteKey)
|
||||
if err != nil {
|
||||
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
|
||||
}
|
||||
copy(global.PasswordHash[:], ph)
|
||||
} else {
|
||||
global.PasswordHash = md5.Sum([]byte(conf.Password))
|
||||
}
|
||||
if !isFastStart {
|
||||
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
|
||||
@ -283,7 +236,7 @@ func main() {
|
||||
}
|
||||
return "未知"
|
||||
}())
|
||||
cli := client.NewClient(conf.Uin, conf.Password)
|
||||
cli := client.NewClientMd5(conf.Uin, global.PasswordHash)
|
||||
cli.OnLog(func(c *client.QQClient, e *client.LogEvent) {
|
||||
switch e.Type {
|
||||
case "INFO":
|
||||
@ -340,27 +293,50 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
//EncryptPwd 通过给定key加密给定pwd
|
||||
func EncryptPwd(pwd string, key []byte) string {
|
||||
tea := binary.NewTeaCipher(key)
|
||||
if tea == nil {
|
||||
return ""
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(tea.Encrypt([]byte(pwd)))
|
||||
// PasswordHashEncrypt 使用key加密给定passwordHash
|
||||
func PasswordHashEncrypt(passwordHash []byte, key []byte) string {
|
||||
if len(passwordHash) != 16 {
|
||||
panic("密码加密参数错误")
|
||||
}
|
||||
|
||||
//DecryptPwd 通过给定key解密给定ePwd
|
||||
func DecryptPwd(ePwd string, key []byte) string {
|
||||
key = pbkdf2.Key(key, key, 114514, 32, sha1.New)
|
||||
|
||||
cipher, _ := aes.NewCipher(key)
|
||||
result := make([]byte, 16)
|
||||
cipher.Encrypt(result, passwordHash)
|
||||
|
||||
return hex.EncodeToString(result)
|
||||
}
|
||||
|
||||
// PasswordHashDecrypt 使用key解密给定passwordHash
|
||||
func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, error) {
|
||||
ciphertext, err := hex.DecodeString(encryptedPasswordHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
key = pbkdf2.Key(key, key, 114514, 32, sha1.New)
|
||||
|
||||
cipher, _ := aes.NewCipher(key)
|
||||
result := make([]byte, 16)
|
||||
cipher.Decrypt(result, ciphertext)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// OldPasswordDecrypt 使用key解密老password,仅供兼容使用
|
||||
func OldPasswordDecrypt(encryptedPassword string, key []byte) string {
|
||||
defer func() {
|
||||
if pan := recover(); pan != nil {
|
||||
log.Fatalf("密码解密失败: %v", pan)
|
||||
}
|
||||
}()
|
||||
encrypted, err := base64.StdEncoding.DecodeString(ePwd)
|
||||
encKey := md5.Sum(key)
|
||||
encrypted, err := base64.StdEncoding.DecodeString(encryptedPassword)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
tea := binary.NewTeaCipher(key)
|
||||
tea := binary.NewTeaCipher(encKey[:])
|
||||
if tea == nil {
|
||||
panic("密钥错误")
|
||||
}
|
||||
@ -491,3 +467,52 @@ func restart(Args []string) {
|
||||
}
|
||||
_ = cmd.Start()
|
||||
}
|
||||
|
||||
func getConfig() *global.JSONConfig {
|
||||
var conf *global.JSONConfig
|
||||
if global.PathExists("config.json") {
|
||||
conf = global.LoadConfig("config.json")
|
||||
_ = conf.Save("config.hjson")
|
||||
_ = os.Remove("config.json")
|
||||
} else if os.Getenv("UIN") != "" {
|
||||
log.Infof("将从环境变量加载配置.")
|
||||
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
|
||||
pwd := os.Getenv("PASS")
|
||||
post := os.Getenv("HTTP_POST")
|
||||
conf = &global.JSONConfig{
|
||||
Uin: uin,
|
||||
Password: pwd,
|
||||
HTTPConfig: &global.GoCQHTTPConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 5700,
|
||||
PostUrls: map[string]string{},
|
||||
},
|
||||
WSConfig: &global.GoCQWebSocketConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 6700,
|
||||
},
|
||||
PostMessageFormat: "string",
|
||||
Debug: os.Getenv("DEBUG") == "true",
|
||||
}
|
||||
if post != "" {
|
||||
conf.HTTPConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
|
||||
}
|
||||
} else {
|
||||
conf = global.LoadConfig("config.hjson")
|
||||
}
|
||||
if conf == nil {
|
||||
err := global.WriteAllText("config.hjson", global.DefaultConfigWithComments)
|
||||
if err != nil {
|
||||
log.Fatalf("创建默认配置文件时出现错误: %v", err)
|
||||
return nil
|
||||
}
|
||||
log.Infof("默认配置文件已生成, 请编辑 config.hjson 后重启程序.")
|
||||
if !isFastStart {
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return conf
|
||||
}
|
||||
|
@ -30,12 +30,16 @@ import (
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
// WebInput 网页输入channel
|
||||
var WebInput = make(chan string, 1) //长度1,用于阻塞
|
||||
|
||||
// Console 控制台channel
|
||||
var Console = make(chan os.Signal, 1)
|
||||
|
||||
// Restart 重启信号监听channel
|
||||
var Restart = make(chan struct{}, 1)
|
||||
|
||||
// JSONConfig go-cqhttp配置
|
||||
var JSONConfig *global.JSONConfig
|
||||
|
||||
type webServer struct {
|
||||
@ -46,23 +50,25 @@ type webServer struct {
|
||||
Console *bufio.Reader
|
||||
}
|
||||
|
||||
// WebServer Admin子站的Server
|
||||
var WebServer = &webServer{}
|
||||
|
||||
// admin 子站的 路由映射
|
||||
var HttpuriAdmin = map[string]func(s *webServer, c *gin.Context){
|
||||
// APIAdminRoutingTable Admin子站的路由映射
|
||||
var APIAdminRoutingTable = map[string]func(s *webServer, c *gin.Context){
|
||||
"do_restart": AdminDoRestart, //热重启
|
||||
"do_process_restart": AdminProcessRestart, //进程重启
|
||||
"get_web_write": AdminWebWrite, //获取是否验证码输入
|
||||
"do_web_write": AdminDoWebWrite, //web上进行输入操作
|
||||
"do_restart_docker": AdminDoRestartDocker, //直接停止(依赖supervisord/docker)重新拉起
|
||||
"do_config_base": AdminDoConfigBase, //修改config.json中的基础部分
|
||||
"do_config_http": AdminDoConfigHttp, //修改config.json的http部分
|
||||
"do_config_ws": AdminDoConfigWs, //修改config.json的正向ws部分
|
||||
"do_config_reverse": AdminDoConfigReverse, //修改config.json 中的反向ws部分
|
||||
"do_config_json": AdminDoConfigJson, //直接修改 config.json配置
|
||||
"get_config_json": AdminGetConfigJson, //拉取 当前的config.json配置
|
||||
"do_config_http": AdminDoConfigHTTP, //修改config.json的http部分
|
||||
"do_config_ws": AdminDoConfigWS, //修改config.json的正向ws部分
|
||||
"do_config_reverse": AdminDoConfigReverseWS, //修改config.json 中的反向ws部分
|
||||
"do_config_json": AdminDoConfigJSON, //直接修改 config.json配置
|
||||
"get_config_json": AdminGetConfigJSON, //拉取 当前的config.json配置
|
||||
}
|
||||
|
||||
// Failed 构建失败返回MSG
|
||||
func Failed(code int, msg string) coolq.MSG {
|
||||
return coolq.MSG{"data": nil, "retcode": code, "status": "failed", "msg": msg}
|
||||
}
|
||||
@ -111,23 +117,40 @@ func (s *webServer) Run(addr string, cli *client.QQClient) *coolq.CQBot {
|
||||
return b
|
||||
}
|
||||
|
||||
func (s *webServer) Dologin() {
|
||||
// logincore 登录核心实现
|
||||
func (s *webServer) logincore(relogin bool) {
|
||||
|
||||
s.Console = bufio.NewReader(os.Stdin)
|
||||
readLine := func() (str string) {
|
||||
str, _ = s.Console.ReadString('\n')
|
||||
str = strings.TrimSpace(str)
|
||||
return
|
||||
}
|
||||
conf := GetConf()
|
||||
cli := s.Cli
|
||||
cli.AllowSlider = true
|
||||
rsp, err := cli.Login()
|
||||
count := 0
|
||||
for {
|
||||
global.Check(err)
|
||||
|
||||
if s.Cli.Online {
|
||||
log.Warn("Bot已登录")
|
||||
return
|
||||
}
|
||||
|
||||
var times uint = 1 // 重试次数
|
||||
for res, err := s.Cli.Login(); ; res, err = s.Cli.Login() {
|
||||
|
||||
var text string
|
||||
if !rsp.Success {
|
||||
switch rsp.Error {
|
||||
count := 0
|
||||
|
||||
if res == nil {
|
||||
goto Relogin
|
||||
}
|
||||
|
||||
Again: // 不执行 s.Cli.Login() 的循环,适用输入验证码等更新 res 的操作
|
||||
if err == nil && res.Success { // 登录成功
|
||||
break
|
||||
} else if err == client.ErrAlreadyOnline {
|
||||
break
|
||||
}
|
||||
log.Error("登录遇到错误: " + err.Error())
|
||||
|
||||
switch res.Error {
|
||||
case client.SliderNeededError:
|
||||
log.Warnf("登录需要滑条验证码, 请选择解决方案: ")
|
||||
log.Warnf("1. 自行抓包. (推荐)")
|
||||
@ -137,207 +160,187 @@ func (s *webServer) Dologin() {
|
||||
log.Warn("请输入(1 - 3): ")
|
||||
text = readLine()
|
||||
if strings.Contains(text, "1") {
|
||||
log.Warnf("请用浏览器打开 -> %v <- 并获取Ticket.", rsp.VerifyUrl)
|
||||
log.Warnf("请用浏览器打开 -> %v <- 并获取Ticket.", res.VerifyUrl)
|
||||
log.Warn("请输入Ticket: (Enter 提交)")
|
||||
text = readLine()
|
||||
rsp, err = cli.SubmitTicket(strings.TrimSpace(text))
|
||||
continue
|
||||
res, err = s.Cli.SubmitTicket(strings.TrimSpace(text))
|
||||
goto Again
|
||||
}
|
||||
if strings.Contains(text, "3") {
|
||||
cli.AllowSlider = false
|
||||
cli.Disconnect()
|
||||
rsp, err = cli.Login()
|
||||
s.Cli.AllowSlider = false
|
||||
s.Cli.Disconnect()
|
||||
continue
|
||||
}
|
||||
id := utils.RandomStringRange(6, "0123456789")
|
||||
log.Warnf("滑块ID为 %v 请在30S内处理.", id)
|
||||
ticket, err := global.GetSliderTicket(rsp.VerifyUrl, id)
|
||||
ticket, err := global.GetSliderTicket(res.VerifyUrl, id)
|
||||
if err != nil {
|
||||
log.Warnf("错误: " + err.Error())
|
||||
os.Exit(0)
|
||||
}
|
||||
rsp, err = cli.SubmitTicket(ticket)
|
||||
res, err = s.Cli.SubmitTicket(ticket)
|
||||
if err != nil {
|
||||
log.Warnf("错误: " + err.Error())
|
||||
os.Exit(0)
|
||||
continue // 尝试重新登录
|
||||
}
|
||||
continue
|
||||
goto Again
|
||||
case client.NeedCaptcha:
|
||||
_ = ioutil.WriteFile("captcha.jpg", rsp.CaptchaImage, 0644)
|
||||
img, _, _ := image.Decode(bytes.NewReader(rsp.CaptchaImage))
|
||||
_ = ioutil.WriteFile("captcha.jpg", res.CaptchaImage, 0644)
|
||||
img, _, _ := image.Decode(bytes.NewReader(res.CaptchaImage))
|
||||
fmt.Println(asciiart.New("image", img).Art)
|
||||
if conf.WebUI != nil && conf.WebUI.WebInput {
|
||||
log.Warnf("请输入验证码 (captcha.jpg): (http://%s:%d/admin/do_web_write 输入)", conf.WebUI.Host, conf.WebUI.WebUIPort)
|
||||
if s.Conf.WebUI != nil && s.Conf.WebUI.WebInput {
|
||||
log.Warnf("请输入验证码 (captcha.jpg): (http://%s:%d/admin/do_web_write 输入)", s.Conf.WebUI.Host, s.Conf.WebUI.WebUIPort)
|
||||
text = <-WebInput
|
||||
} else {
|
||||
log.Warn("请输入验证码 (captcha.jpg): (Enter 提交)")
|
||||
text = readLine()
|
||||
}
|
||||
rsp, err = cli.SubmitCaptcha(strings.ReplaceAll(text, "\n", ""), rsp.CaptchaSign)
|
||||
global.DelFile("captcha.jpg")
|
||||
continue
|
||||
res, err = s.Cli.SubmitCaptcha(strings.ReplaceAll(text, "\n", ""), res.CaptchaSign)
|
||||
goto Again
|
||||
case client.SMSNeededError:
|
||||
log.Warnf("账号已开启设备锁, 按下 Enter 向手机 %v 发送短信验证码.", rsp.SMSPhone)
|
||||
log.Warnf("账号已开启设备锁, 按下 Enter 向手机 %v 发送短信验证码.", res.SMSPhone)
|
||||
readLine()
|
||||
if !cli.RequestSMS() {
|
||||
if !s.Cli.RequestSMS() {
|
||||
log.Warnf("发送验证码失败,可能是请求过于频繁.")
|
||||
time.Sleep(time.Second * 5)
|
||||
os.Exit(0)
|
||||
continue
|
||||
}
|
||||
log.Warn("请输入短信验证码: (Enter 提交)")
|
||||
text = readLine()
|
||||
rsp, err = cli.SubmitSMS(strings.ReplaceAll(strings.ReplaceAll(text, "\n", ""), "\r", ""))
|
||||
continue
|
||||
res, err = s.Cli.SubmitSMS(strings.ReplaceAll(strings.ReplaceAll(text, "\n", ""), "\r", ""))
|
||||
goto Again
|
||||
case client.SMSOrVerifyNeededError:
|
||||
log.Warnf("账号已开启设备锁,请选择验证方式:")
|
||||
log.Warnf("1. 向手机 %v 发送短信验证码", rsp.SMSPhone)
|
||||
log.Warnf("1. 向手机 %v 发送短信验证码", res.SMSPhone)
|
||||
log.Warnf("2. 使用手机QQ扫码验证.")
|
||||
log.Warn("请输入(1 - 2): ")
|
||||
text = readLine()
|
||||
if strings.Contains(text, "1") {
|
||||
if !cli.RequestSMS() {
|
||||
if !s.Cli.RequestSMS() {
|
||||
log.Warnf("发送验证码失败,可能是请求过于频繁.")
|
||||
time.Sleep(time.Second * 5)
|
||||
os.Exit(0)
|
||||
}
|
||||
log.Warn("请输入短信验证码: (Enter 提交)")
|
||||
text = readLine()
|
||||
rsp, err = cli.SubmitSMS(strings.ReplaceAll(strings.ReplaceAll(text, "\n", ""), "\r", ""))
|
||||
continue
|
||||
res, err = s.Cli.SubmitSMS(strings.ReplaceAll(strings.ReplaceAll(text, "\n", ""), "\r", ""))
|
||||
goto Again
|
||||
}
|
||||
log.Warnf("请前往 -> %v <- 验证并重启Bot.", rsp.VerifyUrl)
|
||||
log.Warnf("请前往 -> %v <- 验证.", res.VerifyUrl)
|
||||
log.Infof("按 Enter 继续....")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
return
|
||||
continue
|
||||
case client.UnsafeDeviceError:
|
||||
log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证并重启Bot.", rsp.VerifyUrl)
|
||||
if conf.WebUI != nil && conf.WebUI.WebInput {
|
||||
log.Infof(" (http://%s:%d/admin/do_web_write 确认后继续)....", conf.WebUI.Host, conf.WebUI.WebUIPort)
|
||||
log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证.", res.VerifyUrl)
|
||||
if s.Conf.WebUI != nil && s.Conf.WebUI.WebInput {
|
||||
log.Infof(" (http://%s:%d/admin/do_web_write 确认后继续)....", s.Conf.WebUI.Host, s.Conf.WebUI.WebUIPort)
|
||||
text = <-WebInput
|
||||
} else {
|
||||
log.Infof("按 Enter 继续....")
|
||||
readLine()
|
||||
}
|
||||
log.Info(text)
|
||||
os.Exit(0)
|
||||
return
|
||||
continue
|
||||
case client.OtherLoginError, client.UnknownLoginError:
|
||||
msg := rsp.ErrorMessage
|
||||
msg := res.ErrorMessage
|
||||
if strings.Contains(msg, "版本") {
|
||||
msg = "密码错误或账号被冻结"
|
||||
}
|
||||
if strings.Contains(msg, "上网环境") && count < 5 {
|
||||
cli.Disconnect()
|
||||
rsp, err = cli.Login()
|
||||
count++
|
||||
s.Cli.Disconnect()
|
||||
log.Warnf("错误: 当前上网环境异常. 将更换服务器并重试.")
|
||||
count++
|
||||
time.Sleep(time.Second)
|
||||
continue
|
||||
}
|
||||
if strings.Contains(msg, "冻结") {
|
||||
log.Fatalf("账号被冻结, 放弃重连")
|
||||
}
|
||||
log.Warnf("登录失败: %v", msg)
|
||||
log.Infof("按 Enter 继续....")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
Relogin:
|
||||
if relogin {
|
||||
if times > s.Conf.ReLogin.MaxReloginTimes && s.Conf.ReLogin.MaxReloginTimes != 0 {
|
||||
log.Fatal("重连失败: 重连次数达到设置的上限值")
|
||||
s.bot.Release()
|
||||
return
|
||||
}
|
||||
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v", s.Conf.ReLogin.ReLoginDelay, times)
|
||||
times++
|
||||
time.Sleep(time.Second * time.Duration(s.Conf.ReLogin.ReLoginDelay))
|
||||
s.Cli.Disconnect()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
log.Infof("登录成功 欢迎使用: %v", cli.Nickname)
|
||||
time.Sleep(time.Second)
|
||||
if relogin {
|
||||
log.Info("重连成功")
|
||||
}
|
||||
}
|
||||
|
||||
// Dologin 主程序登录
|
||||
func (s *webServer) Dologin() {
|
||||
|
||||
s.Cli.AllowSlider = true
|
||||
s.logincore(false)
|
||||
log.Infof("登录成功 欢迎使用: %v", s.Cli.Nickname)
|
||||
log.Info("开始加载好友列表...")
|
||||
global.Check(cli.ReloadFriendList())
|
||||
log.Infof("共加载 %v 个好友.", len(cli.FriendList))
|
||||
global.Check(s.Cli.ReloadFriendList())
|
||||
log.Infof("共加载 %v 个好友.", len(s.Cli.FriendList))
|
||||
log.Infof("开始加载群列表...")
|
||||
global.Check(cli.ReloadGroupList())
|
||||
log.Infof("共加载 %v 个群.", len(cli.GroupList))
|
||||
s.bot = coolq.NewQQBot(cli, conf)
|
||||
if conf.PostMessageFormat != "string" && conf.PostMessageFormat != "array" {
|
||||
global.Check(s.Cli.ReloadGroupList())
|
||||
log.Infof("共加载 %v 个群.", len(s.Cli.GroupList))
|
||||
s.bot = coolq.NewQQBot(s.Cli, s.Conf)
|
||||
if s.Conf.PostMessageFormat != "string" && s.Conf.PostMessageFormat != "array" {
|
||||
log.Warnf("post_message_format 配置错误, 将自动使用 string")
|
||||
coolq.SetMessageFormat("string")
|
||||
} else {
|
||||
coolq.SetMessageFormat(conf.PostMessageFormat)
|
||||
coolq.SetMessageFormat(s.Conf.PostMessageFormat)
|
||||
}
|
||||
if conf.RateLimit.Enabled {
|
||||
global.InitLimiter(conf.RateLimit.Frequency, conf.RateLimit.BucketSize)
|
||||
if s.Conf.RateLimit.Enabled {
|
||||
global.InitLimiter(s.Conf.RateLimit.Frequency, s.Conf.RateLimit.BucketSize)
|
||||
}
|
||||
log.Info("正在加载事件过滤器.")
|
||||
global.BootFilter()
|
||||
global.InitCodec()
|
||||
coolq.IgnoreInvalidCQCode = conf.IgnoreInvalidCQCode
|
||||
coolq.SplitUrl = conf.FixURL
|
||||
coolq.ForceFragmented = conf.ForceFragmented
|
||||
coolq.IgnoreInvalidCQCode = s.Conf.IgnoreInvalidCQCode
|
||||
coolq.SplitURL = s.Conf.FixURL
|
||||
coolq.ForceFragmented = s.Conf.ForceFragmented
|
||||
log.Info("资源初始化完成, 开始处理信息.")
|
||||
log.Info("アトリは、高性能ですから!")
|
||||
cli.OnDisconnected(func(bot *client.QQClient, e *client.ClientDisconnectedEvent) {
|
||||
if conf.ReLogin.Enabled {
|
||||
conf.ReLogin.Enabled = false
|
||||
defer func() { conf.ReLogin.Enabled = true }()
|
||||
var times uint = 1
|
||||
for {
|
||||
if cli.Online {
|
||||
log.Warn("Bot已登录")
|
||||
|
||||
s.Cli.OnDisconnected(func(q *client.QQClient, e *client.ClientDisconnectedEvent) {
|
||||
if !s.Conf.ReLogin.Enabled {
|
||||
return
|
||||
}
|
||||
if times > conf.ReLogin.MaxReloginTimes && conf.ReLogin.MaxReloginTimes != 0 {
|
||||
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()
|
||||
if err != nil {
|
||||
log.Errorf("重连失败: %v", err)
|
||||
cli.Disconnect()
|
||||
continue
|
||||
}
|
||||
if !rsp.Success {
|
||||
switch rsp.Error {
|
||||
case client.NeedCaptcha:
|
||||
log.Fatalf("重连失败: 需要验证码. (验证码处理正在开发中)")
|
||||
case client.UnsafeDeviceError:
|
||||
log.Fatalf("重连失败: 设备锁")
|
||||
default:
|
||||
log.Errorf("重连失败: %v", rsp.ErrorMessage)
|
||||
if strings.Contains(rsp.ErrorMessage, "冻结") {
|
||||
log.Fatalf("账号被冻结, 放弃重连")
|
||||
}
|
||||
cli.Disconnect()
|
||||
continue
|
||||
}
|
||||
}
|
||||
log.Info("重连成功")
|
||||
return
|
||||
}
|
||||
log.Fatal("重连失败: 重连次数达到设置的上限值")
|
||||
}
|
||||
s.bot.Release()
|
||||
log.Fatalf("Bot已离线:%v", e.Message)
|
||||
log.Warnf("Bot已离线 (%v),尝试重连", e.Message)
|
||||
s.logincore(true)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *webServer) admin(c *gin.Context) {
|
||||
action := c.Param("action")
|
||||
log.Debugf("WebServer接收到cgi调用: %v", action)
|
||||
if f, ok := HttpuriAdmin[action]; ok {
|
||||
if f, ok := APIAdminRoutingTable[action]; ok {
|
||||
f(s, c)
|
||||
} else {
|
||||
c.JSON(200, coolq.Failed(404))
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前配置文件信息
|
||||
// GetConf 获取当前配置文件信息
|
||||
func GetConf() *global.JSONConfig {
|
||||
if JSONConfig != nil {
|
||||
return JSONConfig
|
||||
}
|
||||
conf := global.Load("config.hjson")
|
||||
conf := global.LoadConfig("config.hjson")
|
||||
return conf
|
||||
}
|
||||
|
||||
// admin 控制器 登录验证
|
||||
// AuthMiddleWare Admin控制器登录验证
|
||||
func AuthMiddleWare() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
conf := GetConf()
|
||||
@ -431,12 +434,13 @@ func (s *webServer) DoReLogin() { // TODO: 协议层的 ReLogin
|
||||
s.Dologin()
|
||||
// 关闭之前的 server
|
||||
if OldConf.HTTPConfig != nil && OldConf.HTTPConfig.Enabled {
|
||||
HttpServer.ShutDown()
|
||||
cqHTTPServer.ShutDown()
|
||||
}
|
||||
// if OldConf.WSConfig != nil && OldConf.WSConfig.Enabled {
|
||||
// server.WsShutdown()
|
||||
// }
|
||||
// s.UpServer()
|
||||
|
||||
s.ReloadServer()
|
||||
s.Conf = conf
|
||||
}
|
||||
@ -444,9 +448,9 @@ func (s *webServer) DoReLogin() { // TODO: 协议层的 ReLogin
|
||||
func (s *webServer) UpServer() {
|
||||
conf := GetConf()
|
||||
if conf.HTTPConfig != nil && conf.HTTPConfig.Enabled {
|
||||
go HttpServer.Run(fmt.Sprintf("%s:%d", conf.HTTPConfig.Host, conf.HTTPConfig.Port), conf.AccessToken, s.bot)
|
||||
go cqHTTPServer.Run(fmt.Sprintf("%s:%d", conf.HTTPConfig.Host, conf.HTTPConfig.Port), conf.AccessToken, s.bot)
|
||||
for k, v := range conf.HTTPConfig.PostUrls {
|
||||
NewHttpClient().Run(k, v, conf.HTTPConfig.Timeout, s.bot)
|
||||
newHTTPClient().Run(k, v, conf.HTTPConfig.Timeout, s.bot)
|
||||
}
|
||||
}
|
||||
if conf.WSConfig != nil && conf.WSConfig.Enabled {
|
||||
@ -461,9 +465,9 @@ func (s *webServer) UpServer() {
|
||||
func (s *webServer) ReloadServer() {
|
||||
conf := GetConf()
|
||||
if conf.HTTPConfig != nil && conf.HTTPConfig.Enabled {
|
||||
go HttpServer.Run(fmt.Sprintf("%s:%d", conf.HTTPConfig.Host, conf.HTTPConfig.Port), conf.AccessToken, s.bot)
|
||||
go cqHTTPServer.Run(fmt.Sprintf("%s:%d", conf.HTTPConfig.Host, conf.HTTPConfig.Port), conf.AccessToken, s.bot)
|
||||
for k, v := range conf.HTTPConfig.PostUrls {
|
||||
NewHttpClient().Run(k, v, conf.HTTPConfig.Timeout, s.bot)
|
||||
newHTTPClient().Run(k, v, conf.HTTPConfig.Timeout, s.bot)
|
||||
}
|
||||
}
|
||||
for _, rc := range conf.ReverseServers {
|
||||
@ -471,7 +475,7 @@ func (s *webServer) ReloadServer() {
|
||||
}
|
||||
}
|
||||
|
||||
// 热重启
|
||||
// AdminDoRestart 热重启
|
||||
func AdminDoRestart(s *webServer, c *gin.Context) {
|
||||
s.bot.Release()
|
||||
s.bot = nil
|
||||
@ -480,19 +484,19 @@ func AdminDoRestart(s *webServer, c *gin.Context) {
|
||||
c.JSON(200, coolq.OK(coolq.MSG{}))
|
||||
}
|
||||
|
||||
// 进程重启
|
||||
// AdminProcessRestart 进程重启
|
||||
func AdminProcessRestart(s *webServer, c *gin.Context) {
|
||||
Restart <- struct{}{}
|
||||
c.JSON(200, coolq.OK(coolq.MSG{}))
|
||||
}
|
||||
|
||||
// 冷重启
|
||||
// AdminDoRestartDocker 冷重启
|
||||
func AdminDoRestartDocker(s *webServer, c *gin.Context) {
|
||||
Console <- os.Kill
|
||||
c.JSON(200, coolq.OK(coolq.MSG{}))
|
||||
}
|
||||
|
||||
// web输入 html 页面
|
||||
// AdminWebWrite web输入html页面
|
||||
func AdminWebWrite(s *webServer, c *gin.Context) {
|
||||
pic := global.ReadAllText("captcha.jpg")
|
||||
var picbase64 string
|
||||
@ -509,14 +513,14 @@ func AdminWebWrite(s *webServer, c *gin.Context) {
|
||||
}))
|
||||
}
|
||||
|
||||
// web输入 处理
|
||||
// AdminDoWebWrite web输入处理
|
||||
func AdminDoWebWrite(s *webServer, c *gin.Context) {
|
||||
input := c.PostForm("input")
|
||||
WebInput <- input
|
||||
c.JSON(200, coolq.OK(coolq.MSG{}))
|
||||
}
|
||||
|
||||
// 普通配置修改
|
||||
// AdminDoConfigBase 普通配置修改
|
||||
func AdminDoConfigBase(s *webServer, c *gin.Context) {
|
||||
conf := GetConf()
|
||||
conf.Uin, _ = strconv.ParseInt(c.PostForm("uin"), 10, 64)
|
||||
@ -536,8 +540,8 @@ func AdminDoConfigBase(s *webServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// http配置修改
|
||||
func AdminDoConfigHttp(s *webServer, c *gin.Context) {
|
||||
// AdminDoConfigHTTP HTTP配置修改
|
||||
func AdminDoConfigHTTP(s *webServer, c *gin.Context) {
|
||||
conf := GetConf()
|
||||
p, _ := strconv.ParseUint(c.PostForm("port"), 10, 16)
|
||||
conf.HTTPConfig.Port = uint16(p)
|
||||
@ -561,8 +565,8 @@ func AdminDoConfigHttp(s *webServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// ws配置修改
|
||||
func AdminDoConfigWs(s *webServer, c *gin.Context) {
|
||||
// AdminDoConfigWS ws配置修改
|
||||
func AdminDoConfigWS(s *webServer, c *gin.Context) {
|
||||
conf := GetConf()
|
||||
p, _ := strconv.ParseUint(c.PostForm("port"), 10, 16)
|
||||
conf.WSConfig.Port = uint16(p)
|
||||
@ -581,8 +585,8 @@ func AdminDoConfigWs(s *webServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 反向ws配置修改
|
||||
func AdminDoConfigReverse(s *webServer, c *gin.Context) {
|
||||
// AdminDoConfigReverseWS 反向ws配置修改
|
||||
func AdminDoConfigReverseWS(s *webServer, c *gin.Context) {
|
||||
conf := GetConf()
|
||||
conf.ReverseServers[0].ReverseAPIURL = c.PostForm("reverse_api_url")
|
||||
conf.ReverseServers[0].ReverseURL = c.PostForm("reverse_url")
|
||||
@ -603,11 +607,11 @@ func AdminDoConfigReverse(s *webServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// config.json配置修改
|
||||
func AdminDoConfigJson(s *webServer, c *gin.Context) {
|
||||
// AdminDoConfigJSON config.hjson配置修改
|
||||
func AdminDoConfigJSON(s *webServer, c *gin.Context) {
|
||||
conf := GetConf()
|
||||
Json := c.PostForm("json")
|
||||
err := json.Unmarshal([]byte(Json), &conf)
|
||||
JSON := c.PostForm("json")
|
||||
err := json.Unmarshal([]byte(JSON), &conf)
|
||||
if err != nil {
|
||||
log.Warnf("尝试加载配置文件 %v 时出现错误: %v", "config.hjson", err)
|
||||
c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
|
||||
@ -622,8 +626,8 @@ func AdminDoConfigJson(s *webServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 拉取config.json配置
|
||||
func AdminGetConfigJson(s *webServer, c *gin.Context) {
|
||||
// AdminGetConfigJSON 拉取config.hjson配置
|
||||
func AdminGetConfigJSON(s *webServer, c *gin.Context) {
|
||||
conf := GetConf()
|
||||
c.JSON(200, coolq.OK(coolq.MSG{"config": conf}))
|
||||
|
||||
|
2
server/doc.go
Normal file
2
server/doc.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package server 包含Admin子站,HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体
|
||||
package server
|
134
server/http.go
134
server/http.go
@ -24,7 +24,7 @@ import (
|
||||
type httpServer struct {
|
||||
engine *gin.Engine
|
||||
bot *coolq.CQBot
|
||||
Http *http.Server
|
||||
HTTP *http.Server
|
||||
}
|
||||
|
||||
type httpClient struct {
|
||||
@ -34,7 +34,9 @@ type httpClient struct {
|
||||
timeout int32
|
||||
}
|
||||
|
||||
var HttpServer = &httpServer{}
|
||||
var cqHTTPServer = &httpServer{}
|
||||
|
||||
// Debug 是否启用Debug模式
|
||||
var Debug = false
|
||||
|
||||
func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
|
||||
@ -84,11 +86,11 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
|
||||
|
||||
go func() {
|
||||
log.Infof("CQ HTTP 服务器已启动: %v", addr)
|
||||
s.Http = &http.Server{
|
||||
s.HTTP = &http.Server{
|
||||
Addr: addr,
|
||||
Handler: s.engine,
|
||||
}
|
||||
if err := s.Http.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
if err := s.HTTP.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Error(err)
|
||||
log.Infof("HTTP 服务启动失败, 请检查端口是否被占用.")
|
||||
log.Warnf("将在五秒后退出.")
|
||||
@ -98,7 +100,7 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
|
||||
}()
|
||||
}
|
||||
|
||||
func NewHttpClient() *httpClient {
|
||||
func newHTTPClient() *httpClient {
|
||||
return &httpClient{}
|
||||
}
|
||||
|
||||
@ -123,7 +125,7 @@ func (c *httpClient) onBotPushEvent(m coolq.MSG) {
|
||||
}
|
||||
if c.secret != "" {
|
||||
mac := hmac.New(sha1.New, []byte(c.secret))
|
||||
_, err := mac.Write([]byte(m.ToJson()))
|
||||
_, err := mac.Write([]byte(m.ToJSON()))
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return nil
|
||||
@ -141,12 +143,12 @@ func (c *httpClient) onBotPushEvent(m coolq.MSG) {
|
||||
return nil
|
||||
}).Do()
|
||||
if err != nil {
|
||||
log.Warnf("上报Event数据 %v 到 %v 失败: %v", m.ToJson(), c.addr, err)
|
||||
log.Warnf("上报Event数据 %v 到 %v 失败: %v", m.ToJSON(), c.addr, err)
|
||||
return
|
||||
}
|
||||
log.Debugf("上报Event数据 %v 到 %v", m.ToJson(), c.addr)
|
||||
log.Debugf("上报Event数据 %v 到 %v", m.ToJSON(), c.addr)
|
||||
if gjson.Valid(res) {
|
||||
c.bot.CQHandleQuickOperation(gjson.Parse(m.ToJson()), gjson.Parse(res))
|
||||
c.bot.CQHandleQuickOperation(gjson.Parse(m.ToJSON()), gjson.Parse(res))
|
||||
}
|
||||
}
|
||||
|
||||
@ -154,67 +156,86 @@ func (s *httpServer) HandleActions(c *gin.Context) {
|
||||
global.RateLimit(context.Background())
|
||||
action := strings.ReplaceAll(c.Param("action"), "_async", "")
|
||||
log.Debugf("HTTPServer接收到API调用: %v", action)
|
||||
if f, ok := httpApi[action]; ok {
|
||||
if f, ok := httpAPI[action]; ok {
|
||||
f(s, c)
|
||||
} else {
|
||||
c.JSON(200, coolq.Failed(404))
|
||||
}
|
||||
}
|
||||
|
||||
// GetLoginInfo 获取登录号信息
|
||||
func GetLoginInfo(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQGetLoginInfo())
|
||||
}
|
||||
|
||||
// GetFriendList 获取好友列表
|
||||
func GetFriendList(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQGetFriendList())
|
||||
}
|
||||
|
||||
// GetGroupList 获取群列表
|
||||
func GetGroupList(s *httpServer, c *gin.Context) {
|
||||
nc := getParamOrDefault(c, "no_cache", "false")
|
||||
c.JSON(200, s.bot.CQGetGroupList(nc == "true"))
|
||||
}
|
||||
|
||||
// GetGroupInfo 获取群信息
|
||||
func GetGroupInfo(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
nc := getParamOrDefault(c, "no_cache", "false")
|
||||
c.JSON(200, s.bot.CQGetGroupInfo(gid, nc == "true"))
|
||||
}
|
||||
|
||||
// GetGroupMemberList 获取群成员列表
|
||||
func GetGroupMemberList(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
nc := getParamOrDefault(c, "no_cache", "false")
|
||||
c.JSON(200, s.bot.CQGetGroupMemberList(gid, nc == "true"))
|
||||
}
|
||||
|
||||
// GetGroupMemberInfo 获取群成员信息
|
||||
func GetGroupMemberInfo(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetGroupMemberInfo(gid, uid))
|
||||
}
|
||||
|
||||
// GetGroupFileSystemInfo 扩展API-获取群文件系统信息
|
||||
func GetGroupFileSystemInfo(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetGroupFileSystemInfo(gid))
|
||||
}
|
||||
|
||||
// GetGroupRootFiles 扩展API-获取群根目录文件列表
|
||||
func GetGroupRootFiles(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetGroupRootFiles(gid))
|
||||
}
|
||||
|
||||
func GetGroupFilesByFolderId(s *httpServer, c *gin.Context) {
|
||||
// GetGroupFilesByFolderID 扩展API-获取群子目录文件列表
|
||||
func GetGroupFilesByFolderID(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
folderId := getParam(c, "folder_id")
|
||||
c.JSON(200, s.bot.CQGetGroupFilesByFolderId(gid, folderId))
|
||||
folderID := getParam(c, "folder_id")
|
||||
c.JSON(200, s.bot.CQGetGroupFilesByFolderID(gid, folderID))
|
||||
}
|
||||
|
||||
func GetGroupFileUrl(s *httpServer, c *gin.Context) {
|
||||
// GetGroupFileURL 扩展API-获取群文件资源链接
|
||||
func GetGroupFileURL(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
fid := getParam(c, "file_id")
|
||||
busid, _ := strconv.ParseInt(getParam(c, "busid"), 10, 32)
|
||||
c.JSON(200, s.bot.CQGetGroupFileUrl(gid, fid, int32(busid)))
|
||||
c.JSON(200, s.bot.CQGetGroupFileURL(gid, fid, int32(busid)))
|
||||
}
|
||||
|
||||
// UploadGroupFile 扩展API-上传群文件
|
||||
func UploadGroupFile(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQUploadGroupFile(gid, getParam(c, "file"), getParam(c, "name"), getParam(c, "folder")))
|
||||
}
|
||||
|
||||
// SendMessage 发送消息
|
||||
//
|
||||
// https://git.io/JtwTQ
|
||||
func SendMessage(s *httpServer, c *gin.Context) {
|
||||
if getParam(c, "message_type") == "private" {
|
||||
SendPrivateMessage(s, c)
|
||||
@ -233,6 +254,7 @@ func SendMessage(s *httpServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// SendPrivateMessage 发送私聊消息
|
||||
func SendPrivateMessage(s *httpServer, c *gin.Context) {
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
msg, t := getParamWithType(c, "message")
|
||||
@ -244,6 +266,7 @@ func SendPrivateMessage(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQSendPrivateMessage(uid, msg, autoEscape))
|
||||
}
|
||||
|
||||
// SendGroupMessage 发送群消息
|
||||
func SendGroupMessage(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
msg, t := getParamWithType(c, "message")
|
||||
@ -255,33 +278,39 @@ func SendGroupMessage(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQSendGroupMessage(gid, msg, autoEscape))
|
||||
}
|
||||
|
||||
// SendGroupForwardMessage 扩展API-发送合并转发(群)
|
||||
func SendGroupForwardMessage(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
msg := getParam(c, "messages")
|
||||
c.JSON(200, s.bot.CQSendGroupForwardMessage(gid, gjson.Parse(msg)))
|
||||
}
|
||||
|
||||
// GetImage 获取图片(修改自OneBot)
|
||||
func GetImage(s *httpServer, c *gin.Context) {
|
||||
file := getParam(c, "file")
|
||||
c.JSON(200, s.bot.CQGetImage(file))
|
||||
}
|
||||
|
||||
// GetMessage 获取消息
|
||||
func GetMessage(s *httpServer, c *gin.Context) {
|
||||
mid, _ := strconv.ParseInt(getParam(c, "message_id"), 10, 32)
|
||||
c.JSON(200, s.bot.CQGetMessage(int32(mid)))
|
||||
}
|
||||
|
||||
// GetGroupHonorInfo 获取群荣誉信息
|
||||
func GetGroupHonorInfo(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetGroupHonorInfo(gid, getParam(c, "type")))
|
||||
}
|
||||
|
||||
// ProcessFriendRequest 处理加好友请求
|
||||
func ProcessFriendRequest(s *httpServer, c *gin.Context) {
|
||||
flag := getParam(c, "flag")
|
||||
approve := getParamOrDefault(c, "approve", "true")
|
||||
c.JSON(200, s.bot.CQProcessFriendRequest(flag, approve == "true"))
|
||||
}
|
||||
|
||||
// ProcessGroupRequest 处理加群请求/邀请
|
||||
func ProcessGroupRequest(s *httpServer, c *gin.Context) {
|
||||
flag := getParam(c, "flag")
|
||||
subType := getParam(c, "sub_type")
|
||||
@ -292,18 +321,21 @@ func ProcessGroupRequest(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQProcessGroupRequest(flag, subType, getParam(c, "reason"), approve == "true"))
|
||||
}
|
||||
|
||||
// SetGroupCard 设置群名片(群备注)
|
||||
func SetGroupCard(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupCard(gid, uid, getParam(c, "card")))
|
||||
}
|
||||
|
||||
// SetSpecialTitle 设置群组专属头衔
|
||||
func SetSpecialTitle(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupSpecialTitle(gid, uid, getParam(c, "special_title")))
|
||||
}
|
||||
|
||||
// SetGroupKick 群组踢人
|
||||
func SetGroupKick(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
@ -312,6 +344,7 @@ func SetGroupKick(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQSetGroupKick(gid, uid, msg, block == "true"))
|
||||
}
|
||||
|
||||
// SetGroupBan 群组单人禁言
|
||||
func SetGroupBan(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
@ -319,32 +352,40 @@ func SetGroupBan(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQSetGroupBan(gid, uid, uint32(i)))
|
||||
}
|
||||
|
||||
// SetWholeBan 群组全员禁言
|
||||
func SetWholeBan(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupWholeBan(gid, getParamOrDefault(c, "enable", "true") == "true"))
|
||||
}
|
||||
|
||||
// SetGroupName 设置群名
|
||||
func SetGroupName(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupName(gid, getParam(c, "group_name")))
|
||||
}
|
||||
|
||||
// SetGroupAdmin 群组设置管理员
|
||||
func SetGroupAdmin(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupAdmin(gid, uid, getParamOrDefault(c, "enable", "true") == "true"))
|
||||
}
|
||||
|
||||
// SendGroupNotice 扩展API-发送群公告
|
||||
func SendGroupNotice(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupMemo(gid, getParam(c, "content")))
|
||||
}
|
||||
|
||||
// SetGroupLeave 退出群组
|
||||
func SetGroupLeave(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetGroupLeave(gid))
|
||||
}
|
||||
|
||||
// SetRestart 重启 OneBot 实现
|
||||
//
|
||||
// https://git.io/JtwkJ
|
||||
func SetRestart(s *httpServer, c *gin.Context) {
|
||||
delay, _ := strconv.ParseInt(getParam(c, "delay"), 10, 64)
|
||||
c.JSON(200, coolq.MSG{"data": nil, "retcode": 0, "status": "async"})
|
||||
@ -355,58 +396,70 @@ func SetRestart(s *httpServer, c *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
// GetForwardMessage 获取合并转发消息
|
||||
func GetForwardMessage(s *httpServer, c *gin.Context) {
|
||||
resId := getParam(c, "message_id")
|
||||
if resId == "" {
|
||||
resId = getParam(c, "id")
|
||||
resID := getParam(c, "message_id")
|
||||
if resID == "" {
|
||||
resID = getParam(c, "id")
|
||||
}
|
||||
c.JSON(200, s.bot.CQGetForwardMessage(resId))
|
||||
c.JSON(200, s.bot.CQGetForwardMessage(resID))
|
||||
}
|
||||
|
||||
// GetGroupSystemMessage 扩展API-获取群文件系统消息
|
||||
func GetGroupSystemMessage(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQGetGroupSystemMessages())
|
||||
}
|
||||
|
||||
// DeleteMessage 撤回消息
|
||||
func DeleteMessage(s *httpServer, c *gin.Context) {
|
||||
mid, _ := strconv.ParseInt(getParam(c, "message_id"), 10, 32)
|
||||
c.JSON(200, s.bot.CQDeleteMessage(int32(mid)))
|
||||
}
|
||||
|
||||
// CanSendImage 检查是否可以发送图片(此处永远返回true)
|
||||
func CanSendImage(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQCanSendImage())
|
||||
}
|
||||
|
||||
// CanSendRecord 检查是否可以发送语音(此处永远返回true)
|
||||
func CanSendRecord(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQCanSendRecord())
|
||||
}
|
||||
|
||||
// GetStatus 获取运行状态
|
||||
func GetStatus(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQGetStatus())
|
||||
}
|
||||
|
||||
// GetVersionInfo 获取版本信息
|
||||
func GetVersionInfo(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQGetVersionInfo())
|
||||
}
|
||||
|
||||
// ReloadEventFilter 扩展API-重载事件过滤器
|
||||
func ReloadEventFilter(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQReloadEventFilter())
|
||||
}
|
||||
|
||||
// GetVipInfo 扩展API-获取VIP信息
|
||||
func GetVipInfo(s *httpServer, c *gin.Context) {
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetVipInfo(uid))
|
||||
}
|
||||
|
||||
// GetStrangerInfo 获取陌生人信息
|
||||
func GetStrangerInfo(s *httpServer, c *gin.Context) {
|
||||
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetStrangerInfo(uid))
|
||||
}
|
||||
|
||||
// GetGroupAtAllRemain 扩展API-获取群 @全体成员 剩余次数
|
||||
func GetGroupAtAllRemain(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetAtAllRemain(gid))
|
||||
}
|
||||
|
||||
// SetGroupAnonymousBan 群组匿名用户禁言
|
||||
func SetGroupAnonymousBan(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
d, _ := strconv.ParseInt(getParam(c, "duration"), 10, 64)
|
||||
@ -421,16 +474,19 @@ func SetGroupAnonymousBan(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQSetGroupAnonymousBan(gid, flag, int32(d)))
|
||||
}
|
||||
|
||||
// GetGroupMessageHistory 获取群消息历史记录
|
||||
func GetGroupMessageHistory(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
seq, _ := strconv.ParseInt(getParam(c, "message_seq"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetGroupMessageHistory(gid, seq))
|
||||
}
|
||||
|
||||
// GetOnlineClients 扩展API-获取当前账号在线客户端列表
|
||||
func GetOnlineClients(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQGetOnlineClients(getParamOrDefault(c, "no_cache", "false") == "true"))
|
||||
}
|
||||
|
||||
// HandleQuickOperation 隐藏API-对事件执行快速操作
|
||||
func HandleQuickOperation(s *httpServer, c *gin.Context) {
|
||||
if c.Request.Method != "POST" {
|
||||
c.AbortWithStatus(404)
|
||||
@ -442,6 +498,7 @@ func HandleQuickOperation(s *httpServer, c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// DownloadFile 扩展API-下载文件到缓存目录
|
||||
func DownloadFile(s *httpServer, c *gin.Context) {
|
||||
url := getParam(c, "url")
|
||||
tc, _ := strconv.Atoi(getParam(c, "thread_count"))
|
||||
@ -469,16 +526,19 @@ func DownloadFile(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQDownloadFile(url, headers, tc))
|
||||
}
|
||||
|
||||
// OcrImage 扩展API-图片OCR
|
||||
func OcrImage(s *httpServer, c *gin.Context) {
|
||||
img := getParam(c, "image")
|
||||
c.JSON(200, s.bot.CQOcrImage(img))
|
||||
}
|
||||
|
||||
// GetWordSlices 隐藏API-获取中文分词
|
||||
func GetWordSlices(s *httpServer, c *gin.Context) {
|
||||
content := getParam(c, "content")
|
||||
c.JSON(200, s.bot.CQGetWordSlices(content))
|
||||
}
|
||||
|
||||
// SetGroupPortrait 扩展API-设置群头像
|
||||
func SetGroupPortrait(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
file := getParam(c, "file")
|
||||
@ -486,6 +546,29 @@ func SetGroupPortrait(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQSetGroupPortrait(gid, file, cache))
|
||||
}
|
||||
|
||||
// SetEssenceMsg 扩展API-设置精华消息
|
||||
func SetEssenceMsg(s *httpServer, c *gin.Context) {
|
||||
mid, _ := strconv.ParseInt(getParam(c, "message_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQSetEssenceMessage(int32(mid)))
|
||||
}
|
||||
|
||||
// DeleteEssenceMsg 扩展API-移出精华消息
|
||||
func DeleteEssenceMsg(s *httpServer, c *gin.Context) {
|
||||
mid, _ := strconv.ParseInt(getParam(c, "message_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQDeleteEssenceMessage(int32(mid)))
|
||||
}
|
||||
|
||||
// GetEssenceMsgList 扩展API-获取精华消息列表
|
||||
func GetEssenceMsgList(s *httpServer, c *gin.Context) {
|
||||
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
|
||||
c.JSON(200, s.bot.CQGetEssenceMessageList(gid))
|
||||
}
|
||||
|
||||
// CheckURLSafely 扩展API-检查链接安全性
|
||||
func CheckURLSafely(s *httpServer, c *gin.Context) {
|
||||
c.JSON(200, s.bot.CQCheckURLSafely(getParam(c, "url")))
|
||||
}
|
||||
|
||||
func getParamOrDefault(c *gin.Context, k, def string) string {
|
||||
r := getParam(c, k)
|
||||
if r != "" {
|
||||
@ -534,7 +617,7 @@ func getParamWithType(c *gin.Context, k string) (string, gjson.Type) {
|
||||
return "", gjson.Null
|
||||
}
|
||||
|
||||
var httpApi = map[string]func(s *httpServer, c *gin.Context){
|
||||
var httpAPI = map[string]func(s *httpServer, c *gin.Context){
|
||||
"get_login_info": GetLoginInfo,
|
||||
"get_friend_list": GetFriendList,
|
||||
"get_group_list": GetGroupList,
|
||||
@ -543,13 +626,16 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
|
||||
"get_group_member_info": GetGroupMemberInfo,
|
||||
"get_group_file_system_info": GetGroupFileSystemInfo,
|
||||
"get_group_root_files": GetGroupRootFiles,
|
||||
"get_group_files_by_folder": GetGroupFilesByFolderId,
|
||||
"get_group_file_url": GetGroupFileUrl,
|
||||
"get_group_files_by_folder": GetGroupFilesByFolderID,
|
||||
"get_group_file_url": GetGroupFileURL,
|
||||
"upload_group_file": UploadGroupFile,
|
||||
"get_essence_msg_list": GetEssenceMsgList,
|
||||
"send_msg": SendMessage,
|
||||
"send_group_msg": SendGroupMessage,
|
||||
"send_group_forward_msg": SendGroupForwardMessage,
|
||||
"send_private_msg": SendPrivateMessage,
|
||||
"delete_msg": DeleteMessage,
|
||||
"delete_essence_msg": DeleteEssenceMsg,
|
||||
"set_friend_add_request": ProcessFriendRequest,
|
||||
"set_group_add_request": ProcessGroupRequest,
|
||||
"set_group_card": SetGroupCard,
|
||||
@ -559,6 +645,7 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
|
||||
"set_group_whole_ban": SetWholeBan,
|
||||
"set_group_name": SetGroupName,
|
||||
"set_group_admin": SetGroupAdmin,
|
||||
"set_essence_msg": SetEssenceMsg,
|
||||
"set_restart": SetRestart,
|
||||
"_send_group_notice": SendGroupNotice,
|
||||
"set_group_leave": SetGroupLeave,
|
||||
@ -577,6 +664,7 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
|
||||
"set_group_portrait": SetGroupPortrait,
|
||||
"set_group_anonymous_ban": SetGroupAnonymousBan,
|
||||
"get_group_msg_history": GetGroupMessageHistory,
|
||||
"check_url_safely": CheckURLSafely,
|
||||
"download_file": DownloadFile,
|
||||
".handle_quick_operation": HandleQuickOperation,
|
||||
".ocr_image": OcrImage,
|
||||
@ -589,7 +677,7 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
|
||||
func (s *httpServer) ShutDown() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.Http.Shutdown(ctx); err != nil {
|
||||
if err := s.HTTP.Shutdown(ctx); err != nil {
|
||||
log.Fatal("http Server Shutdown:", err)
|
||||
}
|
||||
<-ctx.Done()
|
||||
|
@ -25,7 +25,7 @@ type webSocketServer struct {
|
||||
handshake string
|
||||
}
|
||||
|
||||
//WebSocketClient Websocket客户端实例
|
||||
// WebSocketClient WebSocket客户端实例
|
||||
type WebSocketClient struct {
|
||||
conf *global.GoCQReverseWebSocketConfig
|
||||
token string
|
||||
@ -58,7 +58,7 @@ func (s *webSocketServer) Run(addr, authToken string, b *coolq.CQBot) {
|
||||
http.HandleFunc("/api", s.api)
|
||||
http.HandleFunc("/", s.any)
|
||||
go func() {
|
||||
log.Infof("CQ Websocket 服务器已启动: %v", addr)
|
||||
log.Infof("CQ WebSocket 服务器已启动: %v", addr)
|
||||
log.Fatal(http.ListenAndServe(addr, nil))
|
||||
}()
|
||||
}
|
||||
@ -87,7 +87,7 @@ func (c *WebSocketClient) Run() {
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) connectAPI() {
|
||||
log.Infof("开始尝试连接到反向Websocket API服务器: %v", c.conf.ReverseAPIURL)
|
||||
log.Infof("开始尝试连接到反向WebSocket API服务器: %v", c.conf.ReverseAPIURL)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"API"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
@ -98,20 +98,20 @@ func (c *WebSocketClient) connectAPI() {
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.ReverseAPIURL, header)
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向Websocket API服务器 %v 时出现错误: %v", c.conf.ReverseAPIURL, err)
|
||||
log.Warnf("连接到反向WebSocket API服务器 %v 时出现错误: %v", c.conf.ReverseAPIURL, err)
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
c.connectAPI()
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Infof("已连接到反向Websocket API服务器 %v", c.conf.ReverseAPIURL)
|
||||
log.Infof("已连接到反向WebSocket API服务器 %v", c.conf.ReverseAPIURL)
|
||||
wrappedConn := &webSocketConn{Conn: conn}
|
||||
go c.listenAPI(wrappedConn, false)
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) connectEvent() {
|
||||
log.Infof("开始尝试连接到反向Websocket Event服务器: %v", c.conf.ReverseEventURL)
|
||||
log.Infof("开始尝试连接到反向WebSocket Event服务器: %v", c.conf.ReverseEventURL)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"Event"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
@ -122,7 +122,7 @@ func (c *WebSocketClient) connectEvent() {
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.ReverseEventURL, header)
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向Websocket Event服务器 %v 时出现错误: %v", c.conf.ReverseEventURL, err)
|
||||
log.Warnf("连接到反向WebSocket Event服务器 %v 时出现错误: %v", c.conf.ReverseEventURL, err)
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
c.connectEvent()
|
||||
@ -134,15 +134,15 @@ func (c *WebSocketClient) connectEvent() {
|
||||
c.bot.Client.Uin, time.Now().Unix())
|
||||
err = conn.WriteMessage(websocket.TextMessage, []byte(handshake))
|
||||
if err != nil {
|
||||
log.Warnf("反向Websocket 握手时出现错误: %v", err)
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
|
||||
log.Infof("已连接到反向Websocket Event服务器 %v", c.conf.ReverseEventURL)
|
||||
log.Infof("已连接到反向WebSocket Event服务器 %v", c.conf.ReverseEventURL)
|
||||
c.eventConn = &webSocketConn{Conn: conn}
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) connectUniversal() {
|
||||
log.Infof("开始尝试连接到反向Websocket Universal服务器: %v", c.conf.ReverseURL)
|
||||
log.Infof("开始尝试连接到反向WebSocket Universal服务器: %v", c.conf.ReverseURL)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"Universal"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
@ -153,7 +153,7 @@ func (c *WebSocketClient) connectUniversal() {
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.ReverseURL, header)
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向Websocket Universal服务器 %v 时出现错误: %v", c.conf.ReverseURL, err)
|
||||
log.Warnf("连接到反向WebSocket Universal服务器 %v 时出现错误: %v", c.conf.ReverseURL, err)
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
c.connectUniversal()
|
||||
@ -165,7 +165,7 @@ func (c *WebSocketClient) connectUniversal() {
|
||||
c.bot.Client.Uin, time.Now().Unix())
|
||||
err = conn.WriteMessage(websocket.TextMessage, []byte(handshake))
|
||||
if err != nil {
|
||||
log.Warnf("反向Websocket 握手时出现错误: %v", err)
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
|
||||
wrappedConn := &webSocketConn{Conn: conn}
|
||||
@ -195,7 +195,7 @@ func (c *WebSocketClient) listenAPI(conn *webSocketConn, u bool) {
|
||||
|
||||
func (c *WebSocketClient) onBotPushEvent(m coolq.MSG) {
|
||||
if c.eventConn != nil {
|
||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.eventConn.RemoteAddr().String(), m.ToJson())
|
||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.eventConn.RemoteAddr().String(), m.ToJSON())
|
||||
conn := c.eventConn
|
||||
conn.Lock()
|
||||
defer conn.Unlock()
|
||||
@ -210,7 +210,7 @@ func (c *WebSocketClient) onBotPushEvent(m coolq.MSG) {
|
||||
}
|
||||
}
|
||||
if c.universalConn != nil {
|
||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.universalConn.RemoteAddr().String(), m.ToJson())
|
||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.universalConn.RemoteAddr().String(), m.ToJSON())
|
||||
conn := c.universalConn
|
||||
conn.Lock()
|
||||
defer conn.Unlock()
|
||||
@ -230,7 +230,7 @@ func (s *webSocketServer) event(w http.ResponseWriter, r *http.Request) {
|
||||
if s.token != "" {
|
||||
if auth := r.URL.Query().Get("access_token"); auth != s.token {
|
||||
if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) != 2 || auth[1] != s.token {
|
||||
log.Warnf("已拒绝 %v 的 Websocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
log.Warnf("已拒绝 %v 的 WebSocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
@ -238,17 +238,17 @@ func (s *webSocketServer) event(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Warnf("处理 Websocket 请求时出现错误: %v", err)
|
||||
log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
|
||||
if err != nil {
|
||||
log.Warnf("Websocket 握手时出现错误: %v", err)
|
||||
log.Warnf("WebSocket 握手时出现错误: %v", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("接受 Websocket 连接: %v (/event)", r.RemoteAddr)
|
||||
log.Infof("接受 WebSocket 连接: %v (/event)", r.RemoteAddr)
|
||||
|
||||
conn := &webSocketConn{Conn: c}
|
||||
|
||||
@ -261,7 +261,7 @@ func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
|
||||
if s.token != "" {
|
||||
if auth := r.URL.Query().Get("access_token"); auth != s.token {
|
||||
if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) != 2 || auth[1] != s.token {
|
||||
log.Warnf("已拒绝 %v 的 Websocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
log.Warnf("已拒绝 %v 的 WebSocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
@ -269,10 +269,10 @@ func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Warnf("处理 Websocket 请求时出现错误: %v", err)
|
||||
log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
log.Infof("接受 Websocket 连接: %v (/api)", r.RemoteAddr)
|
||||
log.Infof("接受 WebSocket 连接: %v (/api)", r.RemoteAddr)
|
||||
conn := &webSocketConn{Conn: c}
|
||||
go s.listenAPI(conn)
|
||||
}
|
||||
@ -281,7 +281,7 @@ func (s *webSocketServer) any(w http.ResponseWriter, r *http.Request) {
|
||||
if s.token != "" {
|
||||
if auth := r.URL.Query().Get("access_token"); auth != s.token {
|
||||
if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) != 2 || auth[1] != s.token {
|
||||
log.Warnf("已拒绝 %v 的 Websocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
log.Warnf("已拒绝 %v 的 WebSocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
@ -289,16 +289,16 @@ func (s *webSocketServer) any(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Warnf("处理 Websocket 请求时出现错误: %v", err)
|
||||
log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
|
||||
if err != nil {
|
||||
log.Warnf("Websocket 握手时出现错误: %v", err)
|
||||
log.Warnf("WebSocket 握手时出现错误: %v", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
log.Infof("接受 Websocket 连接: %v (/)", r.RemoteAddr)
|
||||
log.Infof("接受 WebSocket 连接: %v (/)", r.RemoteAddr)
|
||||
conn := &webSocketConn{Conn: c}
|
||||
s.eventConn = append(s.eventConn, conn)
|
||||
s.listenAPI(conn)
|
||||
@ -353,9 +353,9 @@ func (s *webSocketServer) onBotPushEvent(m coolq.MSG) {
|
||||
defer s.eventConnMutex.Unlock()
|
||||
for i, l := 0, len(s.eventConn); i < l; 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()
|
||||
next := i + 1
|
||||
if next >= l {
|
||||
@ -557,10 +557,13 @@ var wsAPI = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
|
||||
return bot.CQGetGroupRootFiles(p.Get("group_id").Int())
|
||||
},
|
||||
"get_group_files_by_folder": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQGetGroupFilesByFolderId(p.Get("group_id").Int(), p.Get("folder_id").Str)
|
||||
return bot.CQGetGroupFilesByFolderID(p.Get("group_id").Int(), p.Get("folder_id").Str)
|
||||
},
|
||||
"get_group_file_url": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQGetGroupFileUrl(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("busid").Int()))
|
||||
return bot.CQGetGroupFileURL(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("busid").Int()))
|
||||
},
|
||||
"upload_group_file": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQUploadGroupFile(p.Get("group_id").Int(), p.Get("file").Str, p.Get("name").Str, p.Get("folder").Str)
|
||||
},
|
||||
"get_group_msg_history": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQGetGroupMessageHistory(p.Get("group_id").Int(), p.Get("message_seq").Int())
|
||||
@ -589,6 +592,18 @@ var wsAPI = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
|
||||
"set_group_portrait": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQSetGroupPortrait(p.Get("group_id").Int(), p.Get("file").String(), p.Get("cache").String())
|
||||
},
|
||||
"set_essence_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQSetEssenceMessage(int32(p.Get("message_id").Int()))
|
||||
},
|
||||
"delete_essence_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQDeleteEssenceMessage(int32(p.Get("message_id").Int()))
|
||||
},
|
||||
"get_essence_msg_list": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQGetEssenceMessageList(p.Get("group_id").Int())
|
||||
},
|
||||
"check_url_safely": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
return bot.CQCheckURLSafely(p.Get("url").String())
|
||||
},
|
||||
"set_group_anonymous_ban": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
|
||||
obj := p.Get("anonymous")
|
||||
flag := p.Get("anonymous_flag")
|
||||
|
Loading…
x
Reference in New Issue
Block a user