1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-06-30 20:03:24 +00:00

Compare commits

...

71 Commits

Author SHA1 Message Date
47cdc20d45 fix: correct x-client-role header 2021-10-13 22:51:51 +08:00
1771cda11c feat(server): unify websocket client connect 2021-10-07 22:24:45 +08:00
67f0ea914d feat(server): use nhooyr.io/websocket 2021-10-07 21:40:20 +08:00
446f624a37 feat(http): accept onebot v12 style endpoint
disabled currently, enabled in v1.1.0
2021-10-06 16:13:40 +08:00
19fd331c46 rf(server): use sync.Once 2021-10-06 15:53:50 +08:00
b8c7941dc8 Merge pull request #1085 from purerosefallen/patch-2
add `ffmpeg` into Dockerfile
2021-10-04 23:44:41 +08:00
ce944539c1 feat: split out server register
we can add server with less dependency
2021-10-02 23:42:47 +08:00
4b99f64b56 style: move help resetWorkingDir to internal/base 2021-10-02 23:14:36 +08:00
1337d3f1f3 style: move internal/config to modules/config
config should not be internal, maybe some module need it.
2021-09-26 19:41:03 +08:00
ddd51e6ca3 style: move global/config to internal/config 2021-09-26 13:32:40 +08:00
35b7b8909e style: make linter happy 2021-09-25 21:13:26 +08:00
cf21e81016 style: move flag parse to internal/base 2021-09-25 21:09:50 +08:00
cd141d7d37 fix: build failed on nosilk platform 2021-09-25 13:28:23 +08:00
1a195278cf add ffmpeg into Dockerfile 2021-09-25 13:25:52 +08:00
5acb01c1a3 refactor: new package modules
move silk, mime to modules
2021-09-25 13:24:33 +08:00
883fca089d style: move global/update to internal/selfupdate
also move checkUpdate to internal/selfupdate
2021-09-25 10:58:54 +08:00
110982651d style: make linter happy 2021-09-25 00:17:36 +08:00
2cf136d031 style: move flag variable into internal/base 2021-09-25 00:12:31 +08:00
f2ed46d6ce style: move coolq.Version into internal/base 2021-09-24 23:28:09 +08:00
87754111ce fix: make golangci-lint happy 2021-09-23 21:11:20 +08:00
1db219fce0 feat: replace gout with net/http.
This significantly reduces binary size:
old 16.5MB
new 15.5MB
on windows/amd64
2021-09-23 21:03:46 +08:00
5cafaea082 fix: token login error under special cases 2021-09-22 17:01:16 +08:00
60d5f4d386 feat: hide key in command line. (#1076)
* feat: hide key in command line.

* Update go.mod

* Update go.sum

* Update main.go

* Update go.mod

* Update go.sum
2021-09-19 23:14:38 +08:00
efdd6bd16a style: move coolq.MSG to global package 2021-09-17 19:08:05 +08:00
6d19f07eb4 fix: incorrect unsafe usage in upstream lib
Updates #1070
2021-09-17 15:37:09 +08:00
760bb175c7 fix: incorrect del friend argument
Fixes #1070
2021-09-17 14:47:00 +08:00
4da5d9ebfb Merge pull request #1026 from Shigma/patch-3
enhance help
2021-09-16 19:42:59 +08:00
a6f82d85be fix #1058 2021-09-16 19:37:05 +08:00
c62f193005 Merge branch 'dev' of github.com:/Mrs4s/go-cqhttp into dev 2021-09-16 18:27:58 +08:00
f386a9b94e doc: delete_unidirectional_friend 2021-09-16 18:27:42 +08:00
48afb44287 Merge pull request #1050 from wdvxdr1123/avx2
feat: use avx2 base64
2021-09-16 18:24:44 +08:00
75fe0294ac fix: make lint happy 2021-09-16 18:19:49 +08:00
1290a3dd10 fix: unidirectional friend cache missing. 2021-09-16 18:08:45 +08:00
59209068bf feat: delete_unidirectional_friend. 2021-09-16 18:01:24 +08:00
757661bcf7 doc: get_unidirectional_friend_list. 2021-09-16 17:37:43 +08:00
b8bf3f9711 feat: get_unidirectional_friend_list api. 2021-09-16 17:33:38 +08:00
eadd688e5a doc: fix typo. 2021-09-16 17:22:04 +08:00
8c89d3c432 doc: image subtype. 2021-09-16 17:21:09 +08:00
cfaa18b131 fix: relogin error. 2021-09-16 17:11:38 +08:00
c975975e30 feat: group image subtype support. 2021-09-16 17:10:12 +08:00
ec4ecb1093 docs: fix newline in MINE 2021-09-16 16:48:17 +08:00
b01ea99d1a docs: MINE scan 2021-09-16 16:43:52 +08:00
8c94c810d6 fix relogin default value error. 2021-09-15 14:34:18 +08:00
7485b51c48 update retry message. 2021-09-15 13:45:04 +08:00
449ae96c8f fix env conf load. 2021-09-15 13:43:39 +08:00
7f26df3ac7 feat: use avx2 base64 2021-09-14 15:12:32 +08:00
bfea93312a fix: panic on setting servers.
Fixes #1039
2021-09-02 19:17:01 +08:00
f8dfa8db2c style: simply send msg. 2021-08-29 22:48:03 +08:00
74fd4bbf35 Merge pull request #1030 from 502647092/patch-1
fix: 修复环境变量初始化错误
2021-08-29 01:49:13 +08:00
16db68e054 Merge pull request #1022 from asjdf/master
update fs.go
2021-08-28 19:46:16 +08:00
346e01c4e9 fix: 修复环境变量初始化错误
Close #1025
2021-08-26 17:08:32 +08:00
a69d52821f Merge pull request #1027 from Yukari316/dev
fix /mark_msg_as_read api param type error
2021-08-25 22:31:48 +08:00
d70c2a0b70 Merge branch 'Mrs4s:dev' into dev 2021-08-25 22:30:06 +08:00
46d0d58865 feat: add nosilk tag.
Updates: #1024
2021-08-25 22:29:10 +08:00
d1ca68ed32 dep: drop jsoniter.
reduce binary size about 1 MB.
2021-08-25 22:25:59 +08:00
c8958b2a42 fix /mark_msg_as_read api param type error 2021-08-25 22:25:49 +08:00
d98ad55826 dep: drop jsoniter.
reduce binary size about 1 MB.
2021-08-25 16:24:35 +08:00
8ac460dde9 Update main.go 2021-08-25 15:17:58 +08:00
520cdd90bb fix #1023. 2021-08-24 09:41:26 +08:00
5fb3233a44 fix /send_group_forward_msg api unable to get params from non-json request. 2021-08-23 15:20:22 +08:00
c61a913c49 update fs.go 2021-08-23 14:02:51 +08:00
24c1192fa6 Merge pull request #1019 from Ink-33/alert
NoMoreDoubleClick
2021-08-22 15:56:28 +08:00
8773e19d2c style: remove useless code 2021-08-22 15:40:06 +08:00
8d6978a60d feat: alert windows user when double click 2021-08-22 15:05:14 +08:00
385443ee2d chore: update dependencies 2021-08-22 02:42:45 +08:00
7f0826b594 feat(server): support long polling timeout. 2021-08-21 12:55:01 +08:00
dc48958292 fix go mod. 2021-08-20 23:04:37 +08:00
e820a2a152 fix #1016. 2021-08-20 22:47:43 +08:00
022eb9fd3b all: bump go1.17 & support windows/arm64. 2021-08-18 14:01:31 +08:00
11a5dbb64a fix(coolq): wrong target on send music share.
Fixes: #1011
2021-08-18 13:25:56 +08:00
78d76f55e2 fix(scf): always flush the writer. 2021-08-16 16:05:33 +08:00
50 changed files with 1811 additions and 1469 deletions

View File

@ -22,15 +22,13 @@ jobs:
goarch: arm goarch: arm
- goos: darwin - goos: darwin
goarch: "386" goarch: "386"
- goos: windows
goarch: arm64
fail-fast: true fail-fast: true
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Setup Go environment - name: Setup Go environment
uses: actions/setup-go@v2.1.3 uses: actions/setup-go@v2.1.3
with: with:
go-version: 1.16 go-version: 1.17
- name: Cache downloaded module - name: Cache downloaded module
uses: actions/cache@v2 uses: actions/cache@v2
with: with:

View File

@ -12,7 +12,7 @@ jobs:
- name: Setup Go environment - name: Setup Go environment
uses: actions/setup-go@v2.1.3 uses: actions/setup-go@v2.1.3
with: with:
go-version: 1.16 go-version: 1.17
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v2 uses: golangci/golangci-lint-action@v2

View File

@ -17,7 +17,7 @@ jobs:
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v2 uses: actions/setup-go@v2
with: with:
go-version: '1.16.2' go-version: '1.17'
- name: Run GoReleaser - name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2 uses: goreleaser/goreleaser-action@v2

View File

@ -27,7 +27,7 @@ builds:
flags: flags:
- -trimpath - -trimpath
ldflags: ldflags:
- -s -w -X github.com/Mrs4s/go-cqhttp/coolq.Version=v{{.Version}} - -s -w -X github.com/Mrs4s/go-cqhttp/internal/base.Version=v{{.Version}}
- id: win - id: win
env: env:
- CGO_ENABLED=0 - CGO_ENABLED=0
@ -38,6 +38,7 @@ builds:
- 386 - 386
- amd64 - amd64
- arm - arm
- arm64
goarm: goarm:
- 7 - 7
mod_timestamp: "{{ .CommitTimestamp }}" mod_timestamp: "{{ .CommitTimestamp }}"

View File

@ -1,4 +1,4 @@
FROM golang:1.16-alpine AS builder FROM golang:1.17-alpine AS builder
RUN go env -w GO111MODULE=auto \ RUN go env -w GO111MODULE=auto \
&& go env -w CGO_ENABLED=0 \ && go env -w CGO_ENABLED=0 \
@ -14,6 +14,8 @@ RUN set -ex \
FROM alpine:latest FROM alpine:latest
RUN apk add --no-cache ffmpeg
COPY --from=builder /build/cqhttp /usr/bin/cqhttp COPY --from=builder /build/cqhttp /usr/bin/cqhttp
RUN chmod +x /usr/bin/cqhttp RUN chmod +x /usr/bin/cqhttp

View File

@ -3,13 +3,13 @@ package coolq
import ( import (
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
"encoding/json"
"fmt" "fmt"
"math" "math"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"runtime" "runtime"
"runtime/debug"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -17,38 +17,28 @@ import (
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/MiraiGo/utils"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/param"
) )
// Version go-cqhttp的版本信息在编译时使用ldflags进行覆盖
var Version = "unknown"
func init() {
if Version != "unknown" {
return
}
info, ok := debug.ReadBuildInfo()
if ok {
Version = info.Main.Version
}
}
// CQGetLoginInfo 获取登录号信息 // CQGetLoginInfo 获取登录号信息
// //
// https://git.io/Jtz1I // https://git.io/Jtz1I
func (bot *CQBot) CQGetLoginInfo() MSG { func (bot *CQBot) CQGetLoginInfo() global.MSG {
return OK(MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname}) return OK(global.MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname})
} }
// CQGetQiDianAccountInfo 获取企点账号信息 // CQGetQiDianAccountInfo 获取企点账号信息
func (bot *CQBot) CQGetQiDianAccountInfo() MSG { func (bot *CQBot) CQGetQiDianAccountInfo() global.MSG {
if bot.Client.QiDian == nil { if bot.Client.QiDian == nil {
return Failed(100, "QIDIAN_PROTOCOL_REQUEST", "请使用企点协议") return Failed(100, "QIDIAN_PROTOCOL_REQUEST", "请使用企点协议")
} }
return OK(MSG{ return OK(global.MSG{
"master_id": bot.Client.QiDian.MasterUin, "master_id": bot.Client.QiDian.MasterUin,
"ext_name": bot.Client.QiDian.ExtName, "ext_name": bot.Client.QiDian.ExtName,
"create_time": bot.Client.QiDian.CreateTime, "create_time": bot.Client.QiDian.CreateTime,
@ -58,10 +48,10 @@ func (bot *CQBot) CQGetQiDianAccountInfo() MSG {
// CQGetFriendList 获取好友列表 // CQGetFriendList 获取好友列表
// //
// https://git.io/Jtz1L // https://git.io/Jtz1L
func (bot *CQBot) CQGetFriendList() MSG { func (bot *CQBot) CQGetFriendList() global.MSG {
fs := make([]MSG, 0, len(bot.Client.FriendList)) fs := make([]global.MSG, 0, len(bot.Client.FriendList))
for _, f := range bot.Client.FriendList { for _, f := range bot.Client.FriendList {
fs = append(fs, MSG{ fs = append(fs, global.MSG{
"nickname": f.Nickname, "nickname": f.Nickname,
"remark": f.Remark, "remark": f.Remark,
"user_id": f.Uin, "user_id": f.Uin,
@ -70,10 +60,51 @@ func (bot *CQBot) CQGetFriendList() MSG {
return OK(fs) return OK(fs)
} }
// CQGetUnidirectionalFriendList 获取单向好友列表
//
//
func (bot *CQBot) CQGetUnidirectionalFriendList() global.MSG {
list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil {
log.Errorf("获取单向好友列表时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
fs := make([]global.MSG, 0, len(list))
for _, f := range list {
fs = append(fs, global.MSG{
"nickname": f.Nickname,
"user_id": f.Uin,
"source": f.Source,
})
}
return OK(fs)
}
// CQDeleteUnidirectionalFriend 删除单向好友
//
//
func (bot *CQBot) CQDeleteUnidirectionalFriend(uin int64) global.MSG {
list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil {
log.Errorf("获取单向好友列表时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
for _, f := range list {
if f.Uin == uin {
if err = bot.Client.DeleteUnidirectionalFriend(uin); err != nil {
log.Errorf("删除单向好友时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(nil)
}
}
return Failed(100, "FRIEND_NOT_FOUND", "好友不存在")
}
// CQDeleteFriend 删除好友 // CQDeleteFriend 删除好友
// //
// //
func (bot *CQBot) CQDeleteFriend(uin int64) MSG { func (bot *CQBot) CQDeleteFriend(uin int64) global.MSG {
if bot.Client.FindFriend(uin) == nil { if bot.Client.FindFriend(uin) == nil {
return Failed(100, "FRIEND_NOT_FOUND", "好友不存在") return Failed(100, "FRIEND_NOT_FOUND", "好友不存在")
} }
@ -87,13 +118,13 @@ func (bot *CQBot) CQDeleteFriend(uin int64) MSG {
// CQGetGroupList 获取群列表 // CQGetGroupList 获取群列表
// //
// https://git.io/Jtz1t // https://git.io/Jtz1t
func (bot *CQBot) CQGetGroupList(noCache bool) MSG { func (bot *CQBot) CQGetGroupList(noCache bool) global.MSG {
gs := make([]MSG, 0, len(bot.Client.GroupList)) gs := make([]global.MSG, 0, len(bot.Client.GroupList))
if noCache { if noCache {
_ = bot.Client.ReloadGroupList() _ = bot.Client.ReloadGroupList()
} }
for _, g := range bot.Client.GroupList { for _, g := range bot.Client.GroupList {
gs = append(gs, MSG{ gs = append(gs, global.MSG{
"group_id": g.Code, "group_id": g.Code,
"group_name": g.Name, "group_name": g.Name,
"group_memo": g.Memo, "group_memo": g.Memo,
@ -109,7 +140,7 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
// CQGetGroupInfo 获取群信息 // CQGetGroupInfo 获取群信息
// //
// https://git.io/Jtz1O // https://git.io/Jtz1O
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil || noCache { if group == nil || noCache {
group, _ = bot.Client.GetGroupInfo(groupID) group, _ = bot.Client.GetGroupInfo(groupID)
@ -122,7 +153,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
} }
for _, g := range info { for _, g := range info {
if g.Code == groupID { if g.Code == groupID {
return OK(MSG{ return OK(global.MSG{
"group_id": g.Code, "group_id": g.Code,
"group_name": g.Name, "group_name": g.Name,
"group_memo": g.Memo, "group_memo": g.Memo,
@ -134,7 +165,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
} }
} }
} else { } else {
return OK(MSG{ return OK(global.MSG{
"group_id": group.Code, "group_id": group.Code,
"group_name": group.Name, "group_name": group.Name,
"group_memo": group.Memo, "group_memo": group.Memo,
@ -150,7 +181,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
// CQGetGroupMemberList 获取群成员列表 // CQGetGroupMemberList 获取群成员列表
// //
// https://git.io/Jtz13 // https://git.io/Jtz13
func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil { if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -163,7 +194,7 @@ func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
} }
group.Members = t group.Members = t
} }
members := make([]MSG, 0, len(group.Members)) members := make([]global.MSG, 0, len(group.Members))
for _, m := range group.Members { for _, m := range group.Members {
members = append(members, convertGroupMemberInfo(groupID, m)) members = append(members, convertGroupMemberInfo(groupID, m))
} }
@ -173,7 +204,7 @@ func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
// CQGetGroupMemberInfo 获取群成员信息 // CQGetGroupMemberInfo 获取群成员信息
// //
// https://git.io/Jtz1s // https://git.io/Jtz1s
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil { if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -198,7 +229,7 @@ func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) MSG
// CQGetGroupFileSystemInfo 扩展API-获取群文件系统信息 // 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 // 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 { func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -210,7 +241,7 @@ func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) MSG {
// CQGetGroupRootFiles 扩展API-获取群根目录文件列表 // 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 // 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 { func (bot *CQBot) CQGetGroupRootFiles(groupID int64) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -221,7 +252,7 @@ func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG {
log.Errorf("获取群 %v 根目录文件失败: %v", groupID, err) log.Errorf("获取群 %v 根目录文件失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error()) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(global.MSG{
"files": files, "files": files,
"folders": folders, "folders": folders,
}) })
@ -230,7 +261,7 @@ func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG {
// CQGetGroupFilesByFolderID 扩展API-获取群子目录文件列表 // 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 // 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 { func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -241,7 +272,7 @@ func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG
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 Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(global.MSG{
"files": files, "files": files,
"folders": folders, "folders": folders,
}) })
@ -250,12 +281,12 @@ func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG
// CQGetGroupFileURL 扩展API-获取群文件资源链接 // 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 // 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 { func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) global.MSG {
url := bot.Client.GetGroupFileUrl(groupID, fileID, busID) url := bot.Client.GetGroupFileUrl(groupID, fileID, busID)
if url == "" { if url == "" {
return Failed(100, "FILE_SYSTEM_API_ERROR") return Failed(100, "FILE_SYSTEM_API_ERROR")
} }
return OK(MSG{ return OK(global.MSG{
"url": url, "url": url,
}) })
} }
@ -263,7 +294,7 @@ func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) M
// CQUploadGroupFile 扩展API-上传群文件 // CQUploadGroupFile 扩展API-上传群文件
// //
// https://docs.go-cqhttp.org/api/#%E4%B8%8A%E4%BC%A0%E7%BE%A4%E6%96%87%E4%BB%B6 // 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 { func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) global.MSG {
if !global.PathExists(file) { if !global.PathExists(file) {
log.Errorf("上传群文件 %v 失败: 文件不存在", file) log.Errorf("上传群文件 %v 失败: 文件不存在", file)
return Failed(100, "FILE_NOT_FOUND", "文件不存在") return Failed(100, "FILE_NOT_FOUND", "文件不存在")
@ -286,7 +317,7 @@ func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) MS
// CQGroupFileCreateFolder 拓展API-创建群文件文件夹 // CQGroupFileCreateFolder 拓展API-创建群文件文件夹
// //
// //
func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string) MSG { func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -302,7 +333,7 @@ func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string)
// CQGroupFileDeleteFolder 拓展API-删除群文件文件夹 // CQGroupFileDeleteFolder 拓展API-删除群文件文件夹
// //
// //
func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) MSG { func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -318,7 +349,7 @@ func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) MSG {
// CQGroupFileDeleteFile 拓展API-删除群文件 // CQGroupFileDeleteFile 拓展API-删除群文件
// //
// //
func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) MSG { func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -334,7 +365,7 @@ func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) M
// CQGetWordSlices 隐藏API-获取中文分词 // 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 // 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 { func (bot *CQBot) CQGetWordSlices(content string) global.MSG {
slices, err := bot.Client.GetWordSegmentation(content) slices, err := bot.Client.GetWordSegmentation(content)
if err != nil { if err != nil {
return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error()) return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error())
@ -342,13 +373,13 @@ func (bot *CQBot) CQGetWordSlices(content string) MSG {
for i := 0; i < len(slices); i++ { for i := 0; i < len(slices); i++ {
slices[i] = strings.ReplaceAll(slices[i], "\u0000", "") slices[i] = strings.ReplaceAll(slices[i], "\u0000", "")
} }
return OK(MSG{"slices": slices}) return OK(global.MSG{"slices": slices})
} }
// CQSendGroupMessage 发送群消息 // CQSendGroupMessage 发送群消息
// //
// https://git.io/Jtz1c // https://git.io/Jtz1c
func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape bool) MSG { func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil { if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -366,40 +397,34 @@ func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape b
} }
} }
var elem []message.IMessageElement
if m.Type == gjson.JSON { if m.Type == gjson.JSON {
elem := bot.ConvertObjectMessage(m, true) elem = bot.ConvertObjectMessage(m, true)
fixAt(elem) } else {
mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
}
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(ToStringMessage(elem, groupID)), mid)
return OK(MSG{"message_id": mid})
}
str := m.String() str := m.String()
if str == "" { if str == "" {
log.Warn("群消息发送失败: 信息为空.") log.Warn("群消息发送失败: 信息为空.")
return Failed(100, "EMPTY_MSG_ERROR", "消息为空") return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
} }
var elem []message.IMessageElement
if autoEscape { if autoEscape {
elem = append(elem, message.NewText(str)) elem = []message.IMessageElement{message.NewText(str)}
} else { } else {
elem = bot.ConvertStringMessage(str, true) elem = bot.ConvertStringMessage(str, true)
} }
}
fixAt(elem) fixAt(elem)
mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem}) mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出") return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
} }
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(str), mid) log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(global.MSG{"message_id": mid})
} }
// CQSendGroupForwardMessage 扩展API-发送合并转发(群) // 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 // 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 { func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) global.MSG {
if m.Type != gjson.JSON { if m.Type != gjson.JSON {
return Failed(100) return Failed(100)
} }
@ -414,7 +439,7 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
return true return true
}) })
var resolveElement = func(elems []message.IMessageElement) []message.IMessageElement { resolveElement := func(elems []message.IMessageElement) []message.IMessageElement {
for i, elem := range elems { for i, elem := range elems {
switch elem.(type) { switch elem.(type) {
case *LocalImageElement, *LocalVideoElement: case *LocalImageElement, *LocalVideoElement:
@ -521,7 +546,7 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
log.Warnf("合并转发(群)消息发送失败: 账号可能被风控.") log.Warnf("合并转发(群)消息发送失败: 账号可能被风控.")
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出") return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
} }
return OK(MSG{ return OK(global.MSG{
"message_id": bot.InsertGroupMessage(ret), "message_id": bot.InsertGroupMessage(ret),
}) })
} }
@ -531,38 +556,33 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
// CQSendPrivateMessage 发送私聊消息 // CQSendPrivateMessage 发送私聊消息
// //
// https://git.io/Jtz1l // https://git.io/Jtz1l
func (bot *CQBot) CQSendPrivateMessage(userID int64, groupID int64, m gjson.Result, autoEscape bool) MSG { func (bot *CQBot) CQSendPrivateMessage(userID int64, groupID int64, m gjson.Result, autoEscape bool) global.MSG {
var elem []message.IMessageElement
if m.Type == gjson.JSON { if m.Type == gjson.JSON {
elem := bot.ConvertObjectMessage(m, false) elem = bot.ConvertObjectMessage(m, false)
} else {
str := m.String()
if str == "" {
return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
}
if autoEscape {
elem = []message.IMessageElement{message.NewText(str)}
} else {
elem = bot.ConvertStringMessage(str, false)
}
}
mid := bot.SendPrivateMessage(userID, groupID, &message.SendingMessage{Elements: elem}) mid := bot.SendPrivateMessage(userID, groupID, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出") return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
} }
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}) return OK(global.MSG{"message_id": mid})
}
str := m.String()
if str == "" {
return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
}
var elem []message.IMessageElement
if autoEscape {
elem = append(elem, message.NewText(str))
} else {
elem = bot.ConvertStringMessage(str, false)
}
mid := bot.SendPrivateMessage(userID, groupID, &message.SendingMessage{Elements: elem})
if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
}
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(str), mid)
return OK(MSG{"message_id": mid})
} }
// CQSetGroupCard 设置群名片(群备注) // CQSetGroupCard 设置群名片(群备注)
// //
// https://git.io/Jtz1B // https://git.io/Jtz1B
func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) MSG { func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
m.EditCard(card) m.EditCard(card)
@ -575,7 +595,7 @@ func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) MSG {
// CQSetGroupSpecialTitle 设置群组专属头衔 // CQSetGroupSpecialTitle 设置群组专属头衔
// //
// https://git.io/Jtz10 // https://git.io/Jtz10
func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) MSG { func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
m.EditSpecialTitle(title) m.EditSpecialTitle(title)
@ -588,7 +608,7 @@ func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) MS
// CQSetGroupName 设置群名 // CQSetGroupName 设置群名
// //
// https://git.io/Jtz12 // https://git.io/Jtz12
func (bot *CQBot) CQSetGroupName(groupID int64, name string) MSG { func (bot *CQBot) CQSetGroupName(groupID int64, name string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
g.UpdateName(name) g.UpdateName(name)
return OK(nil) return OK(nil)
@ -599,7 +619,7 @@ func (bot *CQBot) CQSetGroupName(groupID int64, name string) MSG {
// CQSetGroupMemo 扩展API-发送群公告 // CQSetGroupMemo 扩展API-发送群公告
// //
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%BE%A4%E5%85%AC%E5%91%8A // 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, img string) MSG { func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string, img string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if g.SelfPermission() == client.Member { if g.SelfPermission() == client.Member {
return Failed(100, "PERMISSION_DENIED", "权限不足") return Failed(100, "PERMISSION_DENIED", "权限不足")
@ -627,7 +647,7 @@ func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string, img string) MSG {
// CQSetGroupKick 群组踢人 // CQSetGroupKick 群组踢人
// //
// https://git.io/Jtz1V // https://git.io/Jtz1V
func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool) MSG { func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
err := m.Kick(msg, block) err := m.Kick(msg, block)
@ -643,7 +663,7 @@ func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool)
// CQSetGroupBan 群组单人禁言 // CQSetGroupBan 群组单人禁言
// //
// https://git.io/Jtz1w // https://git.io/Jtz1w
func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) MSG { func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
err := m.Mute(duration) err := m.Mute(duration)
@ -662,7 +682,7 @@ func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) MSG {
// CQSetGroupWholeBan 群组全员禁言 // CQSetGroupWholeBan 群组全员禁言
// //
// https://git.io/Jtz1o // https://git.io/Jtz1o
func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) MSG { func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
g.MuteAll(enable) g.MuteAll(enable)
return OK(nil) return OK(nil)
@ -673,7 +693,7 @@ func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) MSG {
// CQSetGroupLeave 退出群组 // CQSetGroupLeave 退出群组
// //
// https://git.io/Jtz1K // https://git.io/Jtz1K
func (bot *CQBot) CQSetGroupLeave(groupID int64) MSG { func (bot *CQBot) CQSetGroupLeave(groupID int64) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
g.Quit() g.Quit()
return OK(nil) return OK(nil)
@ -684,7 +704,7 @@ func (bot *CQBot) CQSetGroupLeave(groupID int64) MSG {
// CQGetAtAllRemain 扩展API-获取群 @全体成员 剩余次数 // 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 // 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 { func (bot *CQBot) CQGetAtAllRemain(groupID int64) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
i, err := bot.Client.GetAtAllRemain(groupID) i, err := bot.Client.GetAtAllRemain(groupID)
if err != nil { if err != nil {
@ -698,7 +718,7 @@ func (bot *CQBot) CQGetAtAllRemain(groupID int64) MSG {
// CQProcessFriendRequest 处理加好友请求 // CQProcessFriendRequest 处理加好友请求
// //
// https://git.io/Jtz11 // https://git.io/Jtz11
func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG { func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) global.MSG {
req, ok := bot.friendReqCache.Load(flag) req, ok := bot.friendReqCache.Load(flag)
if !ok { if !ok {
return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在") return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
@ -714,7 +734,7 @@ func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
// CQProcessGroupRequest 处理加群请求/邀请 // CQProcessGroupRequest 处理加群请求/邀请
// //
// https://git.io/Jtz1D // https://git.io/Jtz1D
func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) MSG { func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) global.MSG {
msgs, err := bot.Client.GetGroupSystemMessages() msgs, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Errorf("获取群系统消息失败: %v", err) log.Errorf("获取群系统消息失败: %v", err)
@ -758,7 +778,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
// CQDeleteMessage 撤回消息 // CQDeleteMessage 撤回消息
// //
// https:// git.io/Jtz1y // https:// git.io/Jtz1y
func (bot *CQBot) CQDeleteMessage(messageID int32) MSG { func (bot *CQBot) CQDeleteMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg := bot.GetMessage(messageID)
if msg == nil { if msg == nil {
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在") return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
@ -789,7 +809,7 @@ func (bot *CQBot) CQDeleteMessage(messageID int32) MSG {
// CQSetGroupAdmin 群组设置管理员 // CQSetGroupAdmin 群组设置管理员
// //
// https://git.io/Jtz1S // https://git.io/Jtz1S
func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) MSG { func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil || group.OwnerUin != bot.Client.Uin { if group == nil || group.OwnerUin != bot.Client.Uin {
return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足") return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足")
@ -811,12 +831,12 @@ func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) MSG {
// CQGetVipInfo 扩展API-获取VIP信息 // CQGetVipInfo 扩展API-获取VIP信息
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96vip%E4%BF%A1%E6%81%AF // 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 { func (bot *CQBot) CQGetVipInfo(userID int64) global.MSG {
vip, err := bot.Client.GetVipInfo(userID) vip, err := bot.Client.GetVipInfo(userID)
if err != nil { if err != nil {
return Failed(100, "VIP_API_ERROR", err.Error()) return Failed(100, "VIP_API_ERROR", err.Error())
} }
msg := MSG{ msg := global.MSG{
"user_id": vip.Uin, "user_id": vip.Uin,
"nickname": vip.Name, "nickname": vip.Name,
"level": vip.Level, "level": vip.Level,
@ -831,11 +851,11 @@ func (bot *CQBot) CQGetVipInfo(userID int64) MSG {
// CQGetGroupHonorInfo 获取群荣誉信息 // CQGetGroupHonorInfo 获取群荣誉信息
// //
// https://git.io/Jtz1H // https://git.io/Jtz1H
func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG { func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) global.MSG {
msg := MSG{"group_id": groupID} msg := global.MSG{"group_id": groupID}
convertMem := func(memList []client.HonorMemberInfo) (ret []MSG) { convertMem := func(memList []client.HonorMemberInfo) (ret []global.MSG) {
for _, mem := range memList { for _, mem := range memList {
ret = append(ret, MSG{ ret = append(ret, global.MSG{
"user_id": mem.Uin, "user_id": mem.Uin,
"nickname": mem.Name, "nickname": mem.Name,
"avatar": mem.Avatar, "avatar": mem.Avatar,
@ -847,7 +867,7 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG {
if t == "talkative" || t == "all" { 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 { if honor.CurrentTalkative.Uin != 0 {
msg["current_talkative"] = MSG{ msg["current_talkative"] = global.MSG{
"user_id": honor.CurrentTalkative.Uin, "user_id": honor.CurrentTalkative.Uin,
"nickname": honor.CurrentTalkative.Name, "nickname": honor.CurrentTalkative.Name,
"avatar": honor.CurrentTalkative.Avatar, "avatar": honor.CurrentTalkative.Avatar,
@ -888,12 +908,12 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG {
// CQGetStrangerInfo 获取陌生人信息 // CQGetStrangerInfo 获取陌生人信息
// //
// https://git.io/Jtz17 // https://git.io/Jtz17
func (bot *CQBot) CQGetStrangerInfo(userID int64) MSG { func (bot *CQBot) CQGetStrangerInfo(userID int64) global.MSG {
info, err := bot.Client.GetSummaryInfo(userID) info, err := bot.Client.GetSummaryInfo(userID)
if err != nil { if err != nil {
return Failed(100, "SUMMARY_API_ERROR", err.Error()) return Failed(100, "SUMMARY_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(global.MSG{
"user_id": info.Uin, "user_id": info.Uin,
"nickname": info.Nickname, "nickname": info.Nickname,
"qid": info.Qid, "qid": info.Qid,
@ -915,7 +935,7 @@ func (bot *CQBot) CQGetStrangerInfo(userID int64) MSG {
// CQHandleQuickOperation 隐藏API-对事件执行快速操作 // CQHandleQuickOperation 隐藏API-对事件执行快速操作
// //
// https://git.io/Jtz15 // https://git.io/Jtz15
func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG { func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) global.MSG {
postType := context.Get("post_type").Str postType := context.Get("post_type").Str
switch postType { switch postType {
@ -926,20 +946,20 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
reply := operation.Get("reply") reply := operation.Get("reply")
if reply.Exists() { if reply.Exists() {
autoEscape := global.EnsureBool(operation.Get("auto_escape"), false) autoEscape := param.EnsureBool(operation.Get("auto_escape"), false)
at := operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group" at := operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group"
if at && reply.IsArray() { if at && reply.IsArray() {
// 在 reply 数组头部插入CQ码 // 在 reply 数组头部插入CQ码
replySegments := make([]MSG, 0) replySegments := make([]global.MSG, 0)
segments := make([]MSG, 0) segments := make([]global.MSG, 0)
segments = append(segments, MSG{ segments = append(segments, global.MSG{
"type": "at", "type": "at",
"data": MSG{ "data": global.MSG{
"qq": context.Get("sender.user_id").Int(), "qq": context.Get("sender.user_id").Int(),
}, },
}) })
err := json.UnmarshalFromString(reply.Raw, &replySegments) err := json.Unmarshal(utils.S2B(reply.Raw), &replySegments)
if err != nil { if err != nil {
log.WithError(err).Warnf("处理 at_sender 过程中发生错误") log.WithError(err).Warnf("处理 at_sender 过程中发生错误")
return Failed(-1, "处理 at_sender 过程中发生错误", err.Error()) return Failed(-1, "处理 at_sender 过程中发生错误", err.Error())
@ -947,13 +967,13 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
segments = append(segments, replySegments...) segments = append(segments, replySegments...)
modified, err := json.MarshalToString(segments) modified, err := json.Marshal(segments)
if err != nil { if err != nil {
log.WithError(err).Warnf("处理 at_sender 过程中发生错误") log.WithError(err).Warnf("处理 at_sender 过程中发生错误")
return Failed(-1, "处理 at_sender 过程中发生错误", err.Error()) return Failed(-1, "处理 at_sender 过程中发生错误", err.Error())
} }
reply = gjson.Parse(modified) reply = gjson.Parse(utils.B2S(modified))
} else if at && reply.Type == gjson.String { } else if at && reply.Type == gjson.String {
reply = gjson.Parse(fmt.Sprintf( reply = gjson.Parse(fmt.Sprintf(
"\"[CQ:at,qq=%d]%s\"", "\"[CQ:at,qq=%d]%s\"",
@ -991,10 +1011,10 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
reqType := context.Get("request_type").Str reqType := context.Get("request_type").Str
if operation.Get("approve").Exists() { if operation.Get("approve").Exists() {
if reqType == "friend" { if reqType == "friend" {
bot.CQProcessFriendRequest(context.Get("flag").Str, operation.Get("approve").Bool()) bot.CQProcessFriendRequest(context.Get("flag").String(), operation.Get("approve").Bool())
} }
if reqType == "group" { if reqType == "group" {
bot.CQProcessGroupRequest(context.Get("flag").Str, context.Get("sub_type").Str, operation.Get("reason").Str, operation.Get("approve").Bool()) bot.CQProcessGroupRequest(context.Get("flag").String(), context.Get("sub_type").Str, operation.Get("reason").Str, operation.Get("approve").Bool())
} }
} }
} }
@ -1004,7 +1024,7 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
// CQGetImage 获取图片(修改自OneBot) // 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 // 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 { func (bot *CQBot) CQGetImage(file string) global.MSG {
if !global.PathExists(path.Join(global.ImagePath, file)) { if !global.PathExists(path.Join(global.ImagePath, file)) {
return Failed(100) return Failed(100)
} }
@ -1012,7 +1032,7 @@ func (bot *CQBot) CQGetImage(file string) MSG {
if err == nil { if err == nil {
r := binary.NewReader(b) r := binary.NewReader(b)
r.ReadBytes(16) r.ReadBytes(16)
msg := MSG{ msg := global.MSG{
"size": r.ReadInt32(), "size": r.ReadInt32(),
"filename": r.ReadString(), "filename": r.ReadString(),
"url": r.ReadString(), "url": r.ReadString(),
@ -1035,7 +1055,7 @@ func (bot *CQBot) CQGetImage(file string) MSG {
// CQDownloadFile 扩展API-下载文件到缓存目录 // 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 // 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 { func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCount int) global.MSG {
hash := md5.Sum([]byte(url)) hash := md5.Sum([]byte(url))
file := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache") file := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache")
if global.PathExists(file) { if global.PathExists(file) {
@ -1049,7 +1069,7 @@ func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCo
return Failed(100, "DOWNLOAD_FILE_ERROR", err.Error()) return Failed(100, "DOWNLOAD_FILE_ERROR", err.Error())
} }
abs, _ := filepath.Abs(file) abs, _ := filepath.Abs(file)
return OK(MSG{ return OK(global.MSG{
"file": abs, "file": abs,
}) })
} }
@ -1057,16 +1077,16 @@ func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCo
// CQGetForwardMessage 获取合并转发消息 // CQGetForwardMessage 获取合并转发消息
// //
// https://git.io/Jtz1F // https://git.io/Jtz1F
func (bot *CQBot) CQGetForwardMessage(resID string) MSG { func (bot *CQBot) CQGetForwardMessage(resID string) global.MSG {
m := bot.Client.GetForwardMessage(resID) m := bot.Client.GetForwardMessage(resID)
if m == nil { if m == nil {
return Failed(100, "MSG_NOT_FOUND", "消息不存在") return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
r := make([]MSG, 0, len(m.Nodes)) r := make([]global.MSG, 0, len(m.Nodes))
for _, n := range m.Nodes { for _, n := range m.Nodes {
bot.checkMedia(n.Message) bot.checkMedia(n.Message)
r = append(r, MSG{ r = append(r, global.MSG{
"sender": MSG{ "sender": global.MSG{
"user_id": n.SenderId, "user_id": n.SenderId,
"nickname": n.SenderName, "nickname": n.SenderName,
}, },
@ -1074,7 +1094,7 @@ func (bot *CQBot) CQGetForwardMessage(resID string) MSG {
"content": ToFormattedMessage(n.Message, 0, false), "content": ToFormattedMessage(n.Message, 0, false),
}) })
} }
return OK(MSG{ return OK(global.MSG{
"messages": r, "messages": r,
}) })
} }
@ -1082,7 +1102,7 @@ func (bot *CQBot) CQGetForwardMessage(resID string) MSG {
// CQGetMessage 获取消息 // CQGetMessage 获取消息
// //
// https://git.io/Jtz1b // https://git.io/Jtz1b
func (bot *CQBot) CQGetMessage(messageID int32) MSG { func (bot *CQBot) CQGetMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg := bot.GetMessage(messageID)
if msg == nil { if msg == nil {
return Failed(100, "MSG_NOT_FOUND", "消息不存在") return Failed(100, "MSG_NOT_FOUND", "消息不存在")
@ -1090,7 +1110,7 @@ func (bot *CQBot) CQGetMessage(messageID int32) MSG {
sender := msg["sender"].(message.Sender) sender := msg["sender"].(message.Sender)
gid, isGroup := msg["group"] gid, isGroup := msg["group"]
raw := msg["message"].(string) raw := msg["message"].(string)
return OK(MSG{ return OK(global.MSG{
"message_id": messageID, "message_id": messageID,
"real_id": msg["message-id"], "real_id": msg["message-id"],
"message_seq": msg["message-id"], "message_seq": msg["message-id"],
@ -1102,7 +1122,7 @@ func (bot *CQBot) CQGetMessage(messageID int32) MSG {
} }
return "private" return "private"
}(), }(),
"sender": MSG{ "sender": global.MSG{
"user_id": sender.Uin, "user_id": sender.Uin,
"nickname": sender.Nickname, "nickname": sender.Nickname,
}, },
@ -1120,7 +1140,7 @@ func (bot *CQBot) CQGetMessage(messageID int32) MSG {
// CQGetGroupSystemMessages 扩展API-获取群文件系统消息 // 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 // 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 { func (bot *CQBot) CQGetGroupSystemMessages() global.MSG {
msg, err := bot.Client.GetGroupSystemMessages() msg, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Warnf("获取群系统消息失败: %v", err) log.Warnf("获取群系统消息失败: %v", err)
@ -1132,7 +1152,7 @@ func (bot *CQBot) CQGetGroupSystemMessages() MSG {
// CQGetGroupMessageHistory 获取群消息历史记录 // 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 // 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 { func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) global.MSG {
if g := bot.Client.FindGroup(groupID); g == nil { if g := bot.Client.FindGroup(groupID); g == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
@ -1148,7 +1168,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
log.Warnf("获取群历史消息失败: %v", err) log.Warnf("获取群历史消息失败: %v", err)
return Failed(100, "MESSAGES_API_ERROR", err.Error()) return Failed(100, "MESSAGES_API_ERROR", err.Error())
} }
ms := make([]MSG, 0, len(msg)) ms := make([]global.MSG, 0, len(msg))
for _, m := range msg { for _, m := range msg {
id := m.Id id := m.Id
bot.checkMedia(m.Elements) bot.checkMedia(m.Elements)
@ -1159,7 +1179,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
t["message_id"] = id t["message_id"] = id
ms = append(ms, t) ms = append(ms, t)
} }
return OK(MSG{ return OK(global.MSG{
"messages": ms, "messages": ms,
}) })
} }
@ -1167,22 +1187,22 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
// CQGetOnlineClients 扩展API-获取当前账号在线客户端列表 // 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 // 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 { func (bot *CQBot) CQGetOnlineClients(noCache bool) global.MSG {
if noCache { if noCache {
if err := bot.Client.RefreshStatus(); err != nil { if err := bot.Client.RefreshStatus(); err != nil {
log.Warnf("刷新客户端状态时出现问题 %v", err) log.Warnf("刷新客户端状态时出现问题 %v", err)
return Failed(100, "REFRESH_STATUS_ERROR", err.Error()) return Failed(100, "REFRESH_STATUS_ERROR", err.Error())
} }
} }
d := make([]MSG, 0, len(bot.Client.OnlineClients)) d := make([]global.MSG, 0, len(bot.Client.OnlineClients))
for _, oc := range bot.Client.OnlineClients { for _, oc := range bot.Client.OnlineClients {
d = append(d, MSG{ d = append(d, global.MSG{
"app_id": oc.AppId, "app_id": oc.AppId,
"device_name": oc.DeviceName, "device_name": oc.DeviceName,
"device_kind": oc.DeviceKind, "device_kind": oc.DeviceKind,
}) })
} }
return OK(MSG{ return OK(global.MSG{
"clients": d, "clients": d,
}) })
} }
@ -1190,21 +1210,21 @@ func (bot *CQBot) CQGetOnlineClients(noCache bool) MSG {
// CQCanSendImage 检查是否可以发送图片(此处永远返回true) // CQCanSendImage 检查是否可以发送图片(此处永远返回true)
// //
// https://git.io/Jtz1N // https://git.io/Jtz1N
func (bot *CQBot) CQCanSendImage() MSG { func (bot *CQBot) CQCanSendImage() global.MSG {
return OK(MSG{"yes": true}) return OK(global.MSG{"yes": true})
} }
// CQCanSendRecord 检查是否可以发送语音(此处永远返回true) // CQCanSendRecord 检查是否可以发送语音(此处永远返回true)
// //
// https://git.io/Jtz1x // https://git.io/Jtz1x
func (bot *CQBot) CQCanSendRecord() MSG { func (bot *CQBot) CQCanSendRecord() global.MSG {
return OK(MSG{"yes": true}) return OK(global.MSG{"yes": true})
} }
// CQOcrImage 扩展API-图片OCR // CQOcrImage 扩展API-图片OCR
// //
// https://docs.go-cqhttp.org/api/#%E5%9B%BE%E7%89%87-ocr // https://docs.go-cqhttp.org/api/#%E5%9B%BE%E7%89%87-ocr
func (bot *CQBot) CQOcrImage(imageID string) MSG { func (bot *CQBot) CQOcrImage(imageID string) global.MSG {
img, err := bot.makeImageOrVideoElem(map[string]string{"file": imageID}, false, true) img, err := bot.makeImageOrVideoElem(map[string]string{"file": imageID}, false, true)
if err != nil { if err != nil {
log.Warnf("load image error: %v", err) log.Warnf("load image error: %v", err)
@ -1221,7 +1241,7 @@ func (bot *CQBot) CQOcrImage(imageID string) MSG {
// CQSetGroupPortrait 扩展API-设置群头像 // CQSetGroupPortrait 扩展API-设置群头像
// //
// https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F // 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 { func (bot *CQBot) CQSetGroupPortrait(groupID int64, file, cache string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
img, err := global.FindFile(file, cache, global.ImagePath) img, err := global.FindFile(file, cache, global.ImagePath)
if err != nil { if err != nil {
@ -1237,7 +1257,7 @@ func (bot *CQBot) CQSetGroupPortrait(groupID int64, file, cache string) MSG {
// CQSetGroupAnonymousBan 群组匿名用户禁言 // CQSetGroupAnonymousBan 群组匿名用户禁言
// //
// https://git.io/Jtz1p // https://git.io/Jtz1p
func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration int32) MSG { func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration int32) global.MSG {
if flag == "" { if flag == "" {
return Failed(100, "INVALID_FLAG", "无效的flag") return Failed(100, "INVALID_FLAG", "无效的flag")
} }
@ -1260,8 +1280,8 @@ func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration in
// CQGetStatus 获取运行状态 // CQGetStatus 获取运行状态
// //
// https://git.io/JtzMe // https://git.io/JtzMe
func (bot *CQBot) CQGetStatus() MSG { func (bot *CQBot) CQGetStatus() global.MSG {
return OK(MSG{ return OK(global.MSG{
"app_initialized": true, "app_initialized": true,
"app_enabled": true, "app_enabled": true,
"plugins_good": nil, "plugins_good": nil,
@ -1275,7 +1295,7 @@ func (bot *CQBot) CQGetStatus() MSG {
// CQSetEssenceMessage 扩展API-设置精华消息 // 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 // 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 { func (bot *CQBot) CQSetEssenceMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg := bot.GetMessage(messageID)
if msg == nil { if msg == nil {
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在") return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
@ -1295,7 +1315,7 @@ func (bot *CQBot) CQSetEssenceMessage(messageID int32) MSG {
// CQDeleteEssenceMessage 扩展API-移出精华消息 // 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 // 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 { func (bot *CQBot) CQDeleteEssenceMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg := bot.GetMessage(messageID)
if msg == nil { if msg == nil {
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在") return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
@ -1315,7 +1335,7 @@ func (bot *CQBot) CQDeleteEssenceMessage(messageID int32) MSG {
// CQGetEssenceMessageList 扩展API-获取精华消息列表 // 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 // 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 { func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) global.MSG {
g := bot.Client.FindGroup(groupCode) g := bot.Client.FindGroup(groupCode)
if g == nil { if g == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -1324,9 +1344,9 @@ func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
if err != nil { if err != nil {
return Failed(100, "GET_ESSENCE_LIST_FOUND", err.Error()) return Failed(100, "GET_ESSENCE_LIST_FOUND", err.Error())
} }
list := make([]MSG, 0, len(msgList)) list := make([]global.MSG, 0, len(msgList))
for _, m := range msgList { for _, m := range msgList {
msg := MSG{ msg := global.MSG{
"sender_nick": m.SenderNick, "sender_nick": m.SenderNick,
"sender_time": m.SenderTime, "sender_time": m.SenderTime,
"operator_time": m.AddDigestTime, "operator_time": m.AddDigestTime,
@ -1343,8 +1363,8 @@ func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
// CQCheckURLSafely 扩展API-检查链接安全性 // 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 // 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 { func (bot *CQBot) CQCheckURLSafely(url string) global.MSG {
return OK(MSG{ return OK(global.MSG{
"level": bot.Client.CheckUrlSafely(url), "level": bot.Client.CheckUrlSafely(url),
}) })
} }
@ -1352,12 +1372,12 @@ func (bot *CQBot) CQCheckURLSafely(url string) MSG {
// CQGetVersionInfo 获取版本信息 // CQGetVersionInfo 获取版本信息
// //
// https://git.io/JtwUs // https://git.io/JtwUs
func (bot *CQBot) CQGetVersionInfo() MSG { func (bot *CQBot) CQGetVersionInfo() global.MSG {
wd, _ := os.Getwd() wd, _ := os.Getwd()
return OK(MSG{ return OK(global.MSG{
"app_name": "go-cqhttp", "app_name": "go-cqhttp",
"app_version": Version, "app_version": base.Version,
"app_full_name": fmt.Sprintf("go-cqhttp-%s_%s_%s-%s", Version, runtime.GOOS, runtime.GOARCH, runtime.Version()), "app_full_name": fmt.Sprintf("go-cqhttp-%s_%s_%s-%s", base.Version, runtime.GOOS, runtime.GOARCH, runtime.Version()),
"protocol_version": "v11", "protocol_version": "v11",
"coolq_directory": wd, "coolq_directory": wd,
"coolq_edition": "pro", "coolq_edition": "pro",
@ -1367,7 +1387,7 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
"plugin_build_configuration": "release", "plugin_build_configuration": "release",
"runtime_version": runtime.Version(), "runtime_version": runtime.Version(),
"runtime_os": runtime.GOOS, "runtime_os": runtime.GOOS,
"version": Version, "version": base.Version,
"protocol": func() int { "protocol": func() int {
switch client.SystemDeviceInfo.Protocol { switch client.SystemDeviceInfo.Protocol {
case client.IPad: case client.IPad:
@ -1390,19 +1410,19 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
// CQGetModelShow 获取在线机型 // CQGetModelShow 获取在线机型
// //
// https://club.vip.qq.com/onlinestatus/set // https://club.vip.qq.com/onlinestatus/set
func (bot *CQBot) CQGetModelShow(modelName string) MSG { func (bot *CQBot) CQGetModelShow(modelName string) global.MSG {
variants, err := bot.Client.GetModelShow(modelName) variants, err := bot.Client.GetModelShow(modelName)
if err != nil { if err != nil {
return Failed(100, "GET_MODEL_SHOW_API_ERROR", "无法获取在线机型") return Failed(100, "GET_MODEL_SHOW_API_ERROR", "无法获取在线机型")
} }
a := make([]MSG, 0, len(variants)) a := make([]global.MSG, 0, len(variants))
for _, v := range variants { for _, v := range variants {
a = append(a, MSG{ a = append(a, global.MSG{
"model_show": v.ModelShow, "model_show": v.ModelShow,
"need_pay": v.NeedPay, "need_pay": v.NeedPay,
}) })
} }
return OK(MSG{ return OK(global.MSG{
"variants": a, "variants": a,
}) })
} }
@ -1410,7 +1430,7 @@ func (bot *CQBot) CQGetModelShow(modelName string) MSG {
// CQSetModelShow 设置在线机型 // CQSetModelShow 设置在线机型
// //
// https://club.vip.qq.com/onlinestatus/set // https://club.vip.qq.com/onlinestatus/set
func (bot *CQBot) CQSetModelShow(modelName string, modelShow string) MSG { func (bot *CQBot) CQSetModelShow(modelName string, modelShow string) global.MSG {
err := bot.Client.SetModelShow(modelName, modelShow) err := bot.Client.SetModelShow(modelName, modelShow)
if err != nil { if err != nil {
return Failed(100, "SET_MODEL_SHOW_API_ERROR", "无法设置在线机型") return Failed(100, "SET_MODEL_SHOW_API_ERROR", "无法设置在线机型")
@ -1419,7 +1439,7 @@ func (bot *CQBot) CQSetModelShow(modelName string, modelShow string) MSG {
} }
// CQMarkMessageAsRead 标记消息已读 // CQMarkMessageAsRead 标记消息已读
func (bot *CQBot) CQMarkMessageAsRead(msgID int32) MSG { func (bot *CQBot) CQMarkMessageAsRead(msgID int32) global.MSG {
m := bot.GetMessage(msgID) m := bot.GetMessage(msgID)
if m == nil { if m == nil {
return Failed(100, "MSG_NOT_FOUND", "消息不存在") return Failed(100, "MSG_NOT_FOUND", "消息不存在")
@ -1431,17 +1451,17 @@ func (bot *CQBot) CQMarkMessageAsRead(msgID int32) MSG {
if _, ok := m["from-group"]; ok { if _, ok := m["from-group"]; ok {
return Failed(100, "MSG_TYPE_ERROR", "不支持标记临时会话") return Failed(100, "MSG_TYPE_ERROR", "不支持标记临时会话")
} }
bot.Client.MarkPrivateMessageReaded(m["sender"].(*message.Sender).Uin, m["time"].(int64)) bot.Client.MarkPrivateMessageReaded(m["sender"].(message.Sender).Uin, int64(m["time"].(int32)))
return OK(nil) return OK(nil)
} }
// OK 生成成功返回值 // OK 生成成功返回值
func OK(data interface{}) MSG { func OK(data interface{}) global.MSG {
return MSG{"data": data, "retcode": 0, "status": "ok"} return global.MSG{"data": data, "retcode": 0, "status": "ok"}
} }
// Failed 生成失败返回值 // Failed 生成失败返回值
func Failed(code int, msg ...string) MSG { func Failed(code int, msg ...string) global.MSG {
m := "" m := ""
w := "" w := ""
if len(msg) > 0 { if len(msg) > 0 {
@ -1450,11 +1470,11 @@ func Failed(code int, msg ...string) MSG {
if len(msg) > 1 { if len(msg) > 1 {
w = msg[1] w = msg[1]
} }
return MSG{"data": nil, "retcode": code, "msg": m, "wording": w, "status": "failed"} return global.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) global.MSG {
return MSG{ return global.MSG{
"group_id": groupID, "group_id": groupID,
"user_id": m.Uin, "user_id": m.Uin,
"nickname": m.Nickname, "nickname": m.Nickname,

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"encoding/gob" "encoding/gob"
"encoding/hex" "encoding/hex"
"encoding/json"
"fmt" "fmt"
"hash/crc32" "hash/crc32"
"io" "io"
@ -13,24 +14,20 @@ import (
"sync" "sync"
"time" "time"
"github.com/gabriel-vasile/mimetype"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors" "github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt" "github.com/syndtr/goleveldb/leveldb/opt"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/modules/config"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary
// CQBot CQBot结构体,存储Bot实例相关配置 // CQBot CQBot结构体,存储Bot实例相关配置
type CQBot struct { type CQBot struct {
Client *client.QQClient Client *client.QQClient
@ -41,15 +38,11 @@ type CQBot struct {
db *leveldb.DB db *leveldb.DB
friendReqCache sync.Map friendReqCache sync.Map
tempSessionCache sync.Map tempSessionCache sync.Map
oneWayMsgCache sync.Map
} }
// MSG 消息Map
type MSG map[string]interface{}
// Event 事件 // Event 事件
type Event struct { type Event struct {
RawMsg MSG RawMsg global.MSG
once sync.Once once sync.Once
buffer *bytes.Buffer buffer *bytes.Buffer
@ -75,27 +68,13 @@ func (e *Event) JSONString() string {
return utils.B2S(e.buffer.Bytes()) return utils.B2S(e.buffer.Bytes())
} }
// ForceFragmented 是否启用强制分片
var ForceFragmented = false
// SkipMimeScan 是否跳过Mime扫描
var SkipMimeScan bool
var lawfulImageTypes = [...]string{"image/png", "image/jpeg", "image/gif", "image/bmp", "image/webp"}
var lawfulAudioTypes = [...]string{
"audio/mpeg", "audio/flac", "audio/midi", "audio/ogg",
"audio/ape", "audio/amr", "audio/wav", "audio/aiff",
"audio/mp4", "audio/aac", "audio/x-m4a",
}
// NewQQBot 初始化一个QQBot实例 // NewQQBot 初始化一个QQBot实例
func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot { func NewQQBot(cli *client.QQClient) *CQBot {
bot := &CQBot{ bot := &CQBot{
Client: cli, Client: cli,
} }
enableLevelDB := false enableLevelDB := false
node, ok := conf.Database["leveldb"] node, ok := base.Database["leveldb"]
if ok { if ok {
lconf := new(config.LevelDBConfig) lconf := new(config.LevelDBConfig)
_ = node.Decode(lconf) _ = node.Decode(lconf)
@ -117,7 +96,7 @@ func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
} }
bot.Client.OnPrivateMessage(bot.privateMessageEvent) bot.Client.OnPrivateMessage(bot.privateMessageEvent)
bot.Client.OnGroupMessage(bot.groupMessageEvent) bot.Client.OnGroupMessage(bot.groupMessageEvent)
if conf.Message.ReportSelfMessage { if base.ReportSelfMessage {
bot.Client.OnSelfPrivateMessage(bot.privateMessageEvent) bot.Client.OnSelfPrivateMessage(bot.privateMessageEvent)
bot.Client.OnSelfGroupMessage(bot.groupMessageEvent) bot.Client.OnSelfGroupMessage(bot.groupMessageEvent)
} }
@ -142,24 +121,20 @@ func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent) bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent)
bot.Client.OnGroupDigest(bot.groupEssenceMsg) bot.Client.OnGroupDigest(bot.groupEssenceMsg)
go func() { go func() {
i := conf.Heartbeat.Interval if base.HeartbeatInterval == 0 {
if i < 0 || conf.Heartbeat.Disabled {
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。") log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
return return
} }
if i == 0 { t := time.NewTicker(base.HeartbeatInterval)
i = 5
}
t := time.NewTicker(time.Second * time.Duration(i))
for { for {
<-t.C <-t.C
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"time": time.Now().Unix(), "time": time.Now().Unix(),
"self_id": bot.Client.Uin, "self_id": bot.Client.Uin,
"post_type": "meta_event", "post_type": "meta_event",
"meta_event_type": "heartbeat", "meta_event_type": "heartbeat",
"status": bot.CQGetStatus()["data"], "status": bot.CQGetStatus()["data"],
"interval": 1000 * i, "interval": base.HeartbeatInterval.Milliseconds(),
}) })
} }
}() }()
@ -174,9 +149,9 @@ func (bot *CQBot) OnEventPush(f func(e *Event)) {
} }
// GetMessage 获取给定消息id对应的消息 // GetMessage 获取给定消息id对应的消息
func (bot *CQBot) GetMessage(mid int32) MSG { func (bot *CQBot) GetMessage(mid int32) global.MSG {
if bot.db != nil { if bot.db != nil {
m := MSG{} m := global.MSG{}
data, err := bot.db.Get(binary.ToBytes(mid), nil) data, err := bot.db.Get(binary.ToBytes(mid), nil)
if err == nil { if err == nil {
err = gob.NewDecoder(bytes.NewReader(data)).Decode(&m) err = gob.NewDecoder(bytes.NewReader(data)).Decode(&m)
@ -199,7 +174,7 @@ func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElemen
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
img.Stream = f img.Stream = f
} }
if lawful, mime := IsLawfulImage(img.Stream); !lawful { if lawful, mime := base.IsLawfulImage(img.Stream); !lawful {
return nil, errors.New("image type error: " + mime) return nil, errors.New("image type error: " + mime)
} }
i, err = bot.Client.UploadGroupImage(groupCode, img.Stream) i, err = bot.Client.UploadGroupImage(groupCode, img.Stream)
@ -234,7 +209,7 @@ func (bot *CQBot) UploadLocalImageAsPrivate(userID int64, img *LocalImageElement
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
img.Stream = f img.Stream = f
} }
if lawful, mime := IsLawfulImage(img.Stream); !lawful { if lawful, mime := base.IsLawfulImage(img.Stream); !lawful {
return nil, errors.New("image type error: " + mime) return nil, errors.New("image type error: " + mime)
} }
i, err = bot.Client.UploadPrivateImage(userID, img.Stream) i, err = bot.Client.UploadPrivateImage(userID, img.Stream)
@ -287,7 +262,7 @@ func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) int
} }
m.Elements = newElem m.Elements = newElem
bot.checkMedia(newElem) bot.checkMedia(newElem)
ret := bot.Client.SendGroupMessage(groupID, m, ForceFragmented) ret := bot.Client.SendGroupMessage(groupID, m, base.ForceFragmented)
if ret == nil || ret.Id == -1 { if ret == nil || ret.Id == -1 {
log.Warnf("群消息发送失败: 账号可能被风控.") log.Warnf("群消息发送失败: 账号可能被风控.")
return -1 return -1
@ -301,7 +276,7 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
for _, e := range m.Elements { for _, e := range m.Elements {
switch i := e.(type) { switch i := e.(type) {
case *LocalImageElement, *message.VoiceElement, *LocalVideoElement: case *LocalImageElement, *message.VoiceElement, *LocalVideoElement:
i, err := bot.uploadMedia(i, groupID, false) i, err := bot.uploadMedia(i, target, false)
if err != nil { if err != nil {
log.Warnf("警告: 私聊 %d 消息%s上传失败: %v", target, e.Type().String(), err) log.Warnf("警告: 私聊 %d 消息%s上传失败: %v", target, e.Type().String(), err)
continue continue
@ -311,7 +286,7 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
bot.Client.SendFriendPoke(i.Target) bot.Client.SendFriendPoke(i.Target)
return 0 return 0
case *message.MusicShareElement: case *message.MusicShareElement:
bot.Client.SendFriendMusicShare(groupID, i) bot.Client.SendFriendMusicShare(target, i)
return 0 return 0
} }
newElem = append(newElem, e) newElem = append(newElem, e)
@ -322,13 +297,31 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
} }
m.Elements = newElem m.Elements = newElem
bot.checkMedia(newElem) bot.checkMedia(newElem)
// 单向好友是否存在
unidirectionalFriendExists := func() bool {
list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil {
return false
}
for _, f := range list {
if f.Uin == target {
return true
}
}
return false
}
session, ok := bot.tempSessionCache.Load(target)
var id int32 = -1 var id int32 = -1
if bot.Client.FindFriend(target) != nil { // 双向好友
switch {
case bot.Client.FindFriend(target) != nil: // 双向好友
msg := bot.Client.SendPrivateMessage(target, m) msg := bot.Client.SendPrivateMessage(target, m)
if msg != nil { if msg != nil {
id = bot.InsertPrivateMessage(msg) id = bot.InsertPrivateMessage(msg)
} }
} else if session, ok := bot.tempSessionCache.Load(target); ok || groupID != 0 { // 临时会话 case ok || groupID != 0: // 临时会话
switch { switch {
case groupID != 0 && bot.Client.FindGroup(groupID) == nil: case groupID != 0 && bot.Client.FindGroup(groupID) == nil:
log.Errorf("错误: 找不到群(%v)", groupID) log.Errorf("错误: 找不到群(%v)", groupID)
@ -353,12 +346,12 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
id = bot.InsertTempMessage(target, msg) id = bot.InsertTempMessage(target, msg)
} }
} }
} else if _, ok := bot.oneWayMsgCache.Load(target); ok { // 单向好友 case unidirectionalFriendExists(): // 单向好友
msg := bot.Client.SendPrivateMessage(target, m) msg := bot.Client.SendPrivateMessage(target, m)
if msg != nil { if msg != nil {
id = bot.InsertPrivateMessage(msg) id = bot.InsertPrivateMessage(msg)
} }
} else { default:
nickname := "Unknown" nickname := "Unknown"
if summaryInfo, _ := bot.Client.GetSummaryInfo(target); summaryInfo != nil { if summaryInfo, _ := bot.Client.GetSummaryInfo(target); summaryInfo != nil {
nickname = summaryInfo.Nickname nickname = summaryInfo.Nickname
@ -370,7 +363,7 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
// InsertGroupMessage 群聊消息入数据库 // InsertGroupMessage 群聊消息入数据库
func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 { func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
val := MSG{ val := global.MSG{
"message-id": m.Id, "message-id": m.Id,
"internal-id": m.InternalId, "internal-id": m.InternalId,
"group": m.GroupCode, "group": m.GroupCode,
@ -397,7 +390,7 @@ func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
// InsertPrivateMessage 私聊消息入数据库 // InsertPrivateMessage 私聊消息入数据库
func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 { func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 {
val := MSG{ val := global.MSG{
"message-id": m.Id, "message-id": m.Id,
"internal-id": m.InternalId, "internal-id": m.InternalId,
"target": m.Target, "target": m.Target,
@ -423,7 +416,7 @@ func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 {
// InsertTempMessage 临时消息入数据库 // InsertTempMessage 临时消息入数据库
func (bot *CQBot) InsertTempMessage(target int64, m *message.TempMessage) int32 { func (bot *CQBot) InsertTempMessage(target int64, m *message.TempMessage) int32 {
val := MSG{ val := global.MSG{
"message-id": m.Id, "message-id": m.Id,
// FIXME(InsertTempMessage) InternalId missing // FIXME(InsertTempMessage) InternalId missing
"from-group": m.GroupCode, "from-group": m.GroupCode,
@ -461,7 +454,7 @@ func (bot *CQBot) Release() {
} }
} }
func (bot *CQBot) dispatchEventMessage(m MSG) { func (bot *CQBot) dispatchEventMessage(m global.MSG) {
bot.lock.RLock() bot.lock.RLock()
defer bot.lock.RUnlock() defer bot.lock.RUnlock()
@ -489,9 +482,9 @@ func (bot *CQBot) dispatchEventMessage(m MSG) {
global.PutBuffer(event.buffer) global.PutBuffer(event.buffer)
} }
func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG { func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) global.MSG {
cqm := ToStringMessage(m.Elements, m.GroupCode, true) cqm := ToStringMessage(m.Elements, m.GroupCode, true)
gm := MSG{ gm := global.MSG{
"anonymous": nil, "anonymous": nil,
"font": 0, "font": 0,
"group_id": m.GroupCode, "group_id": m.GroupCode,
@ -506,7 +499,7 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG {
}(), }(),
"raw_message": cqm, "raw_message": cqm,
"self_id": bot.Client.Uin, "self_id": bot.Client.Uin,
"sender": MSG{ "sender": global.MSG{
"age": 0, "age": 0,
"area": "", "area": "",
"level": "", "level": "",
@ -518,12 +511,12 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG {
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
} }
if m.Sender.IsAnonymous() { if m.Sender.IsAnonymous() {
gm["anonymous"] = MSG{ gm["anonymous"] = global.MSG{
"flag": m.Sender.AnonymousInfo.AnonymousId + "|" + m.Sender.AnonymousInfo.AnonymousNick, "flag": m.Sender.AnonymousInfo.AnonymousId + "|" + m.Sender.AnonymousInfo.AnonymousNick,
"id": m.Sender.Uin, "id": m.Sender.Uin,
"name": m.Sender.AnonymousInfo.AnonymousNick, "name": m.Sender.AnonymousInfo.AnonymousNick,
} }
gm["sender"].(MSG)["nickname"] = "匿名消息" gm["sender"].(global.MSG)["nickname"] = "匿名消息"
gm["sub_type"] = "anonymous" gm["sub_type"] = "anonymous"
} else { } else {
group := bot.Client.FindGroup(m.GroupCode) group := bot.Client.FindGroup(m.GroupCode)
@ -541,7 +534,7 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG {
return nil return nil
} }
} }
ms := gm["sender"].(MSG) ms := gm["sender"].(global.MSG)
switch mem.Permission { switch mem.Permission {
case client.Owner: case client.Owner:
ms["role"] = "owner" ms["role"] = "owner"
@ -587,25 +580,3 @@ func (bot *CQBot) uploadMedia(raw message.IMessageElement, target int64, group b
} }
return nil, errors.New("unsupported message element type") return nil, errors.New("unsupported message element type")
} }
// IsLawfulImage 判断给定流是否为合法图片
// 返回 是否合法, 实际Mime
// 判断后会自动将 Stream Seek 至 0
func IsLawfulImage(r io.ReadSeeker) (bool, string) {
if SkipMimeScan {
return true, ""
}
_, _ = r.Seek(0, io.SeekStart)
defer func() { _, _ = r.Seek(0, io.SeekStart) }()
t, err := mimetype.DetectReader(r)
if err != nil {
log.Debugf("扫描 Mime 时出现问题: %v", err)
return false, ""
}
for _, lt := range lawfulImageTypes {
if t.Is(lt) {
return true, t.String()
}
}
return false, t.String()
}

View File

@ -3,7 +3,6 @@ package coolq
import ( import (
"bytes" "bytes"
"crypto/md5" "crypto/md5"
"encoding/base64"
"encoding/hex" "encoding/hex"
xml2 "encoding/xml" xml2 "encoding/xml"
"errors" "errors"
@ -18,8 +17,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/gabriel-vasile/mimetype"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
@ -27,7 +24,8 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/codec" "github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/param"
) )
/* /*
@ -36,18 +34,6 @@ var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`) var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
*/ */
// RemoveReplyAt 是否删除reply后的at
var RemoveReplyAt bool
// ExtraReplyData 是否上报额外reply信息
var ExtraReplyData bool
// IgnoreInvalidCQCode 是否忽略无效CQ码
var IgnoreInvalidCQCode = false
// SplitURL 是否分割URL
var SplitURL = false
const ( const (
maxImageSize = 1024 * 1024 * 30 // 30MB maxImageSize = 1024 * 1024 * 30 // 30MB
maxVideoSize = 1024 * 1024 * 100 // 100MB maxVideoSize = 1024 * 1024 * 100 // 100MB
@ -126,8 +112,8 @@ func (e *PokeElement) Type() message.ElementType {
} }
// ToArrayMessage 将消息元素数组转为MSG数组以用于消息上报 // ToArrayMessage 将消息元素数组转为MSG数组以用于消息上报
func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) { func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []global.MSG) {
r = make([]MSG, 0, len(e)) r = make([]global.MSG, 0, len(e))
m := &message.SendingMessage{Elements: e} m := &message.SendingMessage{Elements: e}
reply := m.FirstOrNil(func(e message.IMessageElement) bool { reply := m.FirstOrNil(func(e message.IMessageElement) bool {
_, ok := e.(*message.ReplyElement) _, ok := e.(*message.ReplyElement)
@ -139,8 +125,8 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
if rid == 0 { if rid == 0 {
rid = replyElem.Sender rid = replyElem.Sender
} }
if ExtraReplyData { if base.ExtraReplyData {
r = append(r, MSG{ r = append(r, global.MSG{
"type": "reply", "type": "reply",
"data": map[string]string{ "data": map[string]string{
"id": strconv.FormatInt(int64(toGlobalID(rid, replyElem.ReplySeq)), 10), "id": strconv.FormatInt(int64(toGlobalID(rid, replyElem.ReplySeq)), 10),
@ -151,71 +137,71 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
}, },
}) })
} else { } else {
r = append(r, MSG{ r = append(r, global.MSG{
"type": "reply", "type": "reply",
"data": map[string]string{"id": strconv.FormatInt(int64(toGlobalID(rid, replyElem.ReplySeq)), 10)}, "data": map[string]string{"id": strconv.FormatInt(int64(toGlobalID(rid, replyElem.ReplySeq)), 10)},
}) })
} }
} }
for i, elem := range e { for i, elem := range e {
var m MSG var m global.MSG
switch o := elem.(type) { switch o := elem.(type) {
case *message.ReplyElement: case *message.ReplyElement:
if RemoveReplyAt && i+1 < len(e) && e[i+1].Type() == message.At { if base.RemoveReplyAt && i+1 < len(e) {
elem, ok := e[i+1].(*message.AtElement) elem, ok := e[i+1].(*message.AtElement)
if ok && elem.Target == o.Sender { if ok && elem.Target == o.Sender {
e[i+1] = nil e[i+1] = nil
} }
} }
case *message.TextElement: case *message.TextElement:
m = MSG{ m = global.MSG{
"type": "text", "type": "text",
"data": map[string]string{"text": o.Content}, "data": map[string]string{"text": o.Content},
} }
case *message.LightAppElement: case *message.LightAppElement:
m = MSG{ m = global.MSG{
"type": "json", "type": "json",
"data": map[string]string{"data": o.Content}, "data": map[string]string{"data": o.Content},
} }
case *message.AtElement: case *message.AtElement:
if o.Target == 0 { if o.Target == 0 {
m = MSG{ m = global.MSG{
"type": "at", "type": "at",
"data": map[string]string{"qq": "all"}, "data": map[string]string{"qq": "all"},
} }
} else { } else {
m = MSG{ m = global.MSG{
"type": "at", "type": "at",
"data": map[string]string{"qq": strconv.FormatInt(o.Target, 10)}, "data": map[string]string{"qq": strconv.FormatInt(o.Target, 10)},
} }
} }
case *message.RedBagElement: case *message.RedBagElement:
m = MSG{ m = global.MSG{
"type": "redbag", "type": "redbag",
"data": map[string]string{"title": o.Title}, "data": map[string]string{"title": o.Title},
} }
case *message.ForwardElement: case *message.ForwardElement:
m = MSG{ m = global.MSG{
"type": "forward", "type": "forward",
"data": map[string]string{"id": o.ResId}, "data": map[string]string{"id": o.ResId},
} }
case *message.FaceElement: case *message.FaceElement:
m = MSG{ m = global.MSG{
"type": "face", "type": "face",
"data": map[string]string{"id": strconv.FormatInt(int64(o.Index), 10)}, "data": map[string]string{"id": strconv.FormatInt(int64(o.Index), 10)},
} }
case *message.VoiceElement: case *message.VoiceElement:
m = MSG{ m = global.MSG{
"type": "record", "type": "record",
"data": map[string]string{"file": o.Name, "url": o.Url}, "data": map[string]string{"file": o.Name, "url": o.Url},
} }
case *message.ShortVideoElement: case *message.ShortVideoElement:
m = MSG{ m = global.MSG{
"type": "video", "type": "video",
"data": map[string]string{"file": o.Name, "url": o.Url}, "data": map[string]string{"file": o.Name, "url": o.Url},
} }
case *message.GroupImageElement: case *message.GroupImageElement:
data := map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": o.Url} data := map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": o.Url, "subType": strconv.FormatInt(int64(o.ImageBizType), 10)}
switch { switch {
case o.Flash: case o.Flash:
data["type"] = "flash" data["type"] = "flash"
@ -223,7 +209,7 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
data["type"] = "show" data["type"] = "show"
data["id"] = strconv.FormatInt(int64(o.EffectID), 10) data["id"] = strconv.FormatInt(int64(o.EffectID), 10)
} }
m = MSG{ m = global.MSG{
"type": "image", "type": "image",
"data": data, "data": data,
} }
@ -232,18 +218,18 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
if o.Flash { if o.Flash {
data["type"] = "flash" data["type"] = "flash"
} }
m = MSG{ m = global.MSG{
"type": "image", "type": "image",
"data": data, "data": data,
} }
case *message.ServiceElement: case *message.ServiceElement:
if isOk := strings.Contains(o.Content, "<?xml"); isOk { if isOk := strings.Contains(o.Content, "<?xml"); isOk {
m = MSG{ m = global.MSG{
"type": "xml", "type": "xml",
"data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)}, "data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)},
} }
} else { } else {
m = MSG{ m = global.MSG{
"type": "json", "type": "json",
"data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)}, "data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)},
} }
@ -281,7 +267,7 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
if rid == 0 { if rid == 0 {
rid = replyElem.Sender rid = replyElem.Sender
} }
if ExtraReplyData { if base.ExtraReplyData {
write("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]", write("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]",
toGlobalID(rid, replyElem.ReplySeq), toGlobalID(rid, replyElem.ReplySeq),
replyElem.ReplySeq, replyElem.Sender, replyElem.Time, replyElem.ReplySeq, replyElem.Sender, replyElem.Time,
@ -293,7 +279,7 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
for i, elem := range e { for i, elem := range e {
switch o := elem.(type) { switch o := elem.(type) {
case *message.ReplyElement: case *message.ReplyElement:
if RemoveReplyAt && len(e) > i+1 { if base.RemoveReplyAt && len(e) > i+1 {
elem, ok := e[i+1].(*message.AtElement) elem, ok := e[i+1].(*message.AtElement)
if ok && elem.Target == o.Sender { if ok && elem.Target == o.Sender {
e[i+1] = nil e[i+1] = nil
@ -332,6 +318,7 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
} else if o.EffectID != 0 { } else if o.EffectID != 0 {
arg = ",type=show,id=" + strconv.FormatInt(int64(o.EffectID), 10) arg = ",type=show,id=" + strconv.FormatInt(int64(o.EffectID), 10)
} }
arg += ",subType=" + strconv.FormatInt(int64(o.ImageBizType), 10)
if ur { if ur {
write("[CQ:image,file=%s%s]", hex.EncodeToString(o.Md5)+".image", arg) write("[CQ:image,file=%s%s]", hex.EncodeToString(o.Md5)+".image", arg)
} else { } else {
@ -380,7 +367,7 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
switch { switch {
case customText != "": case customText != "":
var elem *message.ReplyElement var elem *message.ReplyElement
var org MSG var org global.MSG
sender, senderErr := strconv.ParseInt(d["qq"], 10, 64) sender, senderErr := strconv.ParseInt(d["qq"], 10, 64)
if senderErr != nil && err != nil { if senderErr != nil && err != nil {
log.Warnf("警告: 自定义 Reply 元素中必须包含 Uin 或 id") log.Warnf("警告: 自定义 Reply 元素中必须包含 Uin 或 id")
@ -455,7 +442,7 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
org += "," + k + "=" + v org += "," + k + "=" + v
} }
org += "]" org += "]"
if !IgnoreInvalidCQCode { if !base.IgnoreInvalidCQCode {
log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err) log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err)
r = append(r, message.NewText(org)) r = append(r, message.NewText(org))
} else { } else {
@ -477,8 +464,8 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
i++ i++
} }
if i > 0 { if i > 0 {
if SplitURL { if base.SplitURL {
for _, txt := range global.SplitURL(CQCodeUnescapeText(raw[:i])) { for _, txt := range param.SplitURL(CQCodeUnescapeText(raw[:i])) {
r = append(r, message.NewText(txt)) r = append(r, message.NewText(txt))
} }
} else { } else {
@ -552,7 +539,7 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
switch { switch {
case customText != "": case customText != "":
var elem *message.ReplyElement var elem *message.ReplyElement
var org MSG var org global.MSG
sender, senderErr := strconv.ParseInt(e.Get("data.[user_id,qq]").String(), 10, 64) sender, senderErr := strconv.ParseInt(e.Get("data.[user_id,qq]").String(), 10, 64)
if senderErr != nil && err != nil { if senderErr != nil && err != nil {
log.Warnf("警告: 自定义 Reply 元素中必须包含 user_id 或 id") log.Warnf("警告: 自定义 Reply 元素中必须包含 user_id 或 id")
@ -663,9 +650,9 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m interface{}, err error) { func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m interface{}, err error) {
switch t { switch t {
case "text": case "text":
if SplitURL { if base.SplitURL {
var ret []message.IMessageElement var ret []message.IMessageElement
for _, text := range global.SplitURL(d["text"]) { for _, text := range param.SplitURL(d["text"]) {
ret = append(ret, message.NewText(text)) ret = append(ret, message.NewText(text))
} }
return ret, nil return ret, nil
@ -696,6 +683,8 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
case *message.GroupImageElement: case *message.GroupImageElement:
img.Flash = flash img.Flash = flash
img.EffectID = int32(id) img.EffectID = int32(id)
i, _ := strconv.ParseInt(d["subType"], 10, 64)
img.ImageBizType = message.ImageBizType(i)
case *message.FriendImageElement: case *message.FriendImageElement:
img.Flash = flash img.Flash = flash
} }
@ -724,7 +713,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &message.VoiceElement{Data: codec.RecodeTo24K(data)}, nil return &message.VoiceElement{Data: base.ResampleSilk(data)}, nil
case "record": case "record":
f := d["file"] f := d["file"]
data, err := global.FindFile(f, d["cache"], global.VoicePath) data, err := global.FindFile(f, d["cache"], global.VoicePath)
@ -734,17 +723,10 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !SkipMimeScan && !global.IsAMRorSILK(data) { if !global.IsAMRorSILK(data) {
mt := mimetype.Detect(data) lawful, mt := base.IsLawfulAudio(bytes.NewReader(data))
lawful := false
for _, lt := range lawfulAudioTypes {
if mt.Is(lt) {
lawful = true
break
}
}
if !lawful { if !lawful {
return nil, errors.New("audio type error: " + mt.String()) return nil, errors.New("audio type error: " + mt)
} }
} }
if !global.IsAMRorSILK(data) { if !global.IsAMRorSILK(data) {
@ -1116,7 +1098,7 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
return &LocalImageElement{File: fu.Path}, nil return &LocalImageElement{File: fu.Path}, nil
} }
if strings.HasPrefix(f, "base64") && !video { if strings.HasPrefix(f, "base64") && !video {
b, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(f, "base64://")) b, err := param.Base64DecodeString(strings.TrimPrefix(f, "base64://"))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -18,8 +18,10 @@ func TestCQBot_ConvertStringMessage(t *testing.T) {
} }
} }
var bench = `asdfqwerqwerqwer[CQ:face,id=115,text=111]asdfasdfasdfasdfasdfasdfasd[CQ:face,id=217]&#93; 123 &#91;` var (
var benchArray = gjson.Parse(`[{"type":"text","data":{"text":"asdfqwerqwerqwer"}},{"type":"face","data":{"id":"115","text":"111"}},{"type":"text","data":{"text":"asdfasdfasdfasdfasdfasdfasd"}},{"type":"face","data":{"id":"217"}},{"type":"text","data":{"text":"] "}},{"type":"text","data":{"text":"123"}},{"type":"text","data":{"text":" ["}}]`) bench = `asdfqwerqwerqwer[CQ:face,id=115,text=111]asdfasdfasdfasdfasdfasdfasd[CQ:face,id=217]&#93; 123 &#91;`
benchArray = gjson.Parse(`[{"type":"text","data":{"text":"asdfqwerqwerqwer"}},{"type":"face","data":{"id":"115","text":"111"}},{"type":"text","data":{"text":"asdfasdfasdfasdfasdfasdfasd"}},{"type":"face","data":{"id":"217"}},{"type":"text","data":{"text":"] "}},{"type":"text","data":{"text":"123"}},{"type":"text","data":{"text":" ["}}]`)
)
func BenchmarkCQBot_ConvertStringMessage(b *testing.B) { func BenchmarkCQBot_ConvertStringMessage(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {

View File

@ -9,6 +9,7 @@ import (
"time" "time"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
@ -16,18 +17,11 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
var format = "string"
// SetMessageFormat 设置消息上报格式默认为string
func SetMessageFormat(f string) {
format = f
}
// ToFormattedMessage 将给定[]message.IMessageElement转换为通过coolq.SetMessageFormat所定义的消息上报格式 // ToFormattedMessage 将给定[]message.IMessageElement转换为通过coolq.SetMessageFormat所定义的消息上报格式
func ToFormattedMessage(e []message.IMessageElement, groupID int64, isRaw ...bool) (r interface{}) { func ToFormattedMessage(e []message.IMessageElement, groupID int64, isRaw ...bool) (r interface{}) {
if format == "string" { if base.PostFormat == "string" {
r = ToStringMessage(e, groupID, isRaw...) r = ToStringMessage(e, groupID, isRaw...)
} else if format == "array" { } else if base.PostFormat == "array" {
r = ToArrayMessage(e, groupID) r = ToArrayMessage(e, groupID)
} }
return return
@ -36,15 +30,12 @@ func ToFormattedMessage(e []message.IMessageElement, groupID int64, isRaw ...boo
func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) { func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) {
bot.checkMedia(m.Elements) bot.checkMedia(m.Elements)
cqm := ToStringMessage(m.Elements, 0, true) cqm := ToStringMessage(m.Elements, 0, true)
if !m.Sender.IsFriend {
bot.oneWayMsgCache.Store(m.Sender.Uin, "")
}
id := m.Id id := m.Id
if bot.db != nil { if bot.db != nil {
id = bot.InsertPrivateMessage(m) id = bot.InsertPrivateMessage(m)
} }
log.Infof("收到好友 %v(%v) 的消息: %v (%v)", m.Sender.DisplayName(), m.Sender.Uin, cqm, id) log.Infof("收到好友 %v(%v) 的消息: %v (%v)", m.Sender.DisplayName(), m.Sender.Uin, cqm, id)
fm := MSG{ fm := global.MSG{
"post_type": func() string { "post_type": func() string {
if m.Sender.Uin == bot.Client.Uin { if m.Sender.Uin == bot.Client.Uin {
return "message_sent" return "message_sent"
@ -61,7 +52,7 @@ func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMess
"font": 0, "font": 0,
"self_id": c.Uin, "self_id": c.Uin,
"time": time.Now().Unix(), "time": time.Now().Unix(),
"sender": MSG{ "sender": global.MSG{
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
"nickname": m.Sender.Nickname, "nickname": m.Sender.Nickname,
"sex": "unknown", "sex": "unknown",
@ -76,12 +67,12 @@ func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage)
for _, elem := range m.Elements { for _, elem := range m.Elements {
if file, ok := elem.(*message.GroupFileElement); ok { if file, ok := elem.(*message.GroupFileElement); ok {
log.Infof("群 %v(%v) 内 %v(%v) 上传了文件: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, file.Name) log.Infof("群 %v(%v) 内 %v(%v) 上传了文件: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, file.Name)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_upload", "notice_type": "group_upload",
"group_id": m.GroupCode, "group_id": m.GroupCode,
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
"file": MSG{ "file": global.MSG{
"id": file.Path, "id": file.Path,
"name": file.Name, "name": file.Name,
"size": file.Size, "size": file.Size,
@ -118,7 +109,7 @@ func (bot *CQBot) tempMessageEvent(c *client.QQClient, e *client.TempMessageEven
id = bot.InsertTempMessage(m.Sender.Uin, m) id = bot.InsertTempMessage(m.Sender.Uin, m)
} }
log.Infof("收到来自群 %v(%v) 内 %v(%v) 的临时会话消息: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, cqm) log.Infof("收到来自群 %v(%v) 内 %v(%v) 的临时会话消息: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, cqm)
tm := MSG{ tm := global.MSG{
"post_type": "message", "post_type": "message",
"message_type": "private", "message_type": "private",
"sub_type": "group", "sub_type": "group",
@ -130,7 +121,7 @@ func (bot *CQBot) tempMessageEvent(c *client.QQClient, e *client.TempMessageEven
"font": 0, "font": 0,
"self_id": c.Uin, "self_id": c.Uin,
"time": time.Now().Unix(), "time": time.Now().Unix(),
"sender": MSG{ "sender": global.MSG{
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
"group_id": m.GroupCode, "group_id": m.GroupCode,
"nickname": m.Sender.Nickname, "nickname": m.Sender.Nickname,
@ -161,7 +152,7 @@ func (bot *CQBot) groupMutedEvent(c *client.QQClient, e *client.GroupMuteEvent)
} }
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"duration": e.Time, "duration": e.Time,
"group_id": e.GroupCode, "group_id": e.GroupCode,
@ -184,7 +175,7 @@ func (bot *CQBot) groupRecallEvent(c *client.QQClient, e *client.GroupMessageRec
gid := toGlobalID(e.GroupCode, e.MessageId) gid := toGlobalID(e.GroupCode, e.MessageId)
log.Infof("群 %v 内 %v 撤回了 %v 的消息: %v.", log.Infof("群 %v 内 %v 撤回了 %v 的消息: %v.",
formatGroupName(g), formatMemberName(g.FindMember(e.OperatorUin)), formatMemberName(g.FindMember(e.AuthorUin)), gid) formatGroupName(g), formatMemberName(g.FindMember(e.OperatorUin)), formatMemberName(g.FindMember(e.AuthorUin)), gid)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": e.GroupCode, "group_id": e.GroupCode,
"notice_type": "group_recall", "notice_type": "group_recall",
@ -203,7 +194,7 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
sender := group.FindMember(notify.Sender) sender := group.FindMember(notify.Sender)
receiver := group.FindMember(notify.Receiver) receiver := group.FindMember(notify.Receiver)
log.Infof("群 %v 内 %v 戳了戳 %v", formatGroupName(group), formatMemberName(sender), formatMemberName(receiver)) log.Infof("群 %v 内 %v 戳了戳 %v", formatGroupName(group), formatMemberName(sender), formatMemberName(receiver))
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": group.Code, "group_id": group.Code,
"notice_type": "notify", "notice_type": "notify",
@ -218,7 +209,7 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
sender := group.FindMember(notify.Sender) sender := group.FindMember(notify.Sender)
luckyKing := group.FindMember(notify.LuckyKing) luckyKing := group.FindMember(notify.LuckyKing)
log.Infof("群 %v 内 %v 的红包被抢完, %v 是运气王", formatGroupName(group), formatMemberName(sender), formatMemberName(luckyKing)) log.Infof("群 %v 内 %v 的红包被抢完, %v 是运气王", formatGroupName(group), formatMemberName(sender), formatMemberName(luckyKing))
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": group.Code, "group_id": group.Code,
"notice_type": "notify", "notice_type": "notify",
@ -231,7 +222,7 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
}) })
case *client.MemberHonorChangedNotifyEvent: case *client.MemberHonorChangedNotifyEvent:
log.Info(notify.Content()) log.Info(notify.Content())
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": group.Code, "group_id": group.Code,
"notice_type": "notify", "notice_type": "notify",
@ -267,7 +258,7 @@ func (bot *CQBot) friendNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
} else { } else {
log.Infof("好友 %v 戳了戳你.", friend.Nickname) log.Infof("好友 %v 戳了戳你.", friend.Nickname)
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "notify", "notice_type": "notify",
"sub_type": "poke", "sub_type": "poke",
@ -284,7 +275,7 @@ func (bot *CQBot) memberTitleUpdatedEvent(c *client.QQClient, e *client.MemberSp
group := c.FindGroup(e.GroupCode) group := c.FindGroup(e.GroupCode)
mem := group.FindMember(e.Uin) mem := group.FindMember(e.Uin)
log.Infof("群 %v(%v) 内成员 %v(%v) 获得了新的头衔: %v", group.Name, group.Code, mem.DisplayName(), mem.Uin, e.NewTitle) log.Infof("群 %v(%v) 内成员 %v(%v) 获得了新的头衔: %v", group.Name, group.Code, mem.DisplayName(), mem.Uin, e.NewTitle)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "notify", "notice_type": "notify",
"sub_type": "title", "sub_type": "title",
@ -304,7 +295,7 @@ func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageR
} else { } else {
log.Infof("好友 %v 撤回了消息: %v", e.FriendUin, gid) log.Infof("好友 %v 撤回了消息: %v", e.FriendUin, gid)
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "friend_recall", "notice_type": "friend_recall",
"self_id": c.Uin, "self_id": c.Uin,
@ -320,11 +311,11 @@ func (bot *CQBot) offlineFileEvent(c *client.QQClient, e *client.OfflineFileEven
return return
} }
log.Infof("好友 %v(%v) 发送了离线文件 %v", f.Nickname, f.Uin, e.FileName) log.Infof("好友 %v(%v) 发送了离线文件 %v", f.Nickname, f.Uin, e.FileName)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "offline_file", "notice_type": "offline_file",
"user_id": e.Sender, "user_id": e.Sender,
"file": MSG{ "file": global.MSG{
"name": e.FileName, "name": e.FileName,
"size": e.FileSize, "size": e.FileSize,
"url": e.DownloadUrl, "url": e.DownloadUrl,
@ -355,7 +346,7 @@ func (bot *CQBot) memberPermissionChangedEvent(c *client.QQClient, e *client.Mem
} }
return "unset" return "unset"
}() }()
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_admin", "notice_type": "group_admin",
"sub_type": st, "sub_type": st,
@ -368,7 +359,7 @@ func (bot *CQBot) memberPermissionChangedEvent(c *client.QQClient, e *client.Mem
func (bot *CQBot) memberCardUpdatedEvent(c *client.QQClient, e *client.MemberCardUpdatedEvent) { func (bot *CQBot) memberCardUpdatedEvent(c *client.QQClient, e *client.MemberCardUpdatedEvent) {
log.Infof("群 %v 的 %v 更新了名片 %v -> %v", formatGroupName(e.Group), formatMemberName(e.Member), e.OldCard, e.Member.CardName) log.Infof("群 %v 的 %v 更新了名片 %v -> %v", formatGroupName(e.Group), formatMemberName(e.Member), e.OldCard, e.Member.CardName)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_card", "notice_type": "group_card",
"group_id": e.Group.Code, "group_id": e.Group.Code,
@ -398,7 +389,7 @@ func (bot *CQBot) friendRequestEvent(c *client.QQClient, e *client.NewFriendRequ
log.Infof("收到来自 %v(%v) 的好友请求: %v", e.RequesterNick, e.RequesterUin, e.Message) log.Infof("收到来自 %v(%v) 的好友请求: %v", e.RequesterNick, e.RequesterUin, e.Message)
flag := strconv.FormatInt(e.RequestId, 10) flag := strconv.FormatInt(e.RequestId, 10)
bot.friendReqCache.Store(flag, e) bot.friendReqCache.Store(flag, e)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "request", "post_type": "request",
"request_type": "friend", "request_type": "friend",
"user_id": e.RequesterUin, "user_id": e.RequesterUin,
@ -412,7 +403,7 @@ func (bot *CQBot) friendRequestEvent(c *client.QQClient, e *client.NewFriendRequ
func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent) { func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent) {
log.Infof("添加了新好友: %v(%v)", e.Friend.Nickname, e.Friend.Uin) log.Infof("添加了新好友: %v(%v)", e.Friend.Nickname, e.Friend.Uin)
bot.tempSessionCache.Delete(e.Friend.Uin) bot.tempSessionCache.Delete(e.Friend.Uin)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "friend_add", "notice_type": "friend_add",
"self_id": c.Uin, "self_id": c.Uin,
@ -424,7 +415,7 @@ func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent)
func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRequest) { func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRequest) {
log.Infof("收到来自群 %v(%v) 内用户 %v(%v) 的加群邀请.", e.GroupName, e.GroupCode, e.InvitorNick, e.InvitorUin) log.Infof("收到来自群 %v(%v) 内用户 %v(%v) 的加群邀请.", e.GroupName, e.GroupCode, e.InvitorNick, e.InvitorUin)
flag := strconv.FormatInt(e.RequestId, 10) flag := strconv.FormatInt(e.RequestId, 10)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "request", "post_type": "request",
"request_type": "group", "request_type": "group",
"sub_type": "invite", "sub_type": "invite",
@ -440,7 +431,7 @@ func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRe
func (bot *CQBot) groupJoinReqEvent(c *client.QQClient, e *client.UserJoinGroupRequest) { func (bot *CQBot) groupJoinReqEvent(c *client.QQClient, e *client.UserJoinGroupRequest) {
log.Infof("群 %v(%v) 收到来自用户 %v(%v) 的加群请求.", e.GroupName, e.GroupCode, e.RequesterNick, e.RequesterUin) log.Infof("群 %v(%v) 收到来自用户 %v(%v) 的加群请求.", e.GroupName, e.GroupCode, e.RequesterNick, e.RequesterUin)
flag := strconv.FormatInt(e.RequestId, 10) flag := strconv.FormatInt(e.RequestId, 10)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "request", "post_type": "request",
"request_type": "group", "request_type": "group",
"sub_type": "add", "sub_type": "add",
@ -459,11 +450,11 @@ func (bot *CQBot) otherClientStatusChangedEvent(c *client.QQClient, e *client.Ot
} else { } else {
log.Infof("Bot 账号在客户端 %v (%v) 登出.", e.Client.DeviceName, e.Client.DeviceKind) log.Infof("Bot 账号在客户端 %v (%v) 登出.", e.Client.DeviceName, e.Client.DeviceKind)
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "client_status", "notice_type": "client_status",
"online": e.Online, "online": e.Online,
"client": MSG{ "client": global.MSG{
"app_id": e.Client.AppId, "app_id": e.Client.AppId,
"device_name": e.Client.DeviceName, "device_name": e.Client.DeviceName,
"device_kind": e.Client.DeviceKind, "device_kind": e.Client.DeviceKind,
@ -496,7 +487,7 @@ func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent
if e.OperatorUin == bot.Client.Uin { if e.OperatorUin == bot.Client.Uin {
return return
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": e.GroupCode, "group_id": e.GroupCode,
"notice_type": "essence", "notice_type": "essence",
@ -514,8 +505,8 @@ func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent
}) })
} }
func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) MSG { func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) global.MSG {
return MSG{ return global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_increase", "notice_type": "group_increase",
"group_id": groupCode, "group_id": groupCode,
@ -527,8 +518,8 @@ func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) MSG {
} }
} }
func (bot *CQBot) groupDecrease(groupCode, userUin int64, operator *client.GroupMemberInfo) MSG { func (bot *CQBot) groupDecrease(groupCode, userUin int64, operator *client.GroupMemberInfo) global.MSG {
return MSG{ return global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_decrease", "notice_type": "group_decrease",
"group_id": groupCode, "group_id": groupCode,

View File

@ -32,7 +32,6 @@ heartbeat:
# -1 为关闭心跳 # -1 为关闭心跳
interval: 5 interval: 5
message:
# 上报数据类型 # 上报数据类型
# 可选: string,array # 可选: string,array
post-format: string post-format: string
@ -48,6 +47,12 @@ message:
proxy-rewrite: '' proxy-rewrite: ''
# 是否上报自身消息 # 是否上报自身消息
report-self-message: false report-self-message: false
# 移除服务端的Reply附带的At
remove-reply-at: false
# 为Reply附加更多信息
extra-reply-data: false
# 跳过 Mime 扫描, 忽略错误数据
skip-mime-scan: false
output: output:
# 日志等级 trace,debug,info,warn,error # 日志等级 trace,debug,info,warn,error
@ -149,6 +154,8 @@ database: # 数据库相关设置
> 注4关闭心跳服务可能引起断线请谨慎关闭 > 注4关闭心跳服务可能引起断线请谨慎关闭
> 注5关于MIME扫描 详见[MIME](file.md#MIME)
## 在线状态 ## 在线状态
| 状态 | 值 | | 状态 | 值 |

View File

@ -77,6 +77,7 @@ Type : `image`
| ------- | --------------- | ---------------------------------------------------------------------- | | ------- | --------------- | ---------------------------------------------------------------------- |
| `file` | - | 图片文件名 | | `file` | - | 图片文件名 |
| `type` | `flash``show` | 图片类型,`flash` 表示闪照,`show` 表示秀图,默认普通图片 | | `type` | `flash``show` | 图片类型,`flash` 表示闪照,`show` 表示秀图,默认普通图片 |
| `subType`| - | 图片子类型, 只出现在群聊. |
| `url` | - | 图片 URL | | `url` | - | 图片 URL |
| `cache` | `0` `1` | 只在通过网络 URL 发送时有效,表示是否使用已缓存的文件,默认 `1` | | `cache` | `0` `1` | 只在通过网络 URL 发送时有效,表示是否使用已缓存的文件,默认 `1` |
| `id` | - | 发送秀图时的特效id默认为40000 | | `id` | - | 发送秀图时的特效id默认为40000 |
@ -93,6 +94,21 @@ Type : `image`
| 40004 | 爱你 | | 40004 | 爱你 |
| 40005 | 征友 | | 40005 | 征友 |
子类型列表:
| value | 说明 |
| ----- | ---- |
| 0 | 正常图片 |
| 1 | 表情包, 在客户端会被分类到表情包图片并缩放显示 |
| 2 | 热图 |
| 3 | 斗图 |
| 4 | 智图? |
| 7 | 贴图 |
| 8 | 自拍 |
| 9 | 贴图广告? |
| 10 | 有待测试 |
| 13 | 热搜图 |
示例: `[CQ:image,file=http://baidu.com/1.jpg,type=show,id=40004]` 示例: `[CQ:image,file=http://baidu.com/1.jpg,type=show,id=40004]`
> 注意图片总大小不能超过30MBgif总帧数不能超过300帧 > 注意图片总大小不能超过30MBgif总帧数不能超过300帧
@ -1086,6 +1102,34 @@ JSON数组:
`该 API 没有响应数据` `该 API 没有响应数据`
### 获取单向好友列表
终结点: `/get_unidirectional_friend_list`
**响应数据**
数组信息:
| 字段 | 类型 | 说明 |
| ------------- | ------ | -------- |
| `nickname` | string | 昵称 |
| `user_id` | int64 | 用户QQ号 |
| `source` | string | 添加途径 |
> 添加途径为用户显示内容, 如 `精确查找` `QQ群 - xxxx`
### 删除单向好友
终结点: `/delete_unidirectional_friend`
**参数**
| 字段名 | 数据类型 | 默认值 | 说明 |
| ---------- | -------- | ------ | -------- |
| `user_id` | int64 | | 好友ID |
`该 API 没有响应数据`
### 删除好友 ### 删除好友
终结点: `/delete_friend` 终结点: `/delete_friend`
@ -1094,7 +1138,7 @@ JSON数组:
| 字段名 | 数据类型 | 默认值 | 说明 | | 字段名 | 数据类型 | 默认值 | 说明 |
| ---------- | -------- | ------ | -------- | | ---------- | -------- | ------ | -------- |
| `id` | int64 | | 好友ID | | `user_id` | int64 | | 好友ID |
`该 API 没有响应数据` `该 API 没有响应数据`

View File

@ -38,3 +38,31 @@ go-cqhttp 默认生成的文件树如下所示:
| 0x10 | uint32 | 图片源文件大小 | | 0x10 | uint32 | 图片源文件大小 |
| 0x14 | string | 图片原名(QQ内部ID) | | 0x14 | string | 图片原名(QQ内部ID) |
| 0x14 + 原名长度 | string | 图片下载链接 | | 0x14 + 原名长度 | string | 图片下载链接 |
# MIME
启用MINE检查可以及时发现媒体资源格式错误引起的上传失败(通常表现为请求网页图片但服务端返回404.html)
在配置文件中设置 `skip-mine-scan: false`go-cqhttp 会在上传媒体资源(视频暂不支持)前对MIME进行检查
详细允许类型如下所示:
图片:
> image/bmp
> image/gif
> image/jpeg
> image/png
> image/webp
语音:
> audio/aac
> audio/aiff
> audio/amr
> audio/ape
> audio/flac
> audio/midi
> audio/mp4
> audio/mpeg
> audio/ogg
> audio/wav
> audio/x-m4a

View File

@ -8,7 +8,7 @@ import (
) )
func TestVersionNameCompare(t *testing.T) { func TestVersionNameCompare(t *testing.T) {
var tests = [...]struct { tests := [...]struct {
current string current string
remote string remote string
expected bool expected bool

View File

@ -7,9 +7,9 @@ import (
"os/exec" "os/exec"
"path" "path"
"github.com/Mrs4s/go-cqhttp/global/codec"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/Mrs4s/go-cqhttp/internal/base"
) )
// EncoderSilk 将音频编码为Silk // EncoderSilk 将音频编码为Silk
@ -23,7 +23,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) { if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) {
return os.ReadFile(silkPath) return os.ReadFile(silkPath)
} }
slk, err := codec.EncodeToSilk(data, tempName, true) slk, err := base.EncodeSilk(data, tempName)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "encode silk failed") return nil, errors.Wrap(err, "encode silk failed")
} }

View File

@ -1,16 +0,0 @@
//go:build (!arm && !arm64 && !amd64 && !386) || race || (!windows && !linux && !darwin) || (windows && arm)
// +build !arm,!arm64,!amd64,!386 race !windows,!linux,!darwin windows,arm
package codec
import "errors"
// EncodeToSilk 将音频编码为Silk
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) {
return nil, errors.New("not supported now")
}
// RecodeTo24K 将silk重新编码为 24000 bit rate
func RecodeTo24K(data []byte) []byte {
return data
}

View File

@ -1,2 +0,0 @@
// Package codec Slik编码核心模块
package codec

View File

@ -1,4 +0,0 @@
package codec
// Debug mode controls the ffmpeg output.
var Debug bool

View File

@ -3,7 +3,6 @@ package global
import ( import (
"bytes" "bytes"
"crypto/md5" "crypto/md5"
"encoding/base64"
"encoding/hex" "encoding/hex"
"errors" "errors"
"net" "net"
@ -16,6 +15,8 @@ import (
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/Mrs4s/go-cqhttp/internal/param"
) )
const ( const (
@ -45,7 +46,7 @@ var (
// PathExists 判断给定path是否存在 // PathExists 判断给定path是否存在
func PathExists(path string) bool { func PathExists(path string) bool {
_, err := os.Stat(path) _, err := os.Stat(path)
return err == nil || os.IsExist(err) return err == nil || errors.Is(err, os.ErrExist)
} }
// ReadAllText 读取给定path对应文件无法读取时返回空值 // ReadAllText 读取给定path对应文件无法读取时返回空值
@ -98,7 +99,7 @@ func FindFile(file, cache, p string) (data []byte, err error) {
return nil, err return nil, err
} }
case strings.HasPrefix(file, "base64"): case strings.HasPrefix(file, "base64"):
data, err = base64.StdEncoding.DecodeString(strings.TrimPrefix(file, "base64://")) data, err = param.Base64DecodeString(strings.TrimPrefix(file, "base64://"))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -12,22 +12,22 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time"
"github.com/guonaihong/gout"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/internal/base"
) )
var ( var (
client = &http.Client{ client = &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
Proxy: func(request *http.Request) (u *url.URL, e error) { Proxy: func(request *http.Request) (u *url.URL, e error) {
if Proxy == "" { if base.Proxy == "" {
return http.ProxyFromEnvironment(request) return http.ProxyFromEnvironment(request)
} }
return url.Parse(Proxy) return url.Parse(base.Proxy)
}, },
ForceAttemptHTTP2: true, ForceAttemptHTTP2: true,
MaxConnsPerHost: 0, MaxConnsPerHost: 0,
@ -36,9 +36,6 @@ var (
}, },
} }
// Proxy 存储Config.proxy_rewrite,用于设置代理
Proxy string
// ErrOverSize 响应主体过大时返回此错误 // ErrOverSize 响应主体过大时返回此错误
ErrOverSize = errors.New("oversize") ErrOverSize = errors.New("oversize")
@ -249,22 +246,6 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int,
return lastErr return lastErr
} }
// GetSliderTicket 通过给定的验证链接raw和id,获取验证结果Ticket
func GetSliderTicket(raw, id string) (string, error) {
var rsp string
if err := gout.POST("https://api.shkong.com/gocqhttpapi/task").SetJSON(gout.H{
"id": id,
"url": raw,
}).SetTimeout(time.Second * 35).BindBody(&rsp).Do(); err != nil {
return "", err
}
g := gjson.Parse(rsp)
if g.Get("error").Str != "" {
return "", errors.New(g.Get("error").Str)
}
return g.Get("ticket").Str, nil
}
// QQMusicSongInfo 通过给定id在QQ音乐上查找曲目信息 // QQMusicSongInfo 通过给定id在QQ音乐上查找曲目信息
func QQMusicSongInfo(id string) (gjson.Result, error) { func QQMusicSongInfo(id string) (gjson.Result, error) {
d, err := GetBytes(`https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data={%22comm%22:{%22ct%22:24,%22cv%22:0},%22songinfo%22:{%22method%22:%22get_song_detail_yqq%22,%22param%22:{%22song_type%22:0,%22song_mid%22:%22%22,%22song_id%22:` + id + `},%22module%22:%22music.pf_song_detail_svr%22}}`) d, err := GetBytes(`https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data={%22comm%22:{%22ct%22:24,%22cv%22:0},%22songinfo%22:{%22method%22:%22get_song_detail_yqq%22,%22param%22:{%22song_type%22:0,%22song_mid%22:%22%22,%22song_id%22:` + id + `},%22module%22:%22music.pf_song_detail_svr%22}}`)

View File

@ -1,58 +1,14 @@
package global package global
import ( import (
"math"
"reflect"
"regexp" "regexp"
"strconv" "strconv"
"strings"
"sync"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
// EnsureBool 判断给定的p是否可表示为合法Bool类型,否则返回defaultVal // MSG 消息Map
// type MSG map[string]interface{}
// 支持的合法类型有
//
// type bool
//
// type gjson.True or gjson.False
//
// type string "true","yes","1" or "false","no","0" (case insensitive)
func EnsureBool(p interface{}, defaultVal bool) bool {
var str string
if b, ok := p.(bool); ok {
return b
}
if j, ok := p.(gjson.Result); ok {
if !j.Exists() {
return defaultVal
}
switch j.Type { // nolint
case gjson.True:
return true
case gjson.False:
return false
case gjson.String:
str = j.Str
default:
return defaultVal
}
} else if s, ok := p.(string); ok {
str = s
}
str = strings.ToLower(str)
switch str {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return defaultVal
}
}
// VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则 // VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则
// //
@ -88,67 +44,3 @@ func VersionNameCompare(current, remote string) bool {
} }
return cur[4] < re[4] return cur[4] < re[4]
} }
// SetAtDefault 在变量 variable 为默认值 defaultValue 的时候修改为 value
func SetAtDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if v.Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}
// SetExcludeDefault 在目标值 value 不为默认值 defaultValue 时修改 variable 为 value
func SetExcludeDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if reflect.Indirect(v2).Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}
var (
// once lazy compile the reg
once sync.Once
// reg is splitURL regex pattern.
reg *regexp.Regexp
)
// SplitURL 将给定URL字符串分割为两部分用于URL预处理防止风控
func SplitURL(s string) []string {
once.Do(func() { // lazy init.
reg = regexp.MustCompile(`(?i)[a-z\d][-a-z\d]{0,62}(\.[a-z\d][-a-z\d]{0,62})+\.?`)
})
idx := reg.FindAllStringIndex(s, -1)
if len(idx) == 0 {
return []string{s}
}
var result []string
last := 0
for i := 0; i < len(idx); i++ {
if len(idx[i]) != 2 {
continue
}
m := int(math.Abs(float64(idx[i][0]-idx[i][1]))/1.5) + idx[i][0]
result = append(result, s[last:m])
last = m
}
result = append(result, s[last:])
return result
}

View File

@ -18,11 +18,9 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
var ( var validTasks = map[string]func(){
validTasks = map[string]func(){
"dumpstack": dumpStack, "dumpstack": dumpStack,
} }
)
// SetupMainSignalHandler is for main to use at last // SetupMainSignalHandler is for main to use at last
func SetupMainSignalHandler() <-chan struct{} { func SetupMainSignalHandler() <-chan struct{} {

View File

@ -7,3 +7,8 @@ package terminal
func RunningByDoubleClick() bool { func RunningByDoubleClick() bool {
return false return false
} }
// NoMoreDoubleClick 提示用户不要双击运行非Windows系统永远返回nil
func NoMoreDoubleClick() error {
return nil
}

View File

@ -4,8 +4,11 @@
package terminal package terminal
import ( import (
"os"
"syscall" "syscall"
"unsafe" "unsafe"
"github.com/pkg/errors"
) )
// RunningByDoubleClick 检查是否通过双击直接运行 // RunningByDoubleClick 检查是否通过双击直接运行
@ -22,3 +25,43 @@ func RunningByDoubleClick() bool {
} }
return true return true
} }
// NoMoreDoubleClick 提示用户不要双击运行,并生成安全启动脚本
func NoMoreDoubleClick() error {
r := boxW(0, "请勿通过双击直接运行本程序, 这将导致一些非预料的后果.\n请在shell中运行./go-cqhttp.exe\n点击确认将释出安全启动脚本点击取消则关闭程序", "警告", 0x00000030|0x00000001)
if r == 2 {
return nil
}
r = boxW(0, "点击确认将覆盖go-cqhttp.bat点击取消则关闭程序", "警告", 0x00000030|0x00000001)
if r == 2 {
return nil
}
f, err := os.OpenFile("go-cqhttp.bat", os.O_CREATE|os.O_RDWR, 0o666)
if err != nil {
return err
}
if err != nil {
return errors.Errorf("打开go-cqhttp.bat失败: %v", err)
}
_ = f.Truncate(0)
_, err = f.WriteString("%Created by go-cqhttp. DO NOT EDIT ME!%\nstart cmd /K go-cqhttp.exe")
if err != nil {
return errors.Errorf("写入go-cqhttp.bat失败: %v", err)
}
f.Close()
boxW(0, "安全启动脚本已生成请双击go-cqhttp.bat启动", "提示", 0x00000040|0x00000000)
return nil
}
// BoxW of Win32 API. Check https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw for more detail.
func boxW(hwnd uintptr, caption, title string, flags uint) int {
captionPtr, _ := syscall.UTF16PtrFromString(caption)
titlePtr, _ := syscall.UTF16PtrFromString(title)
ret, _, _ := syscall.NewLazyDLL("user32.dll").NewProc("MessageBoxW").Call(
hwnd,
uintptr(unsafe.Pointer(captionPtr)),
uintptr(unsafe.Pointer(titlePtr)),
uintptr(flags))
return int(ret)
}

View File

@ -1,93 +0,0 @@
// Package update 包含go-cqhttp自我更新相关函数
package update
import (
"bufio"
"bytes"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"github.com/dustin/go-humanize"
"github.com/kardianos/osext"
log "github.com/sirupsen/logrus"
)
// WriteSumCounter 写入量计算实例
type WriteSumCounter struct {
Total uint64
Hash hash.Hash
}
// Write 方法将写入的byte长度追加至写入的总长度Total中
func (wc *WriteSumCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.Hash.Write(p)
fmt.Printf("\r ")
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
return n, nil
}
// FromStream copy form getlantern/go-update
func FromStream(updateWith io.Reader) (err error, errRecover error) {
updatePath, err := osext.Executable()
if err != nil {
return
}
var newBytes []byte
// no patch to apply, go on through
bufBytes := bufio.NewReader(updateWith)
updateWith = io.Reader(bufBytes)
newBytes, err = io.ReadAll(updateWith)
if err != nil {
return
}
// get the directory the executable exists in
updateDir := filepath.Dir(updatePath)
filename := filepath.Base(updatePath)
// Copy the contents of of newbinary to a the new executable file
newPath := filepath.Join(updateDir, fmt.Sprintf(".%s.new", filename))
fp, err := os.OpenFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return
}
// We won't log this error, because it's always going to happen.
defer func() { _ = fp.Close() }()
if _, err = io.Copy(fp, bytes.NewReader(newBytes)); err != nil {
log.Errorf("Unable to copy data: %v\n", err)
}
// if we don't call fp.Close(), windows won't let us move the new executable
// because the file will still be "in use"
if err := fp.Close(); err != nil {
log.Errorf("Unable to close file: %v\n", err)
}
// this is where we'll move the executable to so that we can swap in the updated replacement
oldPath := filepath.Join(updateDir, fmt.Sprintf(".%s.old", filename))
// delete any existing old exec file - this is necessary on Windows for two reasons:
// 1. after a successful update, Windows can't remove the .old file because the process is still running
// 2. windows rename operations fail if the destination file already exists
_ = os.Remove(oldPath)
// move the existing executable to a new file in the same directory
err = os.Rename(updatePath, oldPath)
if err != nil {
return
}
// move the new executable in to become the new program
err = os.Rename(newPath, updatePath)
if err != nil {
// copy unsuccessful
errRecover = os.Rename(oldPath, updatePath)
} else {
// copy successful, remove the old binary
_ = os.Remove(oldPath)
}
return
}

49
go.mod
View File

@ -1,35 +1,56 @@
module github.com/Mrs4s/go-cqhttp module github.com/Mrs4s/go-cqhttp
go 1.16 go 1.17
replace github.com/willf/bitset v1.2.0 => github.com/bits-and-blooms/bitset v1.2.0
require ( require (
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f
github.com/Microsoft/go-winio v0.5.0 github.com/Microsoft/go-winio v0.5.0
github.com/Mrs4s/MiraiGo v0.0.0-20210810070836-6614d2383adb github.com/Mrs4s/MiraiGo v0.0.0-20210916113136-0238b2382b82
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/fumiama/go-hide-param v0.1.4
github.com/gabriel-vasile/mimetype v1.3.1 github.com/gabriel-vasile/mimetype v1.3.1
github.com/gorilla/websocket v1.4.2
github.com/guonaihong/gout v0.2.1
github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/json-iterator/go v1.1.11
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/lestrrat-go/strftime v1.0.4 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/segmentio/asm v1.0.0
github.com/sirupsen/logrus v1.8.1 github.com/sirupsen/logrus v1.8.1
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
github.com/stretchr/testify v1.7.0 github.com/stretchr/testify v1.7.0
github.com/syndtr/goleveldb v1.0.0 github.com/syndtr/goleveldb v1.0.0
github.com/tidwall/gjson v1.8.1 github.com/tidwall/gjson v1.8.1
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60 github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60
github.com/willf/bitset v1.2.0 // indirect golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d // indirect
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b
golang.org/x/time v0.0.0-20210611083556-38a9dc6acbc6 golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
nhooyr.io/websocket v1.8.7
) )
replace github.com/willf/bitset v1.2.0 => github.com/bits-and-blooms/bitset v1.2.0 require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/klauspost/compress v1.10.3 // indirect
github.com/klauspost/cpuid/v2 v2.0.6 // indirect
github.com/lestrrat-go/strftime v1.0.5 // indirect
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
github.com/tidwall/match v1.0.3 // indirect
github.com/tidwall/pretty v1.1.0 // indirect
github.com/willf/bitset v1.2.0 // indirect
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect
google.golang.org/protobuf v1.27.1 // indirect
modernc.org/libc v1.8.1 // indirect
modernc.org/mathutil v1.2.2 // indirect
modernc.org/memory v1.0.4 // indirect
)

59
go.sum
View File

@ -4,8 +4,8 @@ github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f/g
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Microsoft/go-winio v0.5.0 h1:Elr9Wn+sGKPlkaBvwu4mTrxtmOp3F3yV9qhaHbXGjwU= github.com/Microsoft/go-winio v0.5.0 h1:Elr9Wn+sGKPlkaBvwu4mTrxtmOp3F3yV9qhaHbXGjwU=
github.com/Microsoft/go-winio v0.5.0/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= github.com/Microsoft/go-winio v0.5.0/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=
github.com/Mrs4s/MiraiGo v0.0.0-20210810070836-6614d2383adb h1:agCxYd/ZemDwrEYKpnpKqA0cubxfpkQ/b+GpIlIJK0U= github.com/Mrs4s/MiraiGo v0.0.0-20210916113136-0238b2382b82 h1:VAav2Z5n41cp2bjskooPXAg9W39qQeEEj3FmYlnS3+E=
github.com/Mrs4s/MiraiGo v0.0.0-20210810070836-6614d2383adb/go.mod h1:5V3f/+mTYtrI/+hLqbdzZQXuLMl2RyLfx0XYYjCQ90Q= github.com/Mrs4s/MiraiGo v0.0.0-20210916113136-0238b2382b82/go.mod h1:EpB6wQ+iaIqLRxVrs6si2J3XGv6wHXMrRXNUnJFaoww=
github.com/bits-and-blooms/bitset v1.2.0 h1:Kn4yilvwNtMACtf1eYDlG8H77R07mZSPbMjLyS07ChA= github.com/bits-and-blooms/bitset v1.2.0 h1:Kn4yilvwNtMACtf1eYDlG8H77R07mZSPbMjLyS07ChA=
github.com/bits-and-blooms/bitset v1.2.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/bits-and-blooms/bitset v1.2.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
@ -18,12 +18,14 @@ github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25Kn
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= 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/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fumiama/go-hide-param v0.1.4 h1:y7TRTzZMdCH9GOXnIzU3B+1BSkcmvejVGmGsz4t0DGU=
github.com/fumiama/go-hide-param v0.1.4/go.mod h1:vJkQlJIEI56nIyp7tCQu1/2QOyKtZpudsnJkGk9U1aY=
github.com/gabriel-vasile/mimetype v1.3.1 h1:qevA6c2MtE1RorlScnixeG0VA1H4xrXyhyX3oWBynNQ= github.com/gabriel-vasile/mimetype v1.3.1 h1:qevA6c2MtE1RorlScnixeG0VA1H4xrXyhyX3oWBynNQ=
github.com/gabriel-vasile/mimetype v1.3.1/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8= github.com/gabriel-vasile/mimetype v1.3.1/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.0 h1:Lb3veSYoGaNck69fV2+Vf2juLSsHpMTf3Vk5+X+EDJg= github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.0/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 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 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
@ -31,54 +33,62 @@ 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/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 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0=
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 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/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
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 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.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 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.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.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.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.1.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= 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/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= 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/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/guonaihong/gout v0.2.1 h1:XnaS92y/Mpcu4MOQU5cx4hTKhbqFznbIE/uUI5sMY9E=
github.com/guonaihong/gout v0.2.1/go.mod h1:JkjNv1G2oRWvFgP/r4DUbYhoeIBB0zMP2j1ID+5CYpU=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 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 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 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ=
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
github.com/klauspost/compress v1.10.3 h1:OP96hzwJVBIHYU52pVTI6CczrxPvrGfgqF9N5eTO0Q8=
github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/cpuid/v2 v2.0.6 h1:dQ5ueTiftKxp0gyjKSx5+8BtPWkyQbd95m8Gys/RarI=
github.com/klauspost/cpuid/v2 v2.0.6/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= 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.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= 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/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 h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4=
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA= github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA=
github.com/lestrrat-go/strftime v1.0.4 h1:T1Rb9EPkAhgxKqbcMIPguPq8glqXTA1koF8n9BHElA8= github.com/lestrrat-go/strftime v1.0.5 h1:A7H3tT8DhTz8u65w+JRpiBxM4dINQhUXAZnhBa2xeOE=
github.com/lestrrat-go/strftime v1.0.4/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g= github.com/lestrrat-go/strftime v1.0.5/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g=
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 h1:u9jwvcKbQpghIXgNl/EOL8hzhAFXh4ePrEP493W3tNA= github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 h1:u9jwvcKbQpghIXgNl/EOL8hzhAFXh4ePrEP493W3tNA=
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4/go.mod h1:kcRFpEzolcEklV6rD7W95mG49/sbdX/PlFmd7ni3RvA= github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4/go.mod h1:kcRFpEzolcEklV6rD7W95mG49/sbdX/PlFmd7ni3RvA=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
@ -87,9 +97,8 @@ github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHX
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 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 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-20180228061459-e0a39a4cb421/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 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/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 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 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
@ -103,6 +112,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= 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/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/segmentio/asm v1.0.0 h1:GMF7/2eLkte13LERSOmPI766AJXJDRlsqqiN8T7Mfmk=
github.com/segmentio/asm v1.0.0/go.mod h1:4EUJGaKsB8ImLUwOGORVsNd9vTRDeh44JGsY4aKp5I4=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
@ -131,11 +142,9 @@ github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLY
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60 h1:lRKf10iIOW0VsH5WDF621ihzR+R2wEBZVtNRHuLLCb4= github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60 h1:lRKf10iIOW0VsH5WDF621ihzR+R2wEBZVtNRHuLLCb4=
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60/go.mod h1:ecFKZPX81BaB70I6ruUgEwYcDOtuNgJGnjdK+MIl5ko= github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60/go.mod h1:ecFKZPX81BaB70I6ruUgEwYcDOtuNgJGnjdK+MIl5ko=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e h1:gsTQYXdTw2Gq7RBsWvlQ91b+aEQ6bXFUngBGuR8sPpI= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ=
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d h1:RNPAfi2nHY7C2srAV8A49jpsYr0ADedCk1wq6fTMTvs=
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 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= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
@ -144,7 +153,6 @@ 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-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-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-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 h1:Ugb8sMTWuWRC3+sz5WeN/4kejDx9BvIwnPUiJBjJE+8= golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 h1:Ugb8sMTWuWRC3+sz5WeN/4kejDx9BvIwnPUiJBjJE+8=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
@ -174,8 +182,9 @@ 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/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20210611083556-38a9dc6acbc6 h1:Vv0JUPWTyeqUq42B2WJ1FeIDjjvGKoA2Ss+Ts0lAVbs= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20210611083556-38a9dc6acbc6/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs=
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
@ -198,10 +207,10 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 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/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 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
@ -224,3 +233,5 @@ modernc.org/mathutil v1.2.2 h1:+yFk8hBprV+4c0U9GjFtL+dV3N8hOJ8JCituQcMShFY=
modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= 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 h1:utMBrFcpnQDdNsmM6asmyH/FM9TqLPS7XF7otpJmrwM=
modernc.org/memory v1.0.4/go.mod h1:nV2OApxradM3/OVbs2/0OsP6nPfakXpi50C7dcoHXlc= modernc.org/memory v1.0.4/go.mod h1:nV2OApxradM3/OVbs2/0OsP6nPfakXpi50C7dcoHXlc=
nhooyr.io/websocket v1.8.7 h1:usjR2uOr/zjjkVMy0lW+PPohFok7PCow5sDjLgX4P4g=
nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0=

37
internal/base/feature.go Normal file
View File

@ -0,0 +1,37 @@
package base
import (
"io"
"github.com/pkg/errors"
)
// silk encode features
var (
EncodeSilk = encodeSilk // 编码 SilkV3 音频
ResampleSilk = resampleSilk // 将silk重新编码为 24000 bit rate
)
func encodeSilk(_ []byte, _ string) ([]byte, error) {
return nil, errors.New("not supported now")
}
func resampleSilk(data []byte) []byte {
return data
}
// Mime scan feature
var (
IsLawfulImage = nocheck // 检查图片MIME
IsLawfulAudio = nocheck // 检查音频MIME
)
func nocheck(_ io.ReadSeeker) (bool, string) {
return true, ""
}
// todo: enable in v1.1.0
// onebot v12 feature
const (
AcceptOneBotV12HTTPEndPoint = false
)

148
internal/base/flag.go Normal file
View File

@ -0,0 +1,148 @@
// Package base provides base config for go-cqhttp
package base
import (
"flag"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/modules/config"
)
// command flags
var (
LittleC string // config file
LittleD bool // daemon
LittleH bool // Help
LittleWD string // working directory
)
// config file flags
var (
Debug bool // 是否开启 debug 模式
RemoveReplyAt bool // 是否删除reply后的at
ExtraReplyData bool // 是否上报额外reply信息
IgnoreInvalidCQCode bool // 是否忽略无效CQ码
SplitURL bool // 是否分割URL
ForceFragmented bool // 是否启用强制分片
SkipMimeScan bool // 是否跳过Mime扫描
ReportSelfMessage bool // 是否上报自身消息
UseSSOAddress bool // 是否使用服务器下发的新地址进行重连
LogForceNew bool // 是否在每次启动时强制创建全新的文件储存日志
FastStart bool // 是否为快速启动
PostFormat string // 上报格式 string or array
Proxy string // 存储 proxy_rewrite,用于设置代理
PasswordHash [16]byte // 存储QQ密码哈希供登录使用
AccountToken []byte // 存储 AccountToken 供登录使用
Account *config.Account // 账户配置
Reconnect *config.Reconnect // 重连配置
LogLevel string // 日志等级
LogAging = time.Hour * 24 * 365 // 日志时效
HeartbeatInterval = time.Second * 5 // 心跳间隔
Servers []map[string]yaml.Node // 连接服务列表
Database map[string]yaml.Node // 数据库列表
)
// Parse parse flags
func Parse() {
wd, _ := os.Getwd()
dc := path.Join(wd, "config.yml")
flag.StringVar(&LittleC, "c", dc, "configuration filename")
flag.BoolVar(&LittleD, "d", false, "running as a daemon")
flag.BoolVar(&LittleH, "h", false, "this Help")
flag.StringVar(&LittleWD, "w", "", "cover the working directory")
d := flag.Bool("D", false, "debug mode")
flag.Parse()
if *d {
Debug = true
}
}
// Init read config from yml file
func Init() {
conf := config.Parse(LittleC)
{ // bool config
if conf.Output.Debug {
Debug = true
}
IgnoreInvalidCQCode = conf.Message.IgnoreInvalidCQCode
SplitURL = conf.Message.FixURL
RemoveReplyAt = conf.Message.RemoveReplyAt
ExtraReplyData = conf.Message.ExtraReplyData
ForceFragmented = conf.Message.ForceFragment
SkipMimeScan = conf.Message.SkipMimeScan
ReportSelfMessage = conf.Message.ReportSelfMessage
UseSSOAddress = conf.Account.UseSSOAddress
}
{ // others
Proxy = conf.Message.ProxyRewrite
Account = conf.Account
Reconnect = conf.Account.ReLogin
Servers = conf.Servers
Database = conf.Database
LogLevel = conf.Output.LogLevel
if conf.Message.PostFormat != "string" && conf.Message.PostFormat != "array" {
log.Warnf("post-format 配置错误, 将自动使用 string")
PostFormat = "string"
} else {
PostFormat = conf.Message.PostFormat
}
if conf.Output.LogAging > 0 {
LogAging = time.Hour * 24 * time.Duration(conf.Output.LogAging)
}
if conf.Heartbeat.Interval > 0 {
HeartbeatInterval = time.Second * time.Duration(conf.Heartbeat.Interval)
}
if conf.Heartbeat.Disabled || conf.Heartbeat.Interval < 0 {
HeartbeatInterval = 0
}
}
}
// Help cli命令行-h的帮助提示
func Help() {
fmt.Printf(`go-cqhttp service
version: %s
Usage:
server [OPTIONS]
Options:
`, Version)
flag.PrintDefaults()
os.Exit(0)
}
// ResetWorkingDir 重设工作路径
func ResetWorkingDir() {
wd := LittleWD
args := make([]string, 0, len(os.Args))
for i := 1; i < len(os.Args); i++ {
if os.Args[i] == "-w" {
i++ // skip value field
} else if !strings.HasPrefix(os.Args[i], "-w") {
args = append(args, os.Args[i])
}
}
p, _ := filepath.Abs(os.Args[0])
proc := exec.Command(p, args...)
proc.Stdin = os.Stdin
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
proc.Dir = wd
err := proc.Run()
if err != nil {
panic(err)
}
os.Exit(0)
}

16
internal/base/version.go Normal file
View File

@ -0,0 +1,16 @@
package base
import "runtime/debug"
// Version go-cqhttp的版本信息在编译时使用ldflags进行覆盖
var Version = "unknown"
func init() {
if Version != "unknown" {
return
}
info, ok := debug.ReadBuildInfo()
if ok {
Version = info.Main.Version
}
}

130
internal/param/param.go Normal file
View File

@ -0,0 +1,130 @@
// Package param provide some util for param parse
package param
import (
"math"
"reflect"
"regexp"
"strings"
"sync"
"github.com/Mrs4s/MiraiGo/utils"
"github.com/segmentio/asm/base64"
"github.com/tidwall/gjson"
)
// EnsureBool 判断给定的p是否可表示为合法Bool类型,否则返回defaultVal
//
// 支持的合法类型有
//
// type bool
//
// type gjson.True or gjson.False
//
// type string "true","yes","1" or "false","no","0" (case insensitive)
func EnsureBool(p interface{}, defaultVal bool) bool {
var str string
if b, ok := p.(bool); ok {
return b
}
if j, ok := p.(gjson.Result); ok {
if !j.Exists() {
return defaultVal
}
switch j.Type { // nolint
case gjson.True:
return true
case gjson.False:
return false
case gjson.String:
str = j.Str
default:
return defaultVal
}
} else if s, ok := p.(string); ok {
str = s
}
str = strings.ToLower(str)
switch str {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return defaultVal
}
}
var (
// once lazy compile the reg
once sync.Once
// reg is splitURL regex pattern.
reg *regexp.Regexp
)
// SplitURL 将给定URL字符串分割为两部分用于URL预处理防止风控
func SplitURL(s string) []string {
once.Do(func() { // lazy init.
reg = regexp.MustCompile(`(?i)[a-z\d][-a-z\d]{0,62}(\.[a-z\d][-a-z\d]{0,62})+\.?`)
})
idx := reg.FindAllStringIndex(s, -1)
if len(idx) == 0 {
return []string{s}
}
var result []string
last := 0
for i := 0; i < len(idx); i++ {
if len(idx[i]) != 2 {
continue
}
m := int(math.Abs(float64(idx[i][0]-idx[i][1]))/1.5) + idx[i][0]
result = append(result, s[last:m])
last = m
}
result = append(result, s[last:])
return result
}
// Base64DecodeString decode base64 with avx2
// see https://github.com/segmentio/asm/issues/50
// avoid incorrect unsafe usage in origin library
func Base64DecodeString(s string) ([]byte, error) {
e := base64.StdEncoding
dst := make([]byte, e.DecodedLen(len(s)))
n, err := e.Decode(dst, utils.S2B(s))
return dst[:n], err
}
// SetAtDefault 在变量 variable 为默认值 defaultValue 的时候修改为 value
func SetAtDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if v.Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}
// SetExcludeDefault 在目标值 value 不为默认值 defaultValue 时修改 variable 为 value
func SetExcludeDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if reflect.Indirect(v2).Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}

View File

@ -0,0 +1,206 @@
// Package selfupdate 版本升级检查和自更新
package selfupdate
import (
"bufio"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/dustin/go-humanize"
"github.com/kardianos/osext"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
)
func readLine() (str string) {
console := bufio.NewReader(os.Stdin)
str, _ = console.ReadString('\n')
str = strings.TrimSpace(str)
return
}
func lastVersion() (string, error) {
r, err := global.GetBytes("https://api.github.com/repos/Mrs4s/go-cqhttp/releases/latest")
if err != nil {
return "", err
}
return gjson.GetBytes(r, "tag_name").Str, nil
}
// CheckUpdate 检查更新
func CheckUpdate() {
logrus.Infof("正在检查更新.")
if base.Version == "(devel)" {
logrus.Warnf("检查更新失败: 使用的 Actions 测试版或自编译版本.")
return
}
latest, err := lastVersion()
if err != nil {
logrus.Warnf("检查更新失败: %v", err)
return
}
if global.VersionNameCompare(base.Version, latest) {
logrus.Infof("当前有更新的 go-cqhttp 可供更新, 请前往 https://github.com/Mrs4s/go-cqhttp/releases 下载.")
logrus.Infof("当前版本: %v 最新版本: %v", base.Version, latest)
return
}
logrus.Infof("检查更新完成. 当前已运行最新版本.")
}
func binaryName() string {
goarch := runtime.GOARCH
if goarch == "arm" {
goarch += "v7"
}
ext := "tar.gz"
if runtime.GOOS == "windows" {
ext = "zip"
}
return fmt.Sprintf("go-cqhttp_%v_%v.%v", runtime.GOOS, goarch, ext)
}
func checksum(github, version string) []byte {
sumURL := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/go-cqhttp_checksums.txt", github, version)
closer, err := global.HTTPGetReadCloser(sumURL)
if err != nil {
return nil
}
rd := bufio.NewReader(closer)
for {
str, err := rd.ReadString('\n')
if err != nil {
break
}
str = strings.TrimSpace(str)
if strings.HasSuffix(str, binaryName()) {
sum, _ := hex.DecodeString(strings.TrimSuffix(str, " "+binaryName()))
return sum
}
}
return nil
}
func wait() {
logrus.Info("按 Enter 继续....")
readLine()
os.Exit(0)
}
// SelfUpdate 自更新
func SelfUpdate(github string) {
if github == "" {
github = "https://github.com"
}
logrus.Infof("正在检查更新.")
latest, err := lastVersion()
if err != nil {
logrus.Warnf("获取最新版本失败: %v", err)
wait()
}
url := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/%v", github, latest, binaryName())
if base.Version == latest {
logrus.Info("当前版本已经是最新版本!")
wait()
}
logrus.Info("当前最新版本为 ", latest)
logrus.Warn("是否更新(y/N): ")
r := strings.TrimSpace(readLine())
if r != "y" && r != "Y" {
logrus.Warn("已取消更新!")
wait()
}
logrus.Info("正在更新,请稍等...")
sum := checksum(github, latest)
if sum != nil {
err = update(url, sum)
if err != nil {
logrus.Error("更新失败: ", err)
} else {
logrus.Info("更新成功!")
}
} else {
logrus.Error("checksum 失败!")
}
wait()
}
// writeSumCounter 写入量计算实例
type writeSumCounter struct {
total uint64
hash hash.Hash
}
// Write 方法将写入的byte长度追加至写入的总长度Total中
func (wc *writeSumCounter) Write(p []byte) (int, error) {
n := len(p)
wc.total += uint64(n)
wc.hash.Write(p)
fmt.Printf("\r ")
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.total))
return n, nil
}
// FromStream copy form getlantern/go-update
func fromStream(updateWith io.Reader) (err error, errRecover error) {
updatePath, err := osext.Executable()
if err != nil {
return
}
// get the directory the executable exists in
updateDir := filepath.Dir(updatePath)
filename := filepath.Base(updatePath)
// Copy the contents of of newbinary to a the new executable file
newPath := filepath.Join(updateDir, fmt.Sprintf(".%s.new", filename))
fp, err := os.OpenFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return
}
// We won't log this error, because it's always going to happen.
defer func() { _ = fp.Close() }()
if _, err = io.Copy(fp, bufio.NewReader(updateWith)); err != nil {
logrus.Errorf("Unable to copy data: %v\n", err)
}
// if we don't call fp.Close(), windows won't let us move the new executable
// because the file will still be "in use"
if err := fp.Close(); err != nil {
logrus.Errorf("Unable to close file: %v\n", err)
}
// this is where we'll move the executable to so that we can swap in the updated replacement
oldPath := filepath.Join(updateDir, fmt.Sprintf(".%s.old", filename))
// delete any existing old exec file - this is necessary on Windows for two reasons:
// 1. after a successful update, Windows can't remove the .old file because the process is still running
// 2. windows rename operations fail if the destination file already exists
_ = os.Remove(oldPath)
// move the existing executable to a new file in the same directory
err = os.Rename(updatePath, oldPath)
if err != nil {
return
}
// move the new executable in to become the new program
err = os.Rename(newPath, updatePath)
if err != nil {
// copy unsuccessful
errRecover = os.Rename(oldPath, updatePath)
} else {
// copy successful, remove the old binary
_ = os.Remove(oldPath)
}
return
}

View File

@ -1,7 +1,7 @@
//go:build !windows //go:build !windows
// +build !windows // +build !windows
package update package selfupdate
import ( import (
"archive/tar" "archive/tar"
@ -14,21 +14,21 @@ import (
"net/http" "net/http"
) )
// Update go-cqhttp自我更新 // update go-cqhttp自我更新
func Update(url string, sum []byte) error { func update(url string, sum []byte) error {
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
wc := WriteSumCounter{ wc := writeSumCounter{
Hash: sha256.New(), hash: sha256.New(),
} }
rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc)) rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
if err != nil { if err != nil {
return err return err
} }
if !bytes.Equal(wc.Hash.Sum(nil), sum) { if !bytes.Equal(wc.hash.Sum(nil), sum) {
return errors.New("文件已损坏") return errors.New("文件已损坏")
} }
gr, err := gzip.NewReader(bytes.NewReader(rsp)) gr, err := gzip.NewReader(bytes.NewReader(rsp))
@ -42,7 +42,7 @@ func Update(url string, sum []byte) error {
return err return err
} }
if header.Name == "go-cqhttp" { if header.Name == "go-cqhttp" {
err, _ := FromStream(tr) err, _ := fromStream(tr)
fmt.Println() fmt.Println()
if err != nil { if err != nil {
return err return err

View File

@ -1,4 +1,4 @@
package update package selfupdate
import ( import (
"archive/zip" "archive/zip"
@ -10,21 +10,21 @@ import (
"net/http" "net/http"
) )
// Update go-cqhttp自我更新 // update go-cqhttp自我更新
func Update(url string, sum []byte) error { func update(url string, sum []byte) error {
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
wc := WriteSumCounter{ wc := writeSumCounter{
Hash: sha256.New(), hash: sha256.New(),
} }
rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc)) rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
if err != nil { if err != nil {
return err return err
} }
if !bytes.Equal(wc.Hash.Sum(nil), sum) { if !bytes.Equal(wc.hash.Sum(nil), sum) {
return errors.New("文件已损坏") return errors.New("文件已损坏")
} }
reader, _ := zip.NewReader(bytes.NewReader(rsp), resp.ContentLength) reader, _ := zip.NewReader(bytes.NewReader(rsp), resp.ContentLength)
@ -32,7 +32,7 @@ func Update(url string, sum []byte) error {
if err != nil { if err != nil {
return err return err
} }
err, _ = FromStream(file) err, _ = fromStream(file)
fmt.Println() fmt.Println()
if err != nil { if err != nil {
return err return err

View File

@ -18,13 +18,13 @@ import (
var console = bufio.NewReader(os.Stdin) var console = bufio.NewReader(os.Stdin)
var readLine = func() (str string) { func readLine() (str string) {
str, _ = console.ReadString('\n') str, _ = console.ReadString('\n')
str = strings.TrimSpace(str) str = strings.TrimSpace(str)
return return
} }
var readLineTimeout = func(t time.Duration, de string) (str string) { func readLineTimeout(t time.Duration, de string) (str string) {
r := make(chan string) r := make(chan string)
go func() { go func() {
select { select {

411
main.go
View File

@ -1,105 +1,69 @@
package main package main
import ( import (
"bufio"
"crypto/aes" "crypto/aes"
"crypto/md5" "crypto/md5"
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"flag"
"fmt"
"os" "os"
"os/exec"
"path" "path"
"path/filepath"
"runtime"
"strings"
"sync" "sync"
"time" "time"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/codec"
"github.com/Mrs4s/go-cqhttp/global/config"
"github.com/Mrs4s/go-cqhttp/global/terminal"
"github.com/Mrs4s/go-cqhttp/global/update"
"github.com/Mrs4s/go-cqhttp/server"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/guonaihong/gout" para "github.com/fumiama/go-hide-param"
rotatelogs "github.com/lestrrat-go/file-rotatelogs" rotatelogs "github.com/lestrrat-go/file-rotatelogs"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/pbkdf2"
"golang.org/x/term" "golang.org/x/term"
_ "github.com/Mrs4s/go-cqhttp/modules/mime" // mime检查模块
"github.com/Mrs4s/go-cqhttp/modules/servers"
_ "github.com/Mrs4s/go-cqhttp/modules/silk" // silk编码模块
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/terminal"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/selfupdate"
"github.com/Mrs4s/go-cqhttp/server"
) )
var (
conf *config.Config
isFastStart = false
// PasswordHash 存储QQ密码哈希供登录使用
PasswordHash [16]byte
// AccountToken 存储AccountToken供登录使用
AccountToken []byte
// 允许通过配置文件设置的状态列表 // 允许通过配置文件设置的状态列表
allowStatus = [...]client.UserOnlineStatus{ var allowStatus = [...]client.UserOnlineStatus{
client.StatusOnline, client.StatusAway, client.StatusInvisible, client.StatusBusy, client.StatusOnline, client.StatusAway, client.StatusInvisible, client.StatusBusy,
client.StatusListening, client.StatusConstellation, client.StatusWeather, client.StatusMeetSpring, client.StatusListening, client.StatusConstellation, client.StatusWeather, client.StatusMeetSpring,
client.StatusTimi, client.StatusEatChicken, client.StatusLoving, client.StatusWangWang, client.StatusCookedRice, client.StatusTimi, client.StatusEatChicken, client.StatusLoving, client.StatusWangWang, client.StatusCookedRice,
client.StatusStudy, client.StatusStayUp, client.StatusPlayBall, client.StatusSignal, client.StatusStudyOnline, client.StatusStudy, client.StatusStayUp, client.StatusPlayBall, client.StatusSignal, client.StatusStudyOnline,
client.StatusGaming, client.StatusVacationing, client.StatusWatchingTV, client.StatusFitness, client.StatusGaming, client.StatusVacationing, client.StatusWatchingTV, client.StatusFitness,
} }
)
func main() { func main() {
c := flag.String("c", config.DefaultConfigFile, "configuration filename default is config.hjson") base.Parse()
d := flag.Bool("d", false, "running as a daemon")
h := flag.Bool("h", false, "this help")
wd := flag.String("w", "", "cover the working directory")
debug := flag.Bool("D", false, "debug mode")
flag.Parse()
switch { switch {
case *h: case base.LittleH:
help() base.Help()
case *d: case base.LittleD:
server.Daemon() server.Daemon()
case *wd != "": case base.LittleWD != "":
resetWorkDir(*wd) base.ResetWorkingDir()
}
// 通过-c 参数替换 配置文件路径
config.DefaultConfigFile = *c
conf = config.Get()
if *debug {
conf.Output.Debug = true
}
if conf.Output.Debug {
log.SetReportCaller(true)
codec.Debug = true
} }
base.Init()
rotateOptions := []rotatelogs.Option{ rotateOptions := []rotatelogs.Option{
rotatelogs.WithRotationTime(time.Hour * 24), rotatelogs.WithRotationTime(time.Hour * 24),
} }
rotateOptions = append(rotateOptions, rotatelogs.WithMaxAge(base.LogAging))
if conf.Output.LogAging > 0 { if base.LogForceNew {
rotateOptions = append(rotateOptions, rotatelogs.WithMaxAge(time.Hour*24*time.Duration(conf.Output.LogAging)))
}
if conf.Output.LogForceNew {
rotateOptions = append(rotateOptions, rotatelogs.ForceNewFile()) rotateOptions = append(rotateOptions, rotatelogs.ForceNewFile())
} }
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotateOptions...) w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotateOptions...)
if err != nil { if err != nil {
log.Errorf("rotatelogs init err: %v", err) log.Errorf("rotatelogs init err: %v", err)
panic(err) panic(err)
} }
log.AddHook(global.NewLocalHook(w, global.LogFormat{}, global.GetLogLevel(base.LogLevel)...))
log.AddHook(global.NewLocalHook(w, global.LogFormat{}, global.GetLogLevel(conf.Output.LogLevel)...))
mkCacheDir := func(path string, _type string) { mkCacheDir := func(path string, _type string) {
if !global.PathExists(path) { if !global.PathExists(path) {
@ -120,36 +84,43 @@ func main() {
switch arg[i] { switch arg[i] {
case "update": case "update":
if len(arg) > i+1 { if len(arg) > i+1 {
selfUpdate(arg[i+1]) selfupdate.SelfUpdate(arg[i+1])
} else { } else {
selfUpdate("") selfupdate.SelfUpdate("")
} }
case "key": case "key":
if len(arg) > i+1 { p := i + 1
byteKey = []byte(arg[i+1]) if len(arg) > p {
byteKey = []byte(arg[p])
para.Hide(p)
} }
case "faststart": case "faststart":
isFastStart = true base.FastStart = true
} }
} }
} }
if terminal.RunningByDoubleClick() && !isFastStart {
log.Warning("警告: 强烈不推荐通过双击直接运行本程序, 这将导致一些非预料的后果.")
log.Warning("将等待10s后启动")
time.Sleep(time.Second * 10)
}
if (conf.Account.Uin == 0 || (conf.Account.Password == "" && !conf.Account.Encrypt)) && !global.PathExists("session.token") { if !base.FastStart && terminal.RunningByDoubleClick() {
err := terminal.NoMoreDoubleClick()
if err != nil {
log.Errorf("遇到错误: %v", err)
time.Sleep(time.Second * 5)
}
return
}
if (base.Account.Uin == 0 || (base.Account.Password == "" && !base.Account.Encrypt)) && !global.PathExists("session.token") {
log.Warn("账号密码未配置, 将使用二维码登录.") log.Warn("账号密码未配置, 将使用二维码登录.")
if !isFastStart { if !base.FastStart {
log.Warn("将在 5秒 后继续.") log.Warn("将在 5秒 后继续.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
} }
} }
log.Info("当前版本:", coolq.Version) log.Info("当前版本:", base.Version)
if conf.Output.Debug { if base.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
log.SetReportCaller(true)
log.Warnf("已开启Debug模式.") log.Warnf("已开启Debug模式.")
log.Debugf("开发交流群: 192548878") log.Debugf("开发交流群: 192548878")
} }
@ -166,22 +137,22 @@ func main() {
} }
} }
if conf.Account.Encrypt { if base.Account.Encrypt {
if !global.PathExists("password.encrypt") { if !global.PathExists("password.encrypt") {
if conf.Account.Password == "" { if base.Account.Password == "" {
log.Error("无法进行加密,请在配置文件中的添加密码后重新启动.") log.Error("无法进行加密,请在配置文件中的添加密码后重新启动.")
readLine() readLine()
os.Exit(0) os.Exit(0)
} }
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)") log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd())) byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
PasswordHash = md5.Sum([]byte(conf.Account.Password)) base.PasswordHash = md5.Sum([]byte(base.Account.Password))
_ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(PasswordHash[:], byteKey)), 0o644) _ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(base.PasswordHash[:], byteKey)), 0o644)
log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.") log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
readLine() readLine()
os.Exit(0) os.Exit(0)
} else { } else {
if conf.Account.Password != "" { if base.Account.Password != "" {
log.Error("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.") log.Error("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
readLine() readLine()
os.Exit(0) os.Exit(0)
@ -213,12 +184,12 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码") log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
} }
copy(PasswordHash[:], ph) copy(base.PasswordHash[:], ph)
} }
} else { } else if len(base.Account.Password) > 0 {
PasswordHash = md5.Sum([]byte(conf.Account.Password)) base.PasswordHash = md5.Sum([]byte(base.Account.Password))
} }
if !isFastStart { if !base.FastStart {
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.") log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
} }
@ -239,21 +210,20 @@ func main() {
return "未知" return "未知"
}()) }())
cli = newClient() cli = newClient()
global.Proxy = conf.Message.ProxyRewrite isQRCodeLogin := (base.Account.Uin == 0 || len(base.Account.Password) == 0) && !base.Account.Encrypt
isQRCodeLogin := (conf.Account.Uin == 0 || len(conf.Account.Password) == 0) && !conf.Account.Encrypt
isTokenLogin := false isTokenLogin := false
saveToken := func() { saveToken := func() {
AccountToken = cli.GenToken() base.AccountToken = cli.GenToken()
_ = os.WriteFile("session.token", AccountToken, 0o644) _ = os.WriteFile("session.token", base.AccountToken, 0o644)
} }
if global.PathExists("session.token") { if global.PathExists("session.token") {
token, err := os.ReadFile("session.token") token, err := os.ReadFile("session.token")
if err == nil { if err == nil {
if conf.Account.Uin != 0 { if base.Account.Uin != 0 {
r := binary.NewReader(token) r := binary.NewReader(token)
cu := r.ReadInt64() cu := r.ReadInt64()
if cu != conf.Account.Uin { if cu != base.Account.Uin {
log.Warnf("警告: 配置文件内的QQ号 (%v) 与缓存内的QQ号 (%v) 不相同", conf.Account.Uin, cu) log.Warnf("警告: 配置文件内的QQ号 (%v) 与缓存内的QQ号 (%v) 不相同", base.Account.Uin, cu)
log.Warnf("1. 使用会话缓存继续.") log.Warnf("1. 使用会话缓存继续.")
log.Warnf("2. 删除会话缓存并重启.") log.Warnf("2. 删除会话缓存并重启.")
log.Warnf("请选择: (5秒后自动选1)") log.Warnf("请选择: (5秒后自动选1)")
@ -277,9 +247,9 @@ func main() {
} }
} }
} }
if conf.Account.Uin != 0 && PasswordHash != [16]byte{} { if base.Account.Uin != 0 && base.PasswordHash != [16]byte{} {
cli.Uin = conf.Account.Uin cli.Uin = base.Account.Uin
cli.PasswordMd5 = PasswordHash cli.PasswordMd5 = base.PasswordHash
} }
if !isTokenLogin { if !isTokenLogin {
if !isQRCodeLogin { if !isQRCodeLogin {
@ -302,23 +272,28 @@ func main() {
return return
} }
log.Warnf("Bot已离线: %v", e.Message) log.Warnf("Bot已离线: %v", e.Message)
time.Sleep(time.Second * time.Duration(conf.Account.ReLogin.Delay)) time.Sleep(time.Second * time.Duration(base.Reconnect.Delay))
for { for {
if conf.Account.ReLogin.Disabled { if base.Reconnect.Disabled {
log.Warnf("未启用自动重连, 将退出.")
os.Exit(1) os.Exit(1)
} }
if times > conf.Account.ReLogin.MaxTimes && conf.Account.ReLogin.MaxTimes != 0 { if times > base.Reconnect.MaxTimes && base.Reconnect.MaxTimes != 0 {
log.Fatalf("Bot重连次数超过限制, 停止") log.Fatalf("Bot重连次数超过限制, 停止")
} }
times++ times++
if conf.Account.ReLogin.Interval > 0 { if base.Reconnect.Interval > 0 {
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", conf.Account.ReLogin.Interval, times, conf.Account.ReLogin.MaxTimes) log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", base.Reconnect.Interval, times, base.Reconnect.MaxTimes)
time.Sleep(time.Second * time.Duration(conf.Account.ReLogin.Interval)) time.Sleep(time.Second * time.Duration(base.Reconnect.Interval))
} else { } else {
time.Sleep(time.Second) time.Sleep(time.Second)
} }
if cli.Online {
log.Infof("登录已完成")
break
}
log.Warnf("尝试重连...") log.Warnf("尝试重连...")
err := cli.TokenLogin(AccountToken) err := cli.TokenLogin(base.AccountToken)
if err == nil { if err == nil {
saveToken() saveToken()
return return
@ -346,70 +321,16 @@ func main() {
log.Infof("开始加载群列表...") log.Infof("开始加载群列表...")
global.Check(cli.ReloadGroupList(), true) global.Check(cli.ReloadGroupList(), true)
log.Infof("共加载 %v 个群.", len(cli.GroupList)) log.Infof("共加载 %v 个群.", len(cli.GroupList))
if conf.Account.Status >= int32(len(allowStatus)) || conf.Account.Status < 0 { if uint(base.Account.Status) >= uint(len(allowStatus)) {
conf.Account.Status = 0 base.Account.Status = 0
}
cli.SetOnlineStatus(allowStatus[int(conf.Account.Status)])
bot := coolq.NewQQBot(cli, conf)
_ = bot.Client
if conf.Message.PostFormat != "string" && conf.Message.PostFormat != "array" {
log.Warnf("post-format 配置错误, 将自动使用 string")
coolq.SetMessageFormat("string")
} else {
coolq.SetMessageFormat(conf.Message.PostFormat)
}
coolq.IgnoreInvalidCQCode = conf.Message.IgnoreInvalidCQCode
coolq.SplitURL = conf.Message.FixURL
coolq.ForceFragmented = conf.Message.ForceFragment
coolq.RemoveReplyAt = conf.Message.RemoveReplyAt
coolq.ExtraReplyData = conf.Message.ExtraReplyData
coolq.SkipMimeScan = conf.Message.SkipMimeScan
for _, m := range conf.Servers {
if h, ok := m["http"]; ok {
hc := new(config.HTTPServer)
if err := h.Decode(hc); err != nil {
log.Warn("读取http配置失败 :", err)
} else {
go server.RunHTTPServerAndClients(bot, hc)
}
}
if s, ok := m["ws"]; ok {
sc := new(config.WebsocketServer)
if err := s.Decode(sc); err != nil {
log.Warn("读取正向Websocket配置失败 :", err)
} else {
go server.RunWebSocketServer(bot, sc)
}
}
if c, ok := m["ws-reverse"]; ok {
rc := new(config.WebsocketReverse)
if err := c.Decode(rc); err != nil {
log.Warn("读取反向Websocket配置失败 :", err)
} else {
go server.RunWebSocketClient(bot, rc)
}
}
if p, ok := m["pprof"]; ok {
pc := new(config.PprofServer)
if err := p.Decode(pc); err != nil {
log.Warn("读取pprof配置失败 :", err)
} else {
go server.RunPprofServer(pc)
}
}
if p, ok := m["lambda"]; ok {
lc := new(config.LambdaServer)
if err := p.Decode(lc); err != nil {
log.Warn("读取pprof配置失败 :", err)
} else {
go server.RunLambdaClient(bot, lc)
}
}
} }
cli.SetOnlineStatus(allowStatus[base.Account.Status])
servers.Run(coolq.NewQQBot(cli))
log.Info("资源初始化完成, 开始处理信息.") log.Info("资源初始化完成, 开始处理信息.")
log.Info("アトリは、高性能ですから!") log.Info("アトリは、高性能ですから!")
go checkUpdate() go selfupdate.CheckUpdate()
<-global.SetupMainSignalHandler() <-global.SetupMainSignalHandler()
} }
@ -445,178 +366,10 @@ func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, erro
return result, nil return result, nil
} }
func checkUpdate() {
log.Infof("正在检查更新.")
if coolq.Version == "(devel)" {
log.Warnf("检查更新失败: 使用的 Actions 测试版或自编译版本.")
return
}
var res string
if err := gout.GET("https://api.github.com/repos/Mrs4s/go-cqhttp/releases/latest").BindBody(&res).Do(); err != nil {
log.Warnf("检查更新失败: %v", err)
return
}
info := gjson.Parse(res)
if global.VersionNameCompare(coolq.Version, info.Get("tag_name").Str) {
log.Infof("当前有更新的 go-cqhttp 可供更新, 请前往 https://github.com/Mrs4s/go-cqhttp/releases 下载.")
log.Infof("当前版本: %v 最新版本: %v", coolq.Version, info.Get("tag_name").Str)
return
}
log.Infof("检查更新完成. 当前已运行最新版本.")
}
func selfUpdate(imageURL string) {
log.Infof("正在检查更新.")
var res, r string
if err := gout.GET("https://api.github.com/repos/Mrs4s/go-cqhttp/releases/latest").BindBody(&res).Do(); err != nil {
log.Warnf("检查更新失败: %v", err)
return
}
info := gjson.Parse(res)
version := info.Get("tag_name").Str
if coolq.Version == version {
log.Info("当前版本已经是最新版本!")
goto wait
}
log.Info("当前最新版本为 ", version)
log.Warn("是否更新(y/N): ")
r = strings.TrimSpace(readLine())
if r != "y" && r != "Y" {
log.Warn("已取消更新!")
} else {
log.Info("正在更新,请稍等...")
sumURL := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/go-cqhttp_checksums.txt",
func() string {
if imageURL != "" {
return imageURL
}
return "https://github.com"
}(), version)
closer, err := global.HTTPGetReadCloser(sumURL)
if err != nil {
log.Error("更新失败: ", err)
goto wait
}
rd := bufio.NewReader(closer)
binaryName := fmt.Sprintf("go-cqhttp_%v_%v.%v", runtime.GOOS, func() string {
if runtime.GOARCH == "arm" {
return "armv7"
}
return runtime.GOARCH
}(), func() string {
if runtime.GOOS == "windows" {
return "zip"
}
return "tar.gz"
}())
var sum []byte
for {
str, err := rd.ReadString('\n')
if err != nil {
break
}
str = strings.TrimSpace(str)
if strings.HasSuffix(str, binaryName) {
sum, _ = hex.DecodeString(strings.TrimSuffix(str, " "+binaryName))
break
}
}
url := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/%v",
func() string {
if imageURL != "" {
return imageURL
}
return "https://github.com"
}(), version, binaryName)
err = update.Update(url, sum)
if err != nil {
log.Error("更新失败: ", err)
} else {
log.Info("更新成功!")
}
}
wait:
log.Info("按 Enter 继续....")
readLine()
os.Exit(0)
}
/*
func restart(args []string) {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
file, err := exec.LookPath(args[0])
if err != nil {
log.Errorf("重启失败:%s", err.Error())
return
}
path, err := filepath.Abs(file)
if err != nil {
log.Errorf("重启失败:%s", err.Error())
}
args = append([]string{"/c", "start ", path, "faststart"}, args[1:]...)
cmd = &exec.Cmd{
Path: "cmd.exe",
Args: args,
Stderr: os.Stderr,
Stdout: os.Stdout,
}
} else {
args = append(args, "faststart")
cmd = &exec.Cmd{
Path: args[0],
Args: args,
Stderr: os.Stderr,
Stdout: os.Stdout,
}
}
_ = cmd.Start()
}
*/
// help cli命令行-h的帮助提示
func help() {
fmt.Printf(`go-cqhttp service
version: %s
Usage:
server [OPTIONS]
Options:
`, coolq.Version)
flag.PrintDefaults()
os.Exit(0)
}
func resetWorkDir(wd string) {
args := make([]string, 0, len(os.Args))
for i := 1; i < len(os.Args); i++ {
if os.Args[i] == "-w" {
i++ // skip value field
} else if !strings.HasPrefix(os.Args[i], "-w") {
args = append(args, os.Args[i])
}
}
p, _ := filepath.Abs(os.Args[0])
proc := exec.Command(p, args...)
proc.Stdin = os.Stdin
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
proc.Dir = wd
err := proc.Run()
if err != nil {
panic(err)
}
os.Exit(0)
}
func newClient() *client.QQClient { func newClient() *client.QQClient {
c := client.NewClientEmpty() c := client.NewClientEmpty()
c.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool { c.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool {
if !conf.Account.UseSSOAddress { if !base.UseSSOAddress {
log.Infof("收到服务器地址更新通知, 根据配置文件已忽略.") log.Infof("收到服务器地址更新通知, 根据配置文件已忽略.")
return false return false
} }
@ -627,7 +380,7 @@ func newClient() *client.QQClient {
log.Infof("检测到 address.txt 文件. 将覆盖目标IP.") log.Infof("检测到 address.txt 文件. 将覆盖目标IP.")
addr := global.ReadAddrFile("address.txt") addr := global.ReadAddrFile("address.txt")
if len(addr) > 0 { if len(addr) > 0 {
cli.SetCustomServer(addr) c.SetCustomServer(addr)
} }
log.Infof("读取到 %v 个自定义地址.", len(addr)) log.Infof("读取到 %v 个自定义地址.", len(addr))
} }

View File

@ -6,12 +6,10 @@ import (
_ "embed" // embed the default config file _ "embed" // embed the default config file
"fmt" "fmt"
"os" "os"
"path"
"strconv" "strconv"
"strings" "strings"
"sync"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/internal/param"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -21,27 +19,27 @@ import (
//go:embed default_config.yml //go:embed default_config.yml
var defaultConfig string var defaultConfig string
var currentPath = getCurrentPath() // Reconnect 重连配置
type Reconnect struct {
// DefaultConfigFile 默认配置文件路径
var DefaultConfigFile = path.Join(currentPath, "config.yml")
// Config 总配置文件
type Config struct {
Account struct {
Uin int64 `yaml:"uin"`
Password string `yaml:"password"`
Encrypt bool `yaml:"encrypt"`
Status int32 `yaml:"status"`
ReLogin struct {
Disabled bool `yaml:"disabled"` Disabled bool `yaml:"disabled"`
Delay uint `yaml:"delay"` Delay uint `yaml:"delay"`
MaxTimes uint `yaml:"max-times"` MaxTimes uint `yaml:"max-times"`
Interval int `yaml:"interval"` Interval int `yaml:"interval"`
} }
UseSSOAddress bool `yaml:"use-sso-address"`
} `yaml:"account"`
// Account 账号配置
type Account struct {
Uin int64 `yaml:"uin"`
Password string `yaml:"password"`
Encrypt bool `yaml:"encrypt"`
Status int `yaml:"status"`
ReLogin *Reconnect `yaml:"relogin"`
UseSSOAddress bool `yaml:"use-sso-address"`
}
// Config 总配置文件
type Config struct {
Account *Account `yaml:"account"`
Heartbeat struct { Heartbeat struct {
Disabled bool `yaml:"disabled"` Disabled bool `yaml:"disabled"`
Interval int `yaml:"interval"` Interval int `yaml:"interval"`
@ -49,10 +47,10 @@ type Config struct {
Message struct { Message struct {
PostFormat string `yaml:"post-format"` PostFormat string `yaml:"post-format"`
ProxyRewrite string `yaml:"proxy-rewrite"`
IgnoreInvalidCQCode bool `yaml:"ignore-invalid-cqcode"` IgnoreInvalidCQCode bool `yaml:"ignore-invalid-cqcode"`
ForceFragment bool `yaml:"force-fragment"` ForceFragment bool `yaml:"force-fragment"`
FixURL bool `yaml:"fix-url"` FixURL bool `yaml:"fix-url"`
ProxyRewrite string `yaml:"proxy-rewrite"`
ReportSelfMessage bool `yaml:"report-self-message"` ReportSelfMessage bool `yaml:"report-self-message"`
RemoveReplyAt bool `yaml:"remove-reply-at"` RemoveReplyAt bool `yaml:"remove-reply-at"`
ExtraReplyData bool `yaml:"extra-reply-data"` ExtraReplyData bool `yaml:"extra-reply-data"`
@ -139,28 +137,22 @@ type LevelDBConfig struct {
Enable bool `yaml:"enable"` Enable bool `yaml:"enable"`
} }
var ( // Parse 从默认配置文件路径中获取
config *Config func Parse(path string) *Config {
once sync.Once fromEnv := os.Getenv("GCQ_UIN") != ""
)
// Get 从默认配置文件路径中获取 file, err := os.Open(path)
func Get() *Config { config := &Config{}
once.Do(func() {
hasEnvironmentConf := os.Getenv("GCQ_UIN") != ""
file, err := os.Open(DefaultConfigFile)
config = &Config{}
if err == nil { if err == nil {
defer func() { _ = file.Close() }() defer func() { _ = file.Close() }()
if err = yaml.NewDecoder(file).Decode(config); err != nil && !hasEnvironmentConf { if err = yaml.NewDecoder(file).Decode(config); err != nil && !fromEnv {
log.Fatal("配置文件不合法!", err) log.Fatal("配置文件不合法!", err)
} }
} else if !hasEnvironmentConf { } else if !fromEnv {
generateConfig() generateConfig()
os.Exit(0) os.Exit(0)
} }
if fromEnv {
// type convert tools // type convert tools
toInt64 := func(str string) int64 { toInt64 := func(str string) int64 {
i, _ := strconv.ParseInt(str, 10, 64) i, _ := strconv.ParseInt(str, 10, 64)
@ -168,13 +160,16 @@ func Get() *Config {
} }
// load config from environment variable // load config from environment variable
global.SetAtDefault(&config.Account.Uin, toInt64(os.Getenv("GCQ_UIN")), int64(0)) param.SetAtDefault(&config.Account.Uin, toInt64(os.Getenv("GCQ_UIN")), int64(0))
global.SetAtDefault(&config.Account.Password, os.Getenv("GCQ_PWD"), "") param.SetAtDefault(&config.Account.Password, os.Getenv("GCQ_PWD"), "")
global.SetAtDefault(&config.Account.Status, int32(toInt64(os.Getenv("GCQ_STATUS"))), int32(0)) param.SetAtDefault(&config.Account.Status, int32(toInt64(os.Getenv("GCQ_STATUS"))), int32(0))
global.SetAtDefault(&config.Account.ReLogin.Disabled, !global.EnsureBool(os.Getenv("GCQ_RELOGIN"), false), false) param.SetAtDefault(&config.Account.ReLogin.Disabled, !param.EnsureBool(os.Getenv("GCQ_RELOGIN_DISABLED"), true), false)
global.SetAtDefault(&config.Account.ReLogin.Delay, uint(toInt64(os.Getenv("GCQ_RELOGIN_DELAY"))), uint(0)) param.SetAtDefault(&config.Account.ReLogin.Delay, uint(toInt64(os.Getenv("GCQ_RELOGIN_DELAY"))), uint(0))
global.SetAtDefault(&config.Account.ReLogin.MaxTimes, uint(toInt64(os.Getenv("GCQ_RELOGIN_MAX_TIMES"))), uint(0)) param.SetAtDefault(&config.Account.ReLogin.MaxTimes, uint(toInt64(os.Getenv("GCQ_RELOGIN_MAX_TIMES"))), uint(0))
dbConf := &LevelDBConfig{Enable: global.EnsureBool(os.Getenv("GCQ_LEVELDB"), true)} dbConf := &LevelDBConfig{Enable: param.EnsureBool(os.Getenv("GCQ_LEVELDB"), true)}
if config.Database == nil {
config.Database = make(map[string]yaml.Node)
}
config.Database["leveldb"] = func() yaml.Node { config.Database["leveldb"] = func() yaml.Node {
n := &yaml.Node{} n := &yaml.Node{}
_ = n.Encode(dbConf) _ = n.Encode(dbConf)
@ -190,9 +185,9 @@ func Get() *Config {
AccessToken: accessTokenEnv, AccessToken: accessTokenEnv,
}, },
} }
global.SetExcludeDefault(&httpConf.Disabled, global.EnsureBool(os.Getenv("GCQ_HTTP_DISABLE"), false), false) param.SetExcludeDefault(&httpConf.Disabled, param.EnsureBool(os.Getenv("GCQ_HTTP_DISABLE"), false), false)
global.SetExcludeDefault(&httpConf.Host, os.Getenv("GCQ_HTTP_HOST"), "") param.SetExcludeDefault(&httpConf.Host, os.Getenv("GCQ_HTTP_HOST"), "")
global.SetExcludeDefault(&httpConf.Port, int(toInt64(os.Getenv("GCQ_HTTP_PORT"))), 0) param.SetExcludeDefault(&httpConf.Port, int(toInt64(os.Getenv("GCQ_HTTP_PORT"))), 0)
if os.Getenv("GCQ_HTTP_POST_URL") != "" { if os.Getenv("GCQ_HTTP_POST_URL") != "" {
httpConf.Post = append(httpConf.Post, struct { httpConf.Post = append(httpConf.Post, struct {
URL string `yaml:"url"` URL string `yaml:"url"`
@ -211,9 +206,9 @@ func Get() *Config {
AccessToken: accessTokenEnv, AccessToken: accessTokenEnv,
}, },
} }
global.SetExcludeDefault(&wsServerConf.Disabled, global.EnsureBool(os.Getenv("GCQ_WS_DISABLE"), false), false) param.SetExcludeDefault(&wsServerConf.Disabled, param.EnsureBool(os.Getenv("GCQ_WS_DISABLE"), false), false)
global.SetExcludeDefault(&wsServerConf.Host, os.Getenv("GCQ_WS_HOST"), "") param.SetExcludeDefault(&wsServerConf.Host, os.Getenv("GCQ_WS_HOST"), "")
global.SetExcludeDefault(&wsServerConf.Port, int(toInt64(os.Getenv("GCQ_WS_PORT"))), 0) param.SetExcludeDefault(&wsServerConf.Port, int(toInt64(os.Getenv("GCQ_WS_PORT"))), 0)
_ = node.Encode(wsServerConf) _ = node.Encode(wsServerConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"ws": *node}) config.Servers = append(config.Servers, map[string]yaml.Node{"ws": *node})
} }
@ -224,26 +219,17 @@ func Get() *Config {
AccessToken: accessTokenEnv, AccessToken: accessTokenEnv,
}, },
} }
global.SetExcludeDefault(&rwsConf.Disabled, global.EnsureBool(os.Getenv("GCQ_RWS_DISABLE"), false), false) param.SetExcludeDefault(&rwsConf.Disabled, param.EnsureBool(os.Getenv("GCQ_RWS_DISABLE"), false), false)
global.SetExcludeDefault(&rwsConf.API, os.Getenv("GCQ_RWS_API"), "") param.SetExcludeDefault(&rwsConf.API, os.Getenv("GCQ_RWS_API"), "")
global.SetExcludeDefault(&rwsConf.Event, os.Getenv("GCQ_RWS_EVENT"), "") param.SetExcludeDefault(&rwsConf.Event, os.Getenv("GCQ_RWS_EVENT"), "")
global.SetExcludeDefault(&rwsConf.Universal, os.Getenv("GCQ_RWS_UNIVERSAL"), "") param.SetExcludeDefault(&rwsConf.Universal, os.Getenv("GCQ_RWS_UNIVERSAL"), "")
_ = node.Encode(rwsConf) _ = node.Encode(rwsConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"ws-reverse": *node}) config.Servers = append(config.Servers, map[string]yaml.Node{"ws-reverse": *node})
} }
}) }
return config return config
} }
// getCurrentPath 获取当前文件的路径直接返回string
func getCurrentPath() string {
cwd, e := os.Getwd()
if e != nil {
panic(e)
}
return cwd
}
// generateConfig 生成配置文件 // generateConfig 生成配置文件
func generateConfig() { func generateConfig() {
fmt.Println("未找到配置文件,正在为您生成配置文件中!") fmt.Println("未找到配置文件,正在为您生成配置文件中!")

70
modules/mime/mime.go Normal file
View File

@ -0,0 +1,70 @@
// Package mime 提供MIME检查功能
package mime
import (
"io"
"github.com/gabriel-vasile/mimetype"
"github.com/sirupsen/logrus"
"github.com/Mrs4s/go-cqhttp/internal/base"
)
func init() {
base.IsLawfulAudio = checkImage
base.IsLawfulAudio = checkAudio
}
// keep sync with /docs/file.md#MINE
var lawfulImage = [...]string{
"image/bmp",
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
}
var lawfulAudio = [...]string{
"audio/aac",
"audio/aiff",
"audio/amr",
"audio/ape",
"audio/flac",
"audio/midi",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/x-m4a",
}
func check(r io.ReadSeeker, list []string) (bool, string) {
if base.SkipMimeScan {
return true, ""
}
_, _ = r.Seek(0, io.SeekStart)
defer r.Seek(0, io.SeekStart) // nolint
t, err := mimetype.DetectReader(r)
if err != nil {
logrus.Debugf("扫描 Mime 时出现问题: %v", err)
return false, ""
}
for _, lt := range list {
if t.Is(lt) {
return true, t.String()
}
}
return false, t.String()
}
// checkImage 判断给定流是否为合法图片
// 返回 是否合法, 实际Mime
// 判断后会自动将 Stream Seek 至 0
func checkImage(r io.ReadSeeker) (bool, string) {
return check(r, lawfulImage[:])
}
// checkImage 判断给定流是否为合法音频
func checkAudio(r io.ReadSeeker) (bool, string) {
return check(r, lawfulAudio[:])
}

View File

@ -0,0 +1,31 @@
// Package servers provide servers register
package servers
import (
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/internal/base"
)
var svr = make(map[string]func(*coolq.CQBot, yaml.Node))
// Register 注册 Server
func Register(name string, proc func(*coolq.CQBot, yaml.Node)) {
_, ok := svr[name]
if ok {
panic(name + " server has existed")
}
svr[name] = proc
}
// Run 运行所有svr
func Run(bot *coolq.CQBot) {
for _, l := range base.Servers {
for name, conf := range l {
if fn, ok := svr[name]; ok {
go fn(bot, conf)
}
}
}
}

View File

@ -1,9 +1,10 @@
//go:build (linux || (windows && !arm) || darwin) && (386 || amd64 || arm || arm64) && !race //go:build (linux || (windows && !arm && !arm64) || darwin) && (386 || amd64 || arm || arm64) && !race && !nosilk
// +build linux windows,!arm darwin // +build linux windows,!arm,!arm64 darwin
// +build 386 amd64 arm arm64 // +build 386 amd64 arm arm64
// +build !race // +build !race
// +build !nosilk
package codec package silk
import ( import (
"os" "os"
@ -12,12 +13,14 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/wdvxdr1123/go-silk" "github.com/wdvxdr1123/go-silk"
"github.com/Mrs4s/go-cqhttp/internal/base"
) )
const silkCachePath = "data/cache" const silkCachePath = "data/cache"
// EncodeToSilk 将音频编码为Silk // encode 将音频编码为Silk
func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte, err error) { func encode(record []byte, tempName string) (silkWav []byte, err error) {
// 1. 写入缓存文件 // 1. 写入缓存文件
rawPath := path.Join(silkCachePath, tempName+".wav") rawPath := path.Join(silkCachePath, tempName+".wav")
err = os.WriteFile(rawPath, record, os.ModePerm) err = os.WriteFile(rawPath, record, os.ModePerm)
@ -29,7 +32,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
// 2.转换pcm // 2.转换pcm
pcmPath := path.Join(silkCachePath, tempName+".pcm") pcmPath := path.Join(silkCachePath, tempName+".pcm")
cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath) cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath)
if Debug { if base.Debug {
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
} }
@ -47,15 +50,13 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
if err != nil { if err != nil {
return nil, errors.Wrap(err, "silk encode error") return nil, errors.Wrap(err, "silk encode error")
} }
if useCache {
silkPath := path.Join(silkCachePath, tempName+".silk") silkPath := path.Join(silkCachePath, tempName+".silk")
err = os.WriteFile(silkPath, silkWav, 0o666) err = os.WriteFile(silkPath, silkWav, 0o666)
}
return return
} }
// RecodeTo24K 将silk重新编码为 24000 bit rate // resample 将silk重新编码为 24000 bit rate
func RecodeTo24K(data []byte) []byte { func resample(data []byte) []byte {
pcm, err := silk.DecodeSilkBuffToPcm(data, 24000) pcm, err := silk.DecodeSilkBuffToPcm(data, 24000)
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -0,0 +1,16 @@
//go:build (!arm && !arm64 && !amd64 && !386) || (!windows && !linux && !darwin) || (windows && arm) || (windows && arm64) || race || nosilk
// +build !arm,!arm64,!amd64,!386 !windows,!linux,!darwin windows,arm windows,arm64 race nosilk
package silk
import "errors"
// encode 将音频编码为Silk
func encode(record []byte, tempName string) ([]byte, error) {
return nil, errors.New("not supported now")
}
// resample 将silk重新编码为 24000 bit rate
func resample(data []byte) []byte {
return data
}

11
modules/silk/stubs.go Normal file
View File

@ -0,0 +1,11 @@
// Package silk Silk编码核心模块
package silk
import (
"github.com/Mrs4s/go-cqhttp/internal/base"
)
func init() {
base.EncodeSilk = encode
base.ResampleSilk = resample
}

View File

@ -5,6 +5,7 @@ import (
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/param"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
@ -13,49 +14,57 @@ type resultGetter interface {
Get(string) gjson.Result Get(string) gjson.Result
} }
type handler func(action string, p resultGetter) coolq.MSG type handler func(action string, p resultGetter) global.MSG
type apiCaller struct { type apiCaller struct {
bot *coolq.CQBot bot *coolq.CQBot
handlers []handler handlers []handler
} }
func getLoginInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getLoginInfo(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetLoginInfo() return bot.CQGetLoginInfo()
} }
func getQiDianAccountInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getQiDianAccountInfo(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetQiDianAccountInfo() return bot.CQGetQiDianAccountInfo()
} }
func getFriendList(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getFriendList(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetFriendList() return bot.CQGetFriendList()
} }
func deleteFriend(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getUnidirectionalFriendList(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQDeleteFriend(p.Get("id").Int()) return bot.CQGetUnidirectionalFriendList()
} }
func getGroupList(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteFriend(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteFriend(p.Get("[user_id,id].0").Int())
}
func deleteUnidirectionalFriend(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteUnidirectionalFriend(p.Get("user_id").Int())
}
func getGroupList(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupList(p.Get("no_cache").Bool()) return bot.CQGetGroupList(p.Get("no_cache").Bool())
} }
func getGroupInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupInfo(p.Get("group_id").Int(), p.Get("no_cache").Bool()) return bot.CQGetGroupInfo(p.Get("group_id").Int(), p.Get("no_cache").Bool())
} }
func getGroupMemberList(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupMemberList(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupMemberList(p.Get("group_id").Int(), p.Get("no_cache").Bool()) return bot.CQGetGroupMemberList(p.Get("group_id").Int(), p.Get("no_cache").Bool())
} }
func getGroupMemberInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupMemberInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupMemberInfo( return bot.CQGetGroupMemberInfo(
p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("no_cache").Bool(), p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("no_cache").Bool(),
) )
} }
func sendMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
autoEscape := global.EnsureBool(p.Get("auto_escape"), false) autoEscape := param.EnsureBool(p.Get("auto_escape"), false)
if p.Get("message_type").Str == "private" { if p.Get("message_type").Str == "private" {
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), autoEscape) return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), autoEscape)
} }
@ -68,28 +77,28 @@ func sendMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG {
if p.Get("group_id").Int() != 0 { if p.Get("group_id").Int() != 0 {
return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"), autoEscape) return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"), autoEscape)
} }
return coolq.MSG{} return global.MSG{}
} }
func sendGroupMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendGroupMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"), return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"),
global.EnsureBool(p.Get("auto_escape"), false)) param.EnsureBool(p.Get("auto_escape"), false))
} }
func sendGroupForwardMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendGroupForwardMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSendGroupForwardMessage(p.Get("group_id").Int(), p.Get("messages")) return bot.CQSendGroupForwardMessage(p.Get("group_id").Int(), p.Get("messages"))
} }
func sendPrivateMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendPrivateMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"),
global.EnsureBool(p.Get("auto_escape"), false)) param.EnsureBool(p.Get("auto_escape"), false))
} }
func deleteMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteMessage(int32(p.Get("message_id").Int())) return bot.CQDeleteMessage(int32(p.Get("message_id").Int()))
} }
func setFriendAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setFriendAddRequest(bot *coolq.CQBot, p resultGetter) global.MSG {
apr := true apr := true
if p.Get("approve").Exists() { if p.Get("approve").Exists() {
apr = p.Get("approve").Bool() apr = p.Get("approve").Bool()
@ -97,7 +106,7 @@ func setFriendAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQProcessFriendRequest(p.Get("flag").Str, apr) return bot.CQProcessFriendRequest(p.Get("flag").Str, apr)
} }
func setGroupAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupAddRequest(bot *coolq.CQBot, p resultGetter) global.MSG {
subType := p.Get("sub_type").Str subType := p.Get("sub_type").Str
apr := true apr := true
if subType == "" { if subType == "" {
@ -109,19 +118,19 @@ func setGroupAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, p.Get("reason").Str, apr) return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, p.Get("reason").Str, apr)
} }
func setGroupCard(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupCard(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str) return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str)
} }
func setGroupSpecialTitle(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupSpecialTitle(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str) return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str)
} }
func setGroupKick(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupKick(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str, p.Get("reject_add_request").Bool()) return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str, p.Get("reject_add_request").Bool())
} }
func setGroupBan(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupBan(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), func() uint32 { return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), func() uint32 {
if p.Get("duration").Exists() { if p.Get("duration").Exists() {
return uint32(p.Get("duration").Int()) return uint32(p.Get("duration").Int())
@ -130,7 +139,7 @@ func setGroupBan(bot *coolq.CQBot, p resultGetter) coolq.MSG {
}()) }())
} }
func setGroupWholeBan(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupWholeBan(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupWholeBan(p.Get("group_id").Int(), func() bool { return bot.CQSetGroupWholeBan(p.Get("group_id").Int(), func() bool {
if p.Get("enable").Exists() { if p.Get("enable").Exists() {
return p.Get("enable").Bool() return p.Get("enable").Bool()
@ -139,11 +148,11 @@ func setGroupWholeBan(bot *coolq.CQBot, p resultGetter) coolq.MSG {
}()) }())
} }
func setGroupName(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupName(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupName(p.Get("group_id").Int(), p.Get("group_name").Str) return bot.CQSetGroupName(p.Get("group_id").Int(), p.Get("group_name").Str)
} }
func setGroupAdmin(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupAdmin(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupAdmin(p.Get("group_id").Int(), p.Get("user_id").Int(), func() bool { return bot.CQSetGroupAdmin(p.Get("group_id").Int(), p.Get("user_id").Int(), func() bool {
if p.Get("enable").Exists() { if p.Get("enable").Exists() {
return p.Get("enable").Bool() return p.Get("enable").Bool()
@ -152,19 +161,19 @@ func setGroupAdmin(bot *coolq.CQBot, p resultGetter) coolq.MSG {
}()) }())
} }
func sendGroupNotice(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendGroupNotice(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupMemo(p.Get("group_id").Int(), p.Get("content").Str, p.Get("image").String()) return bot.CQSetGroupMemo(p.Get("group_id").Int(), p.Get("content").Str, p.Get("image").String())
} }
func setGroupLeave(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupLeave(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupLeave(p.Get("group_id").Int()) return bot.CQSetGroupLeave(p.Get("group_id").Int())
} }
func getImage(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getImage(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetImage(p.Get("file").Str) return bot.CQGetImage(p.Get("file").Str)
} }
func getForwardMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getForwardMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
id := p.Get("message_id").Str id := p.Get("message_id").Str
if id == "" { if id == "" {
id = p.Get("id").Str id = p.Get("id").Str
@ -172,11 +181,11 @@ func getForwardMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQGetForwardMessage(id) return bot.CQGetForwardMessage(id)
} }
func getMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetMessage(int32(p.Get("message_id").Int())) return bot.CQGetMessage(int32(p.Get("message_id").Int()))
} }
func downloadFile(bot *coolq.CQBot, p resultGetter) coolq.MSG { func downloadFile(bot *coolq.CQBot, p resultGetter) global.MSG {
headers := map[string]string{} headers := map[string]string{}
headersToken := p.Get("headers") headersToken := p.Get("headers")
if headersToken.IsArray() { if headersToken.IsArray() {
@ -199,11 +208,11 @@ func downloadFile(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQDownloadFile(p.Get("url").Str, headers, int(p.Get("thread_count").Int())) return bot.CQDownloadFile(p.Get("url").Str, headers, int(p.Get("thread_count").Int()))
} }
func getGroupHonorInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupHonorInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str) return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str)
} }
func setRestart(_ *coolq.CQBot, _ resultGetter) coolq.MSG { func setRestart(_ *coolq.CQBot, _ resultGetter) global.MSG {
/* /*
var delay int64 var delay int64
delay = p.Get("delay").Int() delay = p.Get("delay").Int()
@ -215,115 +224,115 @@ func setRestart(_ *coolq.CQBot, _ resultGetter) coolq.MSG {
Restart <- struct{}{} Restart <- struct{}{}
}(delay) }(delay)
*/ */
return coolq.MSG{"data": nil, "retcode": 99, "msg": "restart un-supported now", "wording": "restart函数暂不兼容", "status": "failed"} return global.MSG{"data": nil, "retcode": 99, "msg": "restart un-supported now", "wording": "restart函数暂不兼容", "status": "failed"}
} }
func canSendImage(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func canSendImage(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQCanSendImage() return bot.CQCanSendImage()
} }
func canSendRecord(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func canSendRecord(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQCanSendRecord() return bot.CQCanSendRecord()
} }
func getStrangerInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getStrangerInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetStrangerInfo(p.Get("user_id").Int()) return bot.CQGetStrangerInfo(p.Get("user_id").Int())
} }
func getStatus(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getStatus(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetStatus() return bot.CQGetStatus()
} }
func getVersionInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getVersionInfo(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetVersionInfo() return bot.CQGetVersionInfo()
} }
func getGroupSystemMSG(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getGroupSystemMSG(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetGroupSystemMessages() return bot.CQGetGroupSystemMessages()
} }
func getGroupFileSystemInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupFileSystemInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupFileSystemInfo(p.Get("group_id").Int()) return bot.CQGetGroupFileSystemInfo(p.Get("group_id").Int())
} }
func getGroupRootFiles(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupRootFiles(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupRootFiles(p.Get("group_id").Int()) return bot.CQGetGroupRootFiles(p.Get("group_id").Int())
} }
func getGroupFilesByFolder(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupFilesByFolder(bot *coolq.CQBot, p resultGetter) global.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)
} }
func getGroupFileURL(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupFileURL(bot *coolq.CQBot, p resultGetter) global.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()))
} }
func uploadGroupFile(bot *coolq.CQBot, p resultGetter) coolq.MSG { func uploadGroupFile(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQUploadGroupFile(p.Get("group_id").Int(), p.Get("file").Str, p.Get("name").Str, p.Get("folder").Str) return bot.CQUploadGroupFile(p.Get("group_id").Int(), p.Get("file").Str, p.Get("name").Str, p.Get("folder").Str)
} }
func groupFileCreateFolder(bot *coolq.CQBot, p resultGetter) coolq.MSG { func groupFileCreateFolder(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGroupFileCreateFolder(p.Get("group_id").Int(), p.Get("folder_id").Str, p.Get("name").Str) return bot.CQGroupFileCreateFolder(p.Get("group_id").Int(), p.Get("folder_id").Str, p.Get("name").Str)
} }
func deleteGroupFolder(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteGroupFolder(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGroupFileDeleteFolder(p.Get("group_id").Int(), p.Get("folder_id").Str) return bot.CQGroupFileDeleteFolder(p.Get("group_id").Int(), p.Get("folder_id").Str)
} }
func deleteGroupFile(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteGroupFile(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGroupFileDeleteFile(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("bus_id").Int())) return bot.CQGroupFileDeleteFile(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("bus_id").Int()))
} }
func getGroupMsgHistory(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupMsgHistory(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupMessageHistory(p.Get("group_id").Int(), p.Get("message_seq").Int()) return bot.CQGetGroupMessageHistory(p.Get("group_id").Int(), p.Get("message_seq").Int())
} }
func getVipInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getVipInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetVipInfo(p.Get("user_id").Int()) return bot.CQGetVipInfo(p.Get("user_id").Int())
} }
func reloadEventFilter(_ *coolq.CQBot, p resultGetter) coolq.MSG { func reloadEventFilter(_ *coolq.CQBot, p resultGetter) global.MSG {
addFilter(p.Get("file").String()) addFilter(p.Get("file").String())
return coolq.OK(nil) return coolq.OK(nil)
} }
func getGroupAtAllRemain(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupAtAllRemain(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetAtAllRemain(p.Get("group_id").Int()) return bot.CQGetAtAllRemain(p.Get("group_id").Int())
} }
func ocrImage(bot *coolq.CQBot, p resultGetter) coolq.MSG { func ocrImage(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQOcrImage(p.Get("image").Str) return bot.CQOcrImage(p.Get("image").Str)
} }
func getOnlineClients(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getOnlineClients(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetOnlineClients(p.Get("no_cache").Bool()) return bot.CQGetOnlineClients(p.Get("no_cache").Bool())
} }
func getWordSlices(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getWordSlices(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetWordSlices(p.Get("content").Str) return bot.CQGetWordSlices(p.Get("content").Str)
} }
func setGroupPortrait(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupPortrait(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupPortrait(p.Get("group_id").Int(), p.Get("file").String(), p.Get("cache").String()) return bot.CQSetGroupPortrait(p.Get("group_id").Int(), p.Get("file").String(), p.Get("cache").String())
} }
func setEssenceMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setEssenceMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetEssenceMessage(int32(p.Get("message_id").Int())) return bot.CQSetEssenceMessage(int32(p.Get("message_id").Int()))
} }
func deleteEssenceMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteEssenceMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteEssenceMessage(int32(p.Get("message_id").Int())) return bot.CQDeleteEssenceMessage(int32(p.Get("message_id").Int()))
} }
func getEssenceMsgList(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getEssenceMsgList(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetEssenceMessageList(p.Get("group_id").Int()) return bot.CQGetEssenceMessageList(p.Get("group_id").Int())
} }
func checkURLSafely(bot *coolq.CQBot, p resultGetter) coolq.MSG { func checkURLSafely(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQCheckURLSafely(p.Get("url").String()) return bot.CQCheckURLSafely(p.Get("url").String())
} }
func setGroupAnonymousBan(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupAnonymousBan(bot *coolq.CQBot, p resultGetter) global.MSG {
obj := p.Get("anonymous") obj := p.Get("anonymous")
flag := p.Get("anonymous_flag") flag := p.Get("anonymous_flag")
if !flag.Exists() { if !flag.Exists() {
@ -338,27 +347,29 @@ func setGroupAnonymousBan(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQSetGroupAnonymousBan(p.Get("group_id").Int(), flag.String(), int32(p.Get("duration").Int())) return bot.CQSetGroupAnonymousBan(p.Get("group_id").Int(), flag.String(), int32(p.Get("duration").Int()))
} }
func handleQuickOperation(bot *coolq.CQBot, p resultGetter) coolq.MSG { func handleQuickOperation(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQHandleQuickOperation(p.Get("context"), p.Get("operation")) return bot.CQHandleQuickOperation(p.Get("context"), p.Get("operation"))
} }
func getModelShow(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getModelShow(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetModelShow(p.Get("model").String()) return bot.CQGetModelShow(p.Get("model").String())
} }
func setModelShow(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setModelShow(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetModelShow(p.Get("model").String(), p.Get("model_show").String()) return bot.CQSetModelShow(p.Get("model").String(), p.Get("model_show").String())
} }
func markMSGAsRead(bot *coolq.CQBot, p resultGetter) coolq.MSG { func markMSGAsRead(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQMarkMessageAsRead(int32(p.Get("message_id").Int())) return bot.CQMarkMessageAsRead(int32(p.Get("message_id").Int()))
} }
// API 是go-cqhttp当前支持的所有api的映射表 // API 是go-cqhttp当前支持的所有api的映射表
var API = map[string]func(*coolq.CQBot, resultGetter) coolq.MSG{ var API = map[string]func(*coolq.CQBot, resultGetter) global.MSG{
"get_login_info": getLoginInfo, "get_login_info": getLoginInfo,
"get_friend_list": getFriendList, "get_friend_list": getFriendList,
"get_unidirectional_friend_list": getUnidirectionalFriendList,
"delete_friend": deleteFriend, "delete_friend": deleteFriend,
"delete_unidirectional_friend": deleteUnidirectionalFriend,
"get_group_list": getGroupList, "get_group_list": getGroupList,
"get_group_info": getGroupInfo, "get_group_info": getGroupInfo,
"get_group_member_list": getGroupMemberList, "get_group_member_list": getGroupMemberList,
@ -420,7 +431,7 @@ var API = map[string]func(*coolq.CQBot, resultGetter) coolq.MSG{
"mark_msg_as_read": markMSGAsRead, "mark_msg_as_read": markMSGAsRead,
} }
func (api *apiCaller) callAPI(action string, p resultGetter) coolq.MSG { func (api *apiCaller) callAPI(action string, p resultGetter) global.MSG {
for _, fn := range api.handlers { for _, fn := range api.handlers {
if ret := fn(action, p); ret != nil { if ret := fn(action, p); ret != nil {
return ret return ret

View File

@ -1,2 +1,13 @@
// Package server 包含HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体 // Package server 包含HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体
package server package server
import "github.com/Mrs4s/go-cqhttp/modules/servers"
// 注册
func init() {
servers.Register("http", runHTTP)
servers.Register("ws", runWSServer)
servers.Register("ws-reverse", runWSClient)
servers.Register("pprof", runPprof)
servers.Register("lambda", runLambda)
}

View File

@ -5,23 +5,26 @@ import (
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"encoding/json"
"fmt" "fmt"
"io" "io"
"math/rand"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/guonaihong/gout"
"github.com/guonaihong/gout/dataflow"
jsoniter "github.com/json-iterator/go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/modules/config"
) )
type httpServer struct { type httpServer struct {
@ -30,8 +33,6 @@ type httpServer struct {
accessToken string accessToken string
} }
var json = jsoniter.ConfigCompatibleWithStandardLibrary
// HTTPClient 反向HTTP上报客户端 // HTTPClient 反向HTTP上报客户端
type HTTPClient struct { type HTTPClient struct {
bot *coolq.CQBot bot *coolq.CQBot
@ -53,13 +54,22 @@ func (h *httpCtx) Get(s string) gjson.Result {
if j.Exists() { if j.Exists() {
return j return j
} }
validJSONParam := func(p string) bool {
return (strings.HasPrefix(p, "{") || strings.HasPrefix(p, "[")) && gjson.Valid(p)
}
if h.postForm != nil { if h.postForm != nil {
if form := h.postForm.Get(s); form != "" { if form := h.postForm.Get(s); form != "" {
if validJSONParam(form) {
return gjson.Result{Type: gjson.JSON, Raw: form}
}
return gjson.Result{Type: gjson.String, Str: form} return gjson.Result{Type: gjson.String, Str: form}
} }
} }
if h.query != nil { if h.query != nil {
if query := h.query.Get(s); query != "" { if query := h.query.Get(s); query != "" {
if validJSONParam(query) {
return gjson.Result{Type: gjson.JSON, Raw: query}
}
return gjson.Result{Type: gjson.String, Str: query} return gjson.Result{Type: gjson.String, Str: query}
} }
} }
@ -107,14 +117,21 @@ func (s *httpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request
return return
} }
var response global.MSG
if base.AcceptOneBotV12HTTPEndPoint && request.URL.Path == "/" {
action := strings.TrimSuffix(ctx.Get("action").Str, "_async")
log.Debugf("HTTPServer接收到API调用: %v", action)
response = s.api.callAPI(action, ctx.Get("params"))
} else {
action := strings.TrimPrefix(request.URL.Path, "/") action := strings.TrimPrefix(request.URL.Path, "/")
action = strings.TrimSuffix(action, "_async") action = strings.TrimSuffix(action, "_async")
log.Debugf("HTTPServer接收到API调用: %v", action) log.Debugf("HTTPServer接收到API调用: %v", action)
ret := s.api.callAPI(action, &ctx) response = s.api.callAPI(action, &ctx)
}
writer.Header().Set("Content-Type", "application/json; charset=utf-8") writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(http.StatusOK) writer.WriteHeader(http.StatusOK)
_ = json.NewEncoder(writer).Encode(ret) _ = json.NewEncoder(writer).Encode(response)
} }
func checkAuth(req *http.Request, token string) int { func checkAuth(req *http.Request, token string) int {
@ -142,16 +159,19 @@ func checkAuth(req *http.Request, token string) int {
} }
} }
// RunHTTPServerAndClients 启动HTTP服务器与HTTP上报客户端 // runHTTP 启动HTTP服务器与HTTP上报客户端
func RunHTTPServerAndClients(bot *coolq.CQBot, conf *config.HTTPServer) { func runHTTP(bot *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.HTTPServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取http配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
var (
s = new(httpServer) var addr string
addr string s := &httpServer{accessToken: conf.AccessToken}
)
s.accessToken = conf.AccessToken
if conf.Host == "" || conf.Port == 0 { if conf.Host == "" || conf.Port == 0 {
goto client goto client
} }
@ -204,7 +224,6 @@ func (c HTTPClient) Run() {
} }
func (c *HTTPClient) onBotPushEvent(e *coolq.Event) { func (c *HTTPClient) onBotPushEvent(e *coolq.Event) {
var res string
if c.filter != "" { if c.filter != "" {
filter := findFilter(c.filter) filter := findFilter(c.filter)
if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) { if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) {
@ -213,40 +232,51 @@ func (c *HTTPClient) onBotPushEvent(e *coolq.Event) {
} }
} }
err := gout.POST(c.addr).SetJSON(e.JSONBytes()).BindBody(&res).SetHeader(func() gout.H { client := http.Client{Timeout: time.Second * time.Duration(c.timeout)}
h := gout.H{ req, _ := http.NewRequest("POST", c.addr, nil)
"X-Self-ID": c.bot.Client.Uin, req.Header.Set("X-Self-ID", strconv.FormatInt(c.bot.Client.Uin, 10))
"User-Agent": "CQHttp/4.15.0", req.Header.Set("User-Agent", "CQHttp/4.15.0")
}
if c.secret != "" { if c.secret != "" {
mac := hmac.New(sha1.New, []byte(c.secret)) mac := hmac.New(sha1.New, []byte(c.secret))
_, err := mac.Write(e.JSONBytes()) _, _ = mac.Write(e.JSONBytes())
if err != nil { req.Header.Set("X-Signature", "sha1="+hex.EncodeToString(mac.Sum(nil)))
log.Error(err)
return nil
}
h["X-Signature"] = "sha1=" + hex.EncodeToString(mac.Sum(nil))
} }
if c.apiPort != 0 { if c.apiPort != 0 {
h["X-API-Port"] = c.apiPort req.Header.Set("X-API-Port", strconv.FormatInt(int64(c.apiPort), 10))
} }
return h
}()).SetTimeout(time.Second * time.Duration(c.timeout)).F().Retry().Attempt(5). var res *http.Response
WaitTime(time.Millisecond * 500).MaxWaitTime(time.Second * 5). var err error
Func(func(con *dataflow.Context) error { const maxAttemptTimes = 5
if con.Error != nil {
log.Warnf("上报Event到 HTTP 服务器 %v 时出现错误: %v 将重试.", c.addr, con.Error) for i := 0; i <= maxAttemptTimes; i++ {
return con.Error res, err = client.Do(req)
if err == nil {
//goland:noinspection GoDeferInLoop
defer res.Body.Close()
break
} }
return nil if i != maxAttemptTimes {
}).Do() log.Warnf("上报 Event 数据到 %v 失败: %v 将进行第 %d 次重试", c.addr, err, i+1)
}
const maxWait = int64(time.Second * 3)
const minWait = int64(time.Millisecond * 500)
wait := rand.Int63n(maxWait-minWait) + minWait
time.Sleep(time.Duration(wait))
}
if err != nil { if err != nil {
log.Warnf("上报Event数据 %s 到 %v 失败: %v", e.JSONBytes(), c.addr, err) log.Warnf("上报Event数据 %s 到 %v 失败: %v", e.JSONBytes(), c.addr, err)
return return
} }
log.Debugf("上报Event数据 %s 到 %v", e.JSONBytes(), c.addr) log.Debugf("上报Event数据 %s 到 %v", e.JSONBytes(), c.addr)
if gjson.Valid(res) {
c.bot.CQHandleQuickOperation(gjson.Parse(e.JSONString()), gjson.Parse(res)) r, err := io.ReadAll(res.Body)
if err != nil {
return
}
if gjson.ValidBytes(r) {
c.bot.CQHandleQuickOperation(gjson.Parse(e.JSONString()), gjson.ParseBytes(r))
} }
} }

View File

@ -5,6 +5,7 @@ import (
"context" "context"
"os" "os"
"sync" "sync"
"time"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
@ -21,7 +22,7 @@ var (
func rateLimit(frequency float64, bucketSize int) handler { func rateLimit(frequency float64, bucketSize int) handler {
limiter := rate.NewLimiter(rate.Limit(frequency), bucketSize) limiter := rate.NewLimiter(rate.Limit(frequency), bucketSize)
return func(_ string, _ resultGetter) coolq.MSG { return func(_ string, _ resultGetter) global.MSG {
_ = limiter.Wait(context.Background()) _ = limiter.Wait(context.Background())
return nil return nil
} }
@ -69,15 +70,23 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
} }
cond.Signal() cond.Signal()
}) })
return func(action string, p resultGetter) coolq.MSG { return func(action string, p resultGetter) global.MSG {
if action != "get_updates" { if action != "get_updates" {
return nil return nil
} }
var (
once sync.Once
ch = make(chan []interface{}, 1)
timeout = time.Duration(p.Get("timeout").Int()) * time.Second
)
defer close(ch)
go func() {
mutex.Lock() mutex.Lock()
defer mutex.Unlock() defer mutex.Unlock()
if queue.Len() == 0 { if queue.Len() == 0 {
cond.Wait() cond.Wait()
} }
once.Do(func() {
limit := int(p.Get("limit").Int()) limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit { if limit <= 0 || queue.Len() < limit {
limit = queue.Len() limit = queue.Len()
@ -86,6 +95,18 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
for i := 0; i < limit; i++ { for i := 0; i < limit; i++ {
ret[i] = queue.Remove(queue.Front()) ret[i] = queue.Remove(queue.Front())
} }
ch <- ret
})
}()
if timeout != 0 {
select {
case <-time.After(timeout):
once.Do(func() {})
return coolq.OK([]interface{}{})
case ret := <-ch:
return coolq.OK(ret) return coolq.OK(ret)
} }
} }
return coolq.OK(<-ch)
}
}

View File

@ -8,15 +8,23 @@ import (
"time" "time"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/modules/config"
) )
// RunPprofServer 启动 pprof 性能分析服务器 // runPprof 启动 pprof 性能分析服务器
func RunPprofServer(conf *config.PprofServer) { func runPprof(_ *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.PprofServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取pprof配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port) addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index) mux.HandleFunc("/debug/pprof/", pprof.Index)

View File

@ -2,6 +2,7 @@ package server
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -12,10 +13,11 @@ import (
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/modules/config"
) )
type lambdaClient struct { type lambdaClient struct {
@ -76,8 +78,17 @@ func (l *lambdaResponseWriter) WriteHeader(statusCode int) {
var cli *lambdaClient var cli *lambdaClient
// RunLambdaClient type: [scf,aws] // runLambda type: [scf,aws]
func RunLambdaClient(bot *coolq.CQBot, conf *config.LambdaServer) { func runLambda(bot *coolq.CQBot, node yaml.Node) {
var conf config.LambdaServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取lambda配置失败 :", err)
fallthrough
case conf.Disabled:
return
}
cli = &lambdaClient{ cli = &lambdaClient{
lambdaType: conf.Type, lambdaType: conf.Type,
client: http.Client{Timeout: 0}, client: http.Client{Timeout: 0},
@ -86,8 +97,7 @@ func RunLambdaClient(bot *coolq.CQBot, conf *config.LambdaServer) {
case "scf": // tencent serverless function case "scf": // tencent serverless function
base := fmt.Sprintf("http://%s:%s/runtime/", base := fmt.Sprintf("http://%s:%s/runtime/",
os.Getenv("SCF_RUNTIME_API"), os.Getenv("SCF_RUNTIME_API"),
os.Getenv("SCF_RUNTIME_API_PORT"), os.Getenv("SCF_RUNTIME_API_PORT"))
)
cli.nextURL = base + "invocation/next" cli.nextURL = base + "invocation/next"
cli.responseURL = base + "invocation/response" cli.responseURL = base + "invocation/response"
post, err := http.Post(base+"init/ready", "", nil) post, err := http.Post(base+"init/ready", "", nil)
@ -116,23 +126,20 @@ func RunLambdaClient(bot *coolq.CQBot, conf *config.LambdaServer) {
for { for {
req := cli.next() req := cli.next()
if req == nil { writer := lambdaResponseWriter{statusCode: 200, header: make(http.Header)}
writer := lambdaResponseWriter{statusCode: 200}
_, _ = writer.Write(nil)
continue
}
func() { func() {
defer func() { defer func() {
if e := recover(); e != nil { if e := recover(); e != nil {
log.Warnf("Lambda 出现不可恢复错误: %v\n%s", e, debug.Stack()) log.Warnf("Lambda 出现不可恢复错误: %v\n%s", e, debug.Stack())
} }
}() }()
writer := lambdaResponseWriter{header: make(http.Header)} if req != nil {
server.ServeHTTP(&writer, req) server.ServeHTTP(&writer, req)
}
}()
if err := writer.flush(); err != nil { if err := writer.flush(); err != nil {
log.Warnf("Lambda 发送响应失败: %v", err) log.Warnf("Lambda 发送响应失败: %v", err)
} }
}()
} }
} }
@ -160,8 +167,8 @@ func (c *lambdaClient) next() *http.Request {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil return nil
} }
var req = new(http.Request) req := new(http.Request)
var invoke = new(lambdaInvoke) invoke := new(lambdaInvoke)
_ = json.NewDecoder(resp.Body).Decode(invoke) _ = json.NewDecoder(resp.Body).Decode(invoke)
if invoke.HTTPMethod == "" { // 不是 api 网关 if invoke.HTTPMethod == "" { // 不是 api 网关
return nil return nil

View File

@ -2,6 +2,8 @@ package server
import ( import (
"bytes" "bytes"
"context"
"encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"runtime/debug" "runtime/debug"
@ -10,12 +12,14 @@ import (
"sync" "sync"
"time" "time"
"gopkg.in/yaml.v3"
"nhooyr.io/websocket"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/modules/config"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
@ -24,8 +28,9 @@ type webSocketServer struct {
bot *coolq.CQBot bot *coolq.CQBot
conf *config.WebsocketServer conf *config.WebsocketServer
eventConn []*webSocketConn mu sync.Mutex
eventConnMutex sync.Mutex eventConn []*wsConn
token string token string
handshake string handshake string
filter string filter string
@ -36,32 +41,33 @@ type websocketClient struct {
bot *coolq.CQBot bot *coolq.CQBot
conf *config.WebsocketReverse conf *config.WebsocketReverse
universalConn *webSocketConn mu sync.Mutex
eventConn *webSocketConn
universal *wsConn
event *wsConn
token string token string
filter string filter string
} }
type webSocketConn struct { type wsConn struct {
*websocket.Conn *websocket.Conn
sync.Mutex
apiCaller *apiCaller apiCaller *apiCaller
} }
var upgrader = websocket.Upgrader{ // runWSServer 运行一个正向WS server
CheckOrigin: func(r *http.Request) bool { func runWSServer(b *coolq.CQBot, node yaml.Node) {
return true var conf config.WebsocketServer
}, switch err := node.Decode(&conf); {
} case err != nil:
log.Warn("读取正向Websocket配置失败 :", err)
// RunWebSocketServer 运行一个正向WS server fallthrough
func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) { case conf.Disabled:
if conf.Disabled {
return return
} }
s := &webSocketServer{ s := &webSocketServer{
bot: b, bot: b,
conf: conf, conf: &conf,
token: conf.AccessToken, token: conf.AccessToken,
filter: conf.Filter, filter: conf.Filter,
} }
@ -80,137 +86,89 @@ func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) {
}() }()
} }
// RunWebSocketClient 运行一个向WS client // runWSClient 运行一个反向向WS client
func RunWebSocketClient(b *coolq.CQBot, conf *config.WebsocketReverse) { func runWSClient(b *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.WebsocketReverse
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取反向Websocket配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
c := &websocketClient{ c := &websocketClient{
bot: b, bot: b,
conf: conf, conf: &conf,
token: conf.AccessToken, token: conf.AccessToken,
filter: conf.Filter, filter: conf.Filter,
} }
addFilter(c.filter) addFilter(c.filter)
if c.conf.Universal != "" { if c.conf.Universal != "" {
c.connectUniversal() c.connect("Universal", conf.Universal, &c.universal)
} else { } else {
if c.conf.API != "" { if c.conf.API != "" {
c.connectAPI() c.connect("API", conf.API, nil)
} }
if c.conf.Event != "" { if c.conf.Event != "" {
c.connectEvent() c.connect("Event", conf.Event, &c.event)
} }
} }
c.bot.OnEventPush(c.onBotPushEvent) c.bot.OnEventPush(c.onBotPushEvent)
} }
func (c *websocketClient) connectAPI() { func (c *websocketClient) connect(typ, url string, conptr **wsConn) {
log.Infof("开始尝试连接到反向WebSocket API服务器: %v", c.conf.API) log.Infof("开始尝试连接到反向WebSocket %s服务器: %v", typ, c.conf.API)
header := http.Header{ header := http.Header{
"X-Client-Role": []string{"API"}, "X-Client-Role": []string{typ},
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)}, "X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
"User-Agent": []string{"CQHttp/4.15.0"}, "User-Agent": []string{"CQHttp/4.15.0"},
} }
if c.token != "" { if c.token != "" {
header["Authorization"] = []string{"Token " + c.token} header["Authorization"] = []string{"Token " + c.token}
} }
conn, _, err := websocket.DefaultDialer.Dial(c.conf.API, header) // nolint conn, _, err := websocket.Dial(context.Background(), url, &websocket.DialOptions{HTTPHeader: header}) // nolint
if err != nil { if err != nil {
log.Warnf("连接到反向WebSocket API服务器 %v 时出现错误: %v", c.conf.API, err) log.Warnf("连接到反向WebSocket %s服务器 %v 时出现错误: %v", typ, c.conf.API, err)
if c.conf.ReconnectInterval != 0 { if c.conf.ReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval)) time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
c.connectAPI() c.connect(typ, url, conptr)
} }
return return
} }
log.Infof("已连接到反向WebSocket API服务器 %v", c.conf.API)
wrappedConn := &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)} switch typ {
case "Event", "Universal":
handshake := fmt.Sprintf(`{"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`, c.bot.Client.Uin, time.Now().Unix())
err = conn.Write(context.Background(), websocket.MessageText, []byte(handshake))
if err != nil {
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
}
}
log.Infof("已连接到反向WebSocket %s服务器 %v", typ, c.conf.API)
wrappedConn := &wsConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
if c.conf.RateLimit.Enabled { if c.conf.RateLimit.Enabled {
wrappedConn.apiCaller.use(rateLimit(c.conf.RateLimit.Frequency, c.conf.RateLimit.Bucket)) wrappedConn.apiCaller.use(rateLimit(c.conf.RateLimit.Frequency, c.conf.RateLimit.Bucket))
} }
if conptr != nil {
*conptr = wrappedConn
}
switch typ {
case "API":
go c.listenAPI(wrappedConn, false) go c.listenAPI(wrappedConn, false)
} case "Universal":
go c.listenAPI(wrappedConn, true)
func (c *websocketClient) connectEvent() {
log.Infof("开始尝试连接到反向WebSocket Event服务器: %v", c.conf.Event)
header := http.Header{
"X-Client-Role": []string{"Event"},
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
"User-Agent": []string{"CQHttp/4.15.0"},
}
if c.token != "" {
header["Authorization"] = []string{"Token " + c.token}
}
conn, _, err := websocket.DefaultDialer.Dial(c.conf.Event, header) // nolint
if err != nil {
log.Warnf("连接到反向WebSocket Event服务器 %v 时出现错误: %v", c.conf.Event, err)
if c.conf.ReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
c.connectEvent()
}
return
}
handshake := fmt.Sprintf(`{"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
c.bot.Client.Uin, time.Now().Unix())
err = conn.WriteMessage(websocket.TextMessage, []byte(handshake))
if err != nil {
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
}
log.Infof("已连接到反向WebSocket Event服务器 %v", c.conf.Event)
if c.eventConn == nil {
wrappedConn := &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
c.eventConn = wrappedConn
} else {
c.eventConn.Conn = conn
} }
} }
func (c *websocketClient) connectUniversal() { func (c *websocketClient) listenAPI(conn *wsConn, u bool) {
log.Infof("开始尝试连接到反向WebSocket Universal服务器: %v", c.conf.Universal) defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
header := http.Header{
"X-Client-Role": []string{"Universal"},
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
"User-Agent": []string{"CQHttp/4.15.0"},
}
if c.token != "" {
header["Authorization"] = []string{"Token " + c.token}
}
conn, _, err := websocket.DefaultDialer.Dial(c.conf.Universal, header) // nolint
if err != nil {
log.Warnf("连接到反向WebSocket Universal服务器 %v 时出现错误: %v", c.conf.Universal, err)
if c.conf.ReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
c.connectUniversal()
}
return
}
handshake := fmt.Sprintf(`{"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
c.bot.Client.Uin, time.Now().Unix())
err = conn.WriteMessage(websocket.TextMessage, []byte(handshake))
if err != nil {
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
}
if c.universalConn == nil {
wrappedConn := &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
if c.conf.RateLimit.Enabled {
wrappedConn.apiCaller.use(rateLimit(c.conf.RateLimit.Frequency, c.conf.RateLimit.Bucket))
}
c.universalConn = wrappedConn
} else {
c.universalConn.Conn = conn
}
go c.listenAPI(c.universalConn, true)
}
func (c *websocketClient) listenAPI(conn *webSocketConn, u bool) {
defer func() { _ = conn.Close() }()
for { for {
buffer := global.NewBuffer() buffer := global.NewBuffer()
t, reader, err := conn.NextReader() t, reader, err := conn.Conn.Reader(context.Background())
if err != nil { if err != nil {
log.Warnf("监听反向WS API时出现错误: %v", err) log.Warnf("监听反向WS API时出现错误: %v", err)
break break
@ -220,7 +178,7 @@ func (c *websocketClient) listenAPI(conn *webSocketConn, u bool) {
log.Warnf("监听反向WS API时出现错误: %v", err) log.Warnf("监听反向WS API时出现错误: %v", err)
break break
} }
if t == websocket.TextMessage { if t == websocket.MessageText {
go func(buffer *bytes.Buffer) { go func(buffer *bytes.Buffer) {
defer global.PutBuffer(buffer) defer global.PutBuffer(buffer)
conn.handleRequest(c.bot, buffer.Bytes()) conn.handleRequest(c.bot, buffer.Bytes())
@ -232,7 +190,7 @@ func (c *websocketClient) listenAPI(conn *webSocketConn, u bool) {
if c.conf.ReconnectInterval != 0 { if c.conf.ReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval)) time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
if !u { if !u {
go c.connectAPI() go c.connect("API", c.conf.API, nil)
} }
} }
} }
@ -243,25 +201,34 @@ func (c *websocketClient) onBotPushEvent(e *coolq.Event) {
log.Debugf("上报Event %s 到 WS服务器 时被过滤.", e.JSONBytes()) log.Debugf("上报Event %s 到 WS服务器 时被过滤.", e.JSONBytes())
return return
} }
push := func(conn *webSocketConn, reconnect func()) { push := func(conn *wsConn, reconnect func()) {
log.Debugf("向WS服务器 %v 推送Event: %s", conn.RemoteAddr().String(), e.JSONBytes()) log.Debugf("向WS服务器推送Event: %s", e.JSONBytes())
conn.Lock() ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer conn.Unlock() defer cancel()
_ = conn.SetWriteDeadline(time.Now().Add(time.Second * 15)) if err := conn.Write(ctx, websocket.MessageText, e.JSONBytes()); err != nil {
if err := conn.WriteMessage(websocket.TextMessage, e.JSONBytes()); err != nil { log.Warnf("向WS服务器推送 Event 时出现错误: %v", err)
log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", conn.RemoteAddr().String(), err) _ = conn.Close(websocket.StatusNormalClosure, "")
_ = conn.Close()
if c.conf.ReconnectInterval != 0 { if c.conf.ReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval)) time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
reconnect() reconnect()
} }
} }
} }
if c.eventConn != nil {
push(c.eventConn, c.connectEvent) connect := func(typ, url string, conptr **wsConn) func() {
return func() {
c.connect(typ, url, conptr)
} }
if c.universalConn != nil { }
push(c.universalConn, c.connectUniversal)
c.mu.Lock()
defer c.mu.Unlock()
if c.event != nil {
push(c.event, connect("Event", c.conf.Event, &c.event))
}
if c.universal != nil {
push(c.universal, connect("Universal", c.conf.Universal, &c.universal))
} }
} }
@ -272,25 +239,25 @@ func (s *webSocketServer) event(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status) w.WriteHeader(status)
return return
} }
c, err := upgrader.Upgrade(w, r, nil) c, err := websocket.Accept(w, r, nil)
if err != nil { if err != nil {
log.Warnf("处理 WebSocket 请求时出现错误: %v", err) log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
return return
} }
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake)) err = c.Write(context.Background(), websocket.MessageText, []byte(s.handshake))
if err != nil { if err != nil {
log.Warnf("WebSocket 握手时出现错误: %v", err) log.Warnf("WebSocket 握手时出现错误: %v", err)
_ = c.Close() _ = c.Close(websocket.StatusNormalClosure, "")
return return
} }
log.Infof("接受 WebSocket 连接: %v (/event)", r.RemoteAddr) log.Infof("接受 WebSocket 连接: %v (/event)", r.RemoteAddr)
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)} conn := &wsConn{Conn: c, apiCaller: newAPICaller(s.bot)}
s.eventConnMutex.Lock() s.mu.Lock()
s.eventConn = append(s.eventConn, conn) s.eventConn = append(s.eventConn, conn)
s.eventConnMutex.Unlock() s.mu.Unlock()
} }
func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) { func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
@ -300,13 +267,13 @@ func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status) w.WriteHeader(status)
return return
} }
c, err := upgrader.Upgrade(w, r, nil) c, err := websocket.Accept(w, r, nil)
if err != nil { if err != nil {
log.Warnf("处理 WebSocket 请求时出现错误: %v", err) log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
return return
} }
log.Infof("接受 WebSocket 连接: %v (/api)", r.RemoteAddr) log.Infof("接受 WebSocket 连接: %v (/api)", r.RemoteAddr)
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)} conn := &wsConn{Conn: c, apiCaller: newAPICaller(s.bot)}
if s.conf.RateLimit.Enabled { if s.conf.RateLimit.Enabled {
conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket)) conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket))
} }
@ -320,33 +287,33 @@ func (s *webSocketServer) any(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status) w.WriteHeader(status)
return return
} }
c, err := upgrader.Upgrade(w, r, nil) c, err := websocket.Accept(w, r, nil)
if err != nil { if err != nil {
log.Warnf("处理 WebSocket 请求时出现错误: %v", err) log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
return return
} }
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake)) err = c.Write(context.Background(), websocket.MessageText, []byte(s.handshake))
if err != nil { if err != nil {
log.Warnf("WebSocket 握手时出现错误: %v", err) log.Warnf("WebSocket 握手时出现错误: %v", err)
_ = c.Close() _ = c.Close(websocket.StatusNormalClosure, "")
return return
} }
log.Infof("接受 WebSocket 连接: %v (/)", r.RemoteAddr) log.Infof("接受 WebSocket 连接: %v (/)", r.RemoteAddr)
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)} conn := &wsConn{Conn: c, apiCaller: newAPICaller(s.bot)}
if s.conf.RateLimit.Enabled { if s.conf.RateLimit.Enabled {
conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket)) conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket))
} }
s.eventConnMutex.Lock() s.mu.Lock()
s.eventConn = append(s.eventConn, conn) s.eventConn = append(s.eventConn, conn)
s.eventConnMutex.Unlock() s.mu.Unlock()
s.listenAPI(conn) s.listenAPI(conn)
} }
func (s *webSocketServer) listenAPI(c *webSocketConn) { func (s *webSocketServer) listenAPI(c *wsConn) {
defer func() { _ = c.Close() }() defer func() { _ = c.Close(websocket.StatusNormalClosure, "") }()
for { for {
buffer := global.NewBuffer() buffer := global.NewBuffer()
t, reader, err := c.NextReader() t, reader, err := c.Reader(context.Background())
if err != nil { if err != nil {
break break
} }
@ -355,7 +322,7 @@ func (s *webSocketServer) listenAPI(c *webSocketConn) {
break break
} }
if t == websocket.TextMessage { if t == websocket.MessageText {
go func(buffer *bytes.Buffer) { go func(buffer *bytes.Buffer) {
defer global.PutBuffer(buffer) defer global.PutBuffer(buffer)
c.handleRequest(s.bot, buffer.Bytes()) c.handleRequest(s.bot, buffer.Bytes())
@ -366,11 +333,11 @@ func (s *webSocketServer) listenAPI(c *webSocketConn) {
} }
} }
func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) { func (c *wsConn) handleRequest(_ *coolq.CQBot, payload []byte) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Printf("处置WS命令时发生无法恢复的异常%v\n%s", err, debug.Stack()) log.Printf("处置WS命令时发生无法恢复的异常%v\n%s", err, debug.Stack())
_ = c.Close() _ = c.Close(websocket.StatusInternalError, fmt.Sprint(err))
} }
}() }()
j := gjson.Parse(utils.B2S(payload)) j := gjson.Parse(utils.B2S(payload))
@ -380,27 +347,27 @@ func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) {
if j.Get("echo").Exists() { if j.Get("echo").Exists() {
ret["echo"] = j.Get("echo").Value() ret["echo"] = j.Get("echo").Value()
} }
c.Lock() writer, _ := c.Writer(context.Background(), websocket.MessageText)
defer c.Unlock() _ = json.NewEncoder(writer).Encode(ret)
_ = c.WriteJSON(ret) _ = writer.Close()
} }
func (s *webSocketServer) onBotPushEvent(e *coolq.Event) { func (s *webSocketServer) onBotPushEvent(e *coolq.Event) {
s.eventConnMutex.Lock()
defer s.eventConnMutex.Unlock()
filter := findFilter(s.filter) filter := findFilter(s.filter)
if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) { if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) {
log.Debugf("上报Event %s 到 WS客户端 时被过滤.", e.JSONBytes()) log.Debugf("上报Event %s 到 WS客户端 时被过滤.", e.JSONBytes())
return return
} }
s.mu.Lock()
defer s.mu.Unlock()
j := 0 j := 0
for i := 0; i < len(s.eventConn); i++ { for i := 0; i < len(s.eventConn); i++ {
conn := s.eventConn[i] conn := s.eventConn[i]
log.Debugf("向WS客户端 %v 推送Event: %s", conn.RemoteAddr().String(), e.JSONBytes()) log.Debugf("向WS客户端推送Event: %s", e.JSONBytes())
conn.Lock() if err := conn.Write(context.Background(), websocket.MessageText, e.JSONBytes()); err != nil {
if err := conn.WriteMessage(websocket.TextMessage, e.JSONBytes()); err != nil { _ = conn.Close(websocket.StatusNormalClosure, "")
_ = conn.Close()
conn = nil conn = nil
continue continue
} }
@ -409,7 +376,6 @@ func (s *webSocketServer) onBotPushEvent(e *coolq.Event) {
// use a in-place removal to avoid copying. // use a in-place removal to avoid copying.
s.eventConn[j] = conn s.eventConn[j] = conn
} }
conn.Unlock()
j++ j++
} }
s.eventConn = s.eventConn[:j] s.eventConn = s.eventConn[:j]