mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-06-30 11:53:25 +00:00
Compare commits
60 Commits
v1.0.0-alp
...
v1.0.0-bet
Author | SHA1 | Date | |
---|---|---|---|
c064366d95 | |||
2dd2a935c3 | |||
3c8bb18a94 | |||
35860a4b11 | |||
3c5779ebd3 | |||
bdc0a15465 | |||
beef8da036 | |||
c06aee39d9 | |||
b8f004d278 | |||
464c2c8bcc | |||
e8d2d345e9 | |||
2b1fdd87ee | |||
a7c41e709c | |||
6083fa62b3 | |||
4eacf96a17 | |||
169919020b | |||
d377b8bdf1 | |||
a361366916 | |||
144220a1da | |||
a57a44f3d6 | |||
9dc02fb850 | |||
3ea9c2547c | |||
15a59d4252 | |||
ce63c54a16 | |||
ecf695a68d | |||
337e53ebc6 | |||
a4a531c9d0 | |||
fa024c2528 | |||
33864b6d07 | |||
eb8a65c682 | |||
f0bcc8071e | |||
cebf9c25e1 | |||
daec9cf12c | |||
e93a0fdd84 | |||
f495001fac | |||
75b531e2dc | |||
6b530e3c19 | |||
d7ee32ebe6 | |||
5b74c5cb9f | |||
32bba9994b | |||
db63cbec82 | |||
5b0c693aba | |||
5429292357 | |||
4aab8ebe52 | |||
8db68f9427 | |||
001d9aa0d6 | |||
798df7e9dd | |||
6f0f66132a | |||
079bd9d6ed | |||
a5947ece10 | |||
5940421b72 | |||
f4d76d1d03 | |||
81b8b758a3 | |||
a499ad0c43 | |||
76d00a57ff | |||
9413c801c5 | |||
8e6312914c | |||
69eec1419c | |||
4dfee419e5 | |||
b63659656b |
5
.github/workflows/golint.yml
vendored
5
.github/workflows/golint.yml
vendored
@ -15,10 +15,11 @@ jobs:
|
||||
version: latest
|
||||
|
||||
- name: Commit back
|
||||
if: github.repository_owner == 'Mrs4s'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
git config --local user.name 'Github Actions'
|
||||
git config --local user.email 'github-actions@users.noreply.github.com'
|
||||
git config --local user.name 'github-actions[bot]'
|
||||
git config --local user.email '41898282+github-actions[bot]@users.noreply.github.com'
|
||||
git add --all
|
||||
git commit -m "ci(chore): Fix stylings"
|
||||
git push
|
||||
|
19
.github/workflows/release.yml
vendored
19
.github/workflows/release.yml
vendored
@ -9,14 +9,12 @@ jobs:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
-
|
||||
name: Checkout
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
-
|
||||
name: Set up Go
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: '1.16.2'
|
||||
@ -28,3 +26,16 @@ jobs:
|
||||
args: release --rm-dist
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
#- name: Checkout Dist
|
||||
# uses: actions/checkout@v2
|
||||
# with:
|
||||
# repository: 'gocq/dist'
|
||||
# ref: master
|
||||
# ssh-key: ${{ secrets.SSH_KEY }}
|
||||
# path: upstream/dist
|
||||
|
||||
#- name: Update Dist
|
||||
# run: |
|
||||
# chmod +x scripts/upload_dist.sh
|
||||
# ./scripts/upload_dist.sh
|
||||
|
6
.gitignore
vendored
6
.gitignore
vendored
@ -1,7 +1,9 @@
|
||||
vendor/
|
||||
.idea
|
||||
.vscode
|
||||
config.hjson
|
||||
config.yml
|
||||
session.token
|
||||
device.json
|
||||
codec/
|
||||
data/
|
||||
logs/
|
||||
logs/
|
||||
|
@ -33,7 +33,7 @@ linters:
|
||||
#- goconst
|
||||
- gocritic
|
||||
#- gocyclo
|
||||
- gofmt
|
||||
- gofumpt
|
||||
- goimports
|
||||
- goprintffuncname
|
||||
#- gosec
|
||||
@ -55,7 +55,7 @@ linters:
|
||||
- prealloc
|
||||
- predeclared
|
||||
- asciicheck
|
||||
- revive
|
||||
- golint
|
||||
- forbidigo
|
||||
- makezero
|
||||
#- interfacer
|
||||
@ -82,7 +82,7 @@ run:
|
||||
|
||||
# output configuration options
|
||||
output:
|
||||
format: 'colored-line-number'
|
||||
format: "colored-line-number"
|
||||
print-issued-lines: true
|
||||
print-linter-name: true
|
||||
uniq-by-line: true
|
||||
@ -90,3 +90,6 @@ output:
|
||||
issues:
|
||||
# Fix found issues (if it's supported by the linter)
|
||||
fix: true
|
||||
exclude-use-default: false
|
||||
exclude:
|
||||
- "Error return value of .((os.)?std(out|err)..*|.*Close|.*Flush|os.Remove(All)?|.*print(f|ln)?|os.(Un)?Setenv). is not check"
|
||||
|
@ -4,39 +4,56 @@ before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
builds:
|
||||
- env:
|
||||
- id: nowin
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
- GO111MODULE=on
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
- windows
|
||||
goarch:
|
||||
- 386
|
||||
- amd64
|
||||
- arm
|
||||
- arm64
|
||||
goarm:
|
||||
- 7
|
||||
ignore:
|
||||
- goos: darwin
|
||||
goarch: arm
|
||||
- goos: darwin
|
||||
goarch: 386
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
mod_timestamp: '{{ .CommitTimestamp }}'
|
||||
mod_timestamp: "{{ .CommitTimestamp }}"
|
||||
flags:
|
||||
- -trimpath
|
||||
ldflags:
|
||||
- -s -w -X github.com/Mrs4s/go-cqhttp/coolq.Version=v{{.Version}}
|
||||
- id: win
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
- GO111MODULE=on
|
||||
goos:
|
||||
- windows
|
||||
goarch:
|
||||
- 386
|
||||
- amd64
|
||||
- arm
|
||||
goarm:
|
||||
- 7
|
||||
mod_timestamp: "{{ .CommitTimestamp }}"
|
||||
flags:
|
||||
- -trimpath
|
||||
ldflags:
|
||||
- -s -w -X github.com/Mrs4s/go-cqhttp/coolq.Version=v{{.Version}}
|
||||
|
||||
checksum:
|
||||
name_template: '{{ .ProjectName }}_checksums.txt'
|
||||
name_template: "{{ .ProjectName }}_checksums.txt"
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- '^docs:'
|
||||
- '^test:'
|
||||
- "^docs:"
|
||||
- "^test:"
|
||||
- fix typo
|
||||
- Merge pull request
|
||||
- Merge branch
|
||||
@ -44,7 +61,18 @@ changelog:
|
||||
- go mod tidy
|
||||
|
||||
archives:
|
||||
- name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}'
|
||||
- id: binary
|
||||
builds:
|
||||
- win
|
||||
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: binary
|
||||
- id: nowin
|
||||
builds:
|
||||
- nowin
|
||||
- win
|
||||
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
@ -52,7 +80,8 @@ archives:
|
||||
nfpms:
|
||||
- license: AGPL 3.0
|
||||
homepage: https://go-cqhttp.org
|
||||
file_name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}"
|
||||
file_name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
|
||||
formats:
|
||||
- deb
|
||||
- rpm
|
||||
- rpm
|
||||
maintainer: Mrs4s
|
||||
|
@ -1,4 +1,4 @@
|
||||
FROM golang:1.15.5-alpine AS builder
|
||||
FROM golang:1.16-alpine AS builder
|
||||
|
||||
RUN go env -w GO111MODULE=auto \
|
||||
&& go env -w CGO_ENABLED=0 \
|
||||
|
106
coolq/api.go
106
coolq/api.go
@ -14,14 +14,16 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/binary"
|
||||
"github.com/Mrs4s/MiraiGo/client"
|
||||
"github.com/Mrs4s/MiraiGo/message"
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
)
|
||||
|
||||
// Version go-cqhttp的版本信息,在编译时使用ldflags进行覆盖
|
||||
@ -69,10 +71,13 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
|
||||
}
|
||||
for _, g := range bot.Client.GroupList {
|
||||
gs = append(gs, MSG{
|
||||
"group_id": g.Code,
|
||||
"group_name": g.Name,
|
||||
"max_member_count": g.MaxMemberCount,
|
||||
"member_count": g.MemberCount,
|
||||
"group_id": g.Code,
|
||||
"group_name": g.Name,
|
||||
"group_memo": g.Memo,
|
||||
"group_create_time": g.GroupCreateTime,
|
||||
"group_level": g.GroupLevel,
|
||||
"max_member_count": g.MaxMemberCount,
|
||||
"member_count": g.MemberCount,
|
||||
})
|
||||
}
|
||||
return OK(gs)
|
||||
@ -83,6 +88,9 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
|
||||
// https://git.io/Jtz1O
|
||||
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
if group == nil || noCache {
|
||||
group, _ = bot.Client.GetGroupInfo(groupID)
|
||||
}
|
||||
if group == nil {
|
||||
gid := strconv.FormatInt(groupID, 10)
|
||||
info, err := bot.Client.SearchGroupByKeyword(gid)
|
||||
@ -92,28 +100,28 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
|
||||
for _, g := range info {
|
||||
if g.Code == groupID {
|
||||
return OK(MSG{
|
||||
"group_id": g.Code,
|
||||
"group_name": g.Name,
|
||||
"max_member_count": 0,
|
||||
"member_count": 0,
|
||||
"group_id": g.Code,
|
||||
"group_name": g.Name,
|
||||
"group_memo": g.Memo,
|
||||
"group_create_time": 0,
|
||||
"group_level": 0,
|
||||
"max_member_count": 0,
|
||||
"member_count": 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在失败")
|
||||
} else {
|
||||
return OK(MSG{
|
||||
"group_id": group.Code,
|
||||
"group_name": group.Name,
|
||||
"group_memo": group.Memo,
|
||||
"group_create_time": group.GroupCreateTime,
|
||||
"group_level": group.GroupLevel,
|
||||
"max_member_count": group.MaxMemberCount,
|
||||
"member_count": group.MemberCount,
|
||||
})
|
||||
}
|
||||
if noCache {
|
||||
var err error
|
||||
group, err = bot.Client.GetGroupInfo(groupID)
|
||||
if err != nil {
|
||||
return Failed(100, "GET_GROUP_INFO_API_ERROR", err.Error())
|
||||
}
|
||||
}
|
||||
return OK(MSG{
|
||||
"group_id": group.Code,
|
||||
"group_name": group.Name,
|
||||
"max_member_count": group.MaxMemberCount,
|
||||
"member_count": group.MemberCount,
|
||||
})
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
|
||||
// CQGetGroupMemberList 获取群成员列表
|
||||
@ -142,12 +150,22 @@ func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
|
||||
// CQGetGroupMemberInfo 获取群成员信息
|
||||
//
|
||||
// https://git.io/Jtz1s
|
||||
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64) MSG {
|
||||
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) MSG {
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
if group == nil {
|
||||
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
|
||||
}
|
||||
member := group.FindMember(userID)
|
||||
var member *client.GroupMemberInfo
|
||||
if noCache {
|
||||
var err error
|
||||
member, err = bot.Client.GetMemberInfo(groupID, userID)
|
||||
if err != nil {
|
||||
log.Warnf("刷新群 %v 中成员 %v 失败: %v", groupID, userID, err)
|
||||
return Failed(100, "GET_MEMBER_INFO_API_ERROR", err.Error())
|
||||
}
|
||||
} else {
|
||||
member = group.FindMember(userID)
|
||||
}
|
||||
if member == nil {
|
||||
return Failed(100, "MEMBER_NOT_FOUND", "群员不存在")
|
||||
}
|
||||
@ -286,7 +304,7 @@ func (bot *CQBot) CQSendGroupMessage(groupID int64, i interface{}, autoEscape bo
|
||||
if mid == -1 {
|
||||
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
|
||||
}
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupID, groupID, limitedString(m.String()), mid)
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(ToStringMessage(elem, int64(mid))), mid)
|
||||
return OK(MSG{"message_id": mid})
|
||||
}
|
||||
str = func() string {
|
||||
@ -313,7 +331,7 @@ func (bot *CQBot) CQSendGroupMessage(groupID int64, i interface{}, autoEscape bo
|
||||
if mid == -1 {
|
||||
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
|
||||
}
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupID, groupID, limitedString(str), mid)
|
||||
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(str), mid)
|
||||
return OK(MSG{"message_id": mid})
|
||||
}
|
||||
|
||||
@ -842,12 +860,7 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
|
||||
|
||||
if reply.Exists() {
|
||||
autoEscape := global.EnsureBool(operation.Get("auto_escape"), false)
|
||||
|
||||
at := !isAnonymous && msgType == "group" // 除匿名消息场合外默认 true
|
||||
if operation.Get("at_sender").Exists() {
|
||||
at = operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group"
|
||||
}
|
||||
|
||||
at := operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group"
|
||||
if at && reply.IsArray() {
|
||||
// 在 reply 数组头部插入CQ码
|
||||
replySegments := make([]MSG, 0)
|
||||
@ -1065,7 +1078,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
|
||||
log.Warnf("获取群历史消息失败: %v", err)
|
||||
return Failed(100, "MESSAGES_API_ERROR", err.Error())
|
||||
}
|
||||
var ms = make([]MSG, 0, len(msg))
|
||||
ms := make([]MSG, 0, len(msg))
|
||||
for _, m := range msg {
|
||||
id := m.Id
|
||||
bot.checkMedia(m.Elements)
|
||||
@ -1091,7 +1104,7 @@ func (bot *CQBot) CQGetOnlineClients(noCache bool) MSG {
|
||||
return Failed(100, "REFRESH_STATUS_ERROR", err.Error())
|
||||
}
|
||||
}
|
||||
var d = make([]MSG, 0, len(bot.Client.OnlineClients))
|
||||
d := make([]MSG, 0, len(bot.Client.OnlineClients))
|
||||
for _, oc := range bot.Client.OnlineClients {
|
||||
d = append(d, MSG{
|
||||
"app_id": oc.AppId,
|
||||
@ -1135,14 +1148,6 @@ func (bot *CQBot) CQOcrImage(imageID string) MSG {
|
||||
return OK(rsp)
|
||||
}
|
||||
|
||||
// CQReloadEventFilter 扩展API-重载事件过滤器
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E9%87%8D%E8%BD%BD%E4%BA%8B%E4%BB%B6%E8%BF%87%E6%BB%A4%E5%99%A8
|
||||
func (bot *CQBot) CQReloadEventFilter() MSG {
|
||||
global.BootFilter()
|
||||
return OK(nil)
|
||||
}
|
||||
|
||||
// CQSetGroupPortrait 扩展API-设置群头像
|
||||
//
|
||||
// https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F
|
||||
@ -1251,7 +1256,7 @@ func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
|
||||
}
|
||||
list := make([]MSG, 0, len(msgList))
|
||||
for _, m := range msgList {
|
||||
var msg = MSG{
|
||||
msg := MSG{
|
||||
"sender_nick": m.SenderNick,
|
||||
"sender_time": m.SenderTime,
|
||||
"operator_time": m.AddDigestTime,
|
||||
@ -1368,10 +1373,15 @@ func convertGroupMemberInfo(groupID int64, m *client.GroupMemberInfo) MSG {
|
||||
}
|
||||
|
||||
func limitedString(str string) string {
|
||||
if strings.Count(str, "") <= 10 {
|
||||
if utf8.RuneCountInString(str) <= 10 {
|
||||
return str
|
||||
}
|
||||
limited := []rune(str)
|
||||
limited = limited[:10]
|
||||
b := utils.S2B(str)
|
||||
limited := make([]rune, 0, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
decodeRune, size := utf8.DecodeRune(b)
|
||||
b = b[size:]
|
||||
limited = append(limited, decodeRune)
|
||||
}
|
||||
return string(limited) + " ..."
|
||||
}
|
||||
|
58
coolq/bot.go
58
coolq/bot.go
@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/global/config"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/binary"
|
||||
"github.com/Mrs4s/MiraiGo/client"
|
||||
@ -30,11 +31,11 @@ var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
type CQBot struct {
|
||||
Client *client.QQClient
|
||||
|
||||
events []func(*bytes.Buffer)
|
||||
db *leveldb.DB
|
||||
friendReqCache sync.Map
|
||||
tempMsgCache sync.Map
|
||||
oneWayMsgCache sync.Map
|
||||
events []func(*bytes.Buffer)
|
||||
db *leveldb.DB
|
||||
friendReqCache sync.Map
|
||||
tempSessionCache sync.Map
|
||||
oneWayMsgCache sync.Map
|
||||
}
|
||||
|
||||
// MSG 消息Map
|
||||
@ -44,11 +45,18 @@ type MSG map[string]interface{}
|
||||
var ForceFragmented = false
|
||||
|
||||
// NewQQBot 初始化一个QQBot实例
|
||||
func NewQQBot(cli *client.QQClient, conf *global.JSONConfig) *CQBot {
|
||||
func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
|
||||
bot := &CQBot{
|
||||
Client: cli,
|
||||
}
|
||||
if conf.EnableDB {
|
||||
enableLevelDB := false
|
||||
node, ok := conf.Database["leveldb"]
|
||||
if ok {
|
||||
lconf := new(config.LevelDBConfig)
|
||||
_ = node.Decode(lconf)
|
||||
enableLevelDB = lconf.Enable
|
||||
}
|
||||
if enableLevelDB {
|
||||
p := path.Join("data", "leveldb")
|
||||
db, err := leveldb.OpenFile(p, nil)
|
||||
if err != nil {
|
||||
@ -62,7 +70,7 @@ func NewQQBot(cli *client.QQClient, conf *global.JSONConfig) *CQBot {
|
||||
}
|
||||
bot.Client.OnPrivateMessage(bot.privateMessageEvent)
|
||||
bot.Client.OnGroupMessage(bot.groupMessageEvent)
|
||||
if conf.EnableSelfMessage {
|
||||
if conf.Message.ReportSelfMessage {
|
||||
bot.Client.OnSelfPrivateMessage(bot.privateMessageEvent)
|
||||
bot.Client.OnSelfGroupMessage(bot.groupMessageEvent)
|
||||
}
|
||||
@ -86,16 +94,17 @@ func NewQQBot(cli *client.QQClient, conf *global.JSONConfig) *CQBot {
|
||||
bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent)
|
||||
bot.Client.OnGroupDigest(bot.groupEssenceMsg)
|
||||
go func() {
|
||||
i := conf.HeartbeatInterval
|
||||
if i < 0 {
|
||||
i := conf.Heartbeat.Interval
|
||||
if i < 0 || conf.Heartbeat.Disabled {
|
||||
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
|
||||
return
|
||||
}
|
||||
if i == 0 {
|
||||
i = 5
|
||||
}
|
||||
t := time.NewTicker(time.Second * time.Duration(i))
|
||||
for {
|
||||
time.Sleep(time.Second * i)
|
||||
<-t.C
|
||||
bot.dispatchEventMessage(MSG{
|
||||
"time": time.Now().Unix(),
|
||||
"self_id": bot.Client.Uin,
|
||||
@ -174,7 +183,7 @@ func (bot *CQBot) UploadLocalImageAsPrivate(userID int64, img *LocalImageElement
|
||||
|
||||
// SendGroupMessage 发送群消息
|
||||
func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) int32 {
|
||||
var newElem = make([]message.IMessageElement, 0, len(m.Elements))
|
||||
newElem := make([]message.IMessageElement, 0, len(m.Elements))
|
||||
group := bot.Client.FindGroup(groupID)
|
||||
for _, elem := range m.Elements {
|
||||
if i, ok := elem.(*LocalImageElement); ok {
|
||||
@ -246,7 +255,7 @@ func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) int
|
||||
|
||||
// SendPrivateMessage 发送私聊消息
|
||||
func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.SendingMessage) int32 {
|
||||
var newElem = make([]message.IMessageElement, 0, len(m.Elements))
|
||||
newElem := make([]message.IMessageElement, 0, len(m.Elements))
|
||||
for _, elem := range m.Elements {
|
||||
if i, ok := elem.(*LocalImageElement); ok {
|
||||
fm, err := bot.UploadLocalImageAsPrivate(target, i)
|
||||
@ -297,22 +306,24 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
|
||||
if msg != nil {
|
||||
id = bot.InsertPrivateMessage(msg)
|
||||
}
|
||||
} else if code, ok := bot.tempMsgCache.Load(target); ok || groupID != 0 { // 临时会话
|
||||
} else if session, ok := bot.tempSessionCache.Load(target); ok || groupID != 0 { // 临时会话
|
||||
switch {
|
||||
case bot.Client.FindGroup(groupID) == nil:
|
||||
case groupID != 0 && bot.Client.FindGroup(groupID) == nil:
|
||||
log.Errorf("错误: 找不到群(%v)", groupID)
|
||||
id = -1
|
||||
case groupID != 0 && !bot.Client.FindGroup(groupID).AdministratorOrOwner():
|
||||
log.Errorf("错误: 机器人在群(%v) 为非管理员或群主, 无法主动发起临时会话", groupID)
|
||||
id = -1
|
||||
case groupID != 0 && bot.Client.FindGroup(groupID).FindMember(target) == nil:
|
||||
log.Errorf("错误: 群员(%v) 不在 群(%v), 无法发起临时会话", target, groupID)
|
||||
id = -1
|
||||
default:
|
||||
if code != nil {
|
||||
groupID = code.(int64)
|
||||
if session == nil && groupID != 0 {
|
||||
bot.Client.SendGroupTempMessage(groupID, target, m)
|
||||
break
|
||||
}
|
||||
msg, err := session.(*client.TempSessionInfo).SendMessage(m)
|
||||
if err != nil {
|
||||
log.Errorf("发送临时会话消息失败: %v", err)
|
||||
break
|
||||
}
|
||||
msg := bot.Client.SendTempMessage(groupID, target, m)
|
||||
if msg != nil {
|
||||
id = bot.InsertTempMessage(target, msg)
|
||||
}
|
||||
@ -429,10 +440,6 @@ func (bot *CQBot) Release() {
|
||||
}
|
||||
|
||||
func (bot *CQBot) dispatchEventMessage(m MSG) {
|
||||
if global.EventFilter != nil && !global.EventFilter.Eval(global.MSG(m)) {
|
||||
log.Debug("Event filtered!")
|
||||
return
|
||||
}
|
||||
buf := global.NewBuffer()
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(bot.events))
|
||||
@ -445,6 +452,7 @@ func (bot *CQBot) dispatchEventMessage(m MSG) {
|
||||
log.Warnf("处理事件 %v 时出现错误: %v \n%s", m, pan, debug.Stack())
|
||||
}
|
||||
}()
|
||||
|
||||
start := time.Now()
|
||||
fn(buf)
|
||||
end := time.Now()
|
||||
|
280
coolq/cqcode.go
280
coolq/cqcode.go
@ -4,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
goBinary "encoding/binary"
|
||||
"encoding/hex"
|
||||
xml2 "encoding/xml"
|
||||
"errors"
|
||||
@ -29,6 +28,7 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/global/config"
|
||||
)
|
||||
|
||||
/*
|
||||
@ -37,6 +37,8 @@ var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
|
||||
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
|
||||
*/
|
||||
|
||||
var conf *config.Config
|
||||
|
||||
// IgnoreInvalidCQCode 是否忽略无效CQ码
|
||||
var IgnoreInvalidCQCode = false
|
||||
|
||||
@ -47,15 +49,9 @@ var SplitURL = false
|
||||
var magicCQ = uint32(0)
|
||||
|
||||
func init() {
|
||||
const sizeInt = int(unsafe.Sizeof(0))
|
||||
x := 0x1234
|
||||
p := unsafe.Pointer(&x)
|
||||
p2 := (*[sizeInt]byte)(p)
|
||||
if p2[0] == 0 {
|
||||
magicCQ = goBinary.BigEndian.Uint32([]byte("[CQ:"))
|
||||
} else {
|
||||
magicCQ = goBinary.LittleEndian.Uint32([]byte("[CQ:"))
|
||||
}
|
||||
conf = config.Get()
|
||||
CQHeader := "[CQ:"
|
||||
magicCQ = *(*uint32)(unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&CQHeader)).Data))
|
||||
}
|
||||
|
||||
// add 指针运算
|
||||
@ -63,8 +59,11 @@ func add(ptr unsafe.Pointer, offset uintptr) unsafe.Pointer {
|
||||
return unsafe.Pointer(uintptr(ptr) + offset)
|
||||
}
|
||||
|
||||
const maxImageSize = 1024 * 1024 * 30 // 30MB
|
||||
const maxVideoSize = 1024 * 1024 * 100 // 100MB
|
||||
const (
|
||||
maxImageSize = 1024 * 1024 * 30 // 30MB
|
||||
maxVideoSize = 1024 * 1024 * 100 // 100MB
|
||||
)
|
||||
|
||||
// PokeElement 拍一拍
|
||||
type PokeElement struct {
|
||||
Target int64
|
||||
@ -139,14 +138,35 @@ func ToArrayMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r []M
|
||||
return ok
|
||||
})
|
||||
if reply != nil {
|
||||
r = append(r, MSG{
|
||||
"type": "reply",
|
||||
"data": map[string]string{"id": fmt.Sprint(toGlobalID(id, reply.(*message.ReplyElement).ReplySeq))},
|
||||
})
|
||||
replyElem := reply.(*message.ReplyElement)
|
||||
if conf.Message.ExtraReplyData {
|
||||
r = append(r, MSG{
|
||||
"type": "reply",
|
||||
"data": map[string]string{
|
||||
"id": fmt.Sprint(toGlobalID(id, reply.(*message.ReplyElement).ReplySeq)),
|
||||
"seq": string(replyElem.ReplySeq),
|
||||
"qq": strconv.FormatInt(replyElem.Sender, 10),
|
||||
"time": string(replyElem.Time),
|
||||
"text": CQCodeEscapeValue(CQCodeEscapeText(ToStringMessage(replyElem.Elements, id))),
|
||||
},
|
||||
})
|
||||
} else {
|
||||
r = append(r, MSG{
|
||||
"type": "reply",
|
||||
"data": map[string]string{"id": fmt.Sprint(toGlobalID(id, replyElem.ReplySeq))},
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, elem := range e {
|
||||
for i, elem := range e {
|
||||
var m MSG
|
||||
switch o := elem.(type) {
|
||||
case *message.ReplyElement:
|
||||
if conf.Message.RemoveReplyAt && len(e) > i+1 {
|
||||
elem, ok := e[i+1].(*message.AtElement)
|
||||
if ok && elem.Target == o.Sender {
|
||||
e[i+1] = nil
|
||||
}
|
||||
}
|
||||
case *message.TextElement:
|
||||
m = MSG{
|
||||
"type": "text",
|
||||
@ -233,7 +253,7 @@ func ToArrayMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r []M
|
||||
} else {
|
||||
m = MSG{
|
||||
"type": "image",
|
||||
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": CQCodeEscapeText(o.Url)},
|
||||
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": o.Url},
|
||||
}
|
||||
}
|
||||
case *message.FriendImageElement:
|
||||
@ -245,7 +265,7 @@ func ToArrayMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r []M
|
||||
} else {
|
||||
m = MSG{
|
||||
"type": "image",
|
||||
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": CQCodeEscapeText(o.Url)},
|
||||
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": o.Url},
|
||||
}
|
||||
}
|
||||
case *message.GroupFlashImgElement:
|
||||
@ -291,10 +311,25 @@ func ToStringMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r st
|
||||
return ok
|
||||
})
|
||||
if reply != nil {
|
||||
r += fmt.Sprintf("[CQ:reply,id=%d]", toGlobalID(id, reply.(*message.ReplyElement).ReplySeq))
|
||||
replyElem := reply.(*message.ReplyElement)
|
||||
if conf.Message.ExtraReplyData {
|
||||
r += fmt.Sprintf("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]",
|
||||
toGlobalID(id, replyElem.ReplySeq),
|
||||
replyElem.ReplySeq, replyElem.Sender, replyElem.Time,
|
||||
CQCodeEscapeValue(CQCodeEscapeText(ToStringMessage(replyElem.Elements, id))))
|
||||
} else {
|
||||
r += fmt.Sprintf("[CQ:reply,id=%d]", toGlobalID(id, replyElem.ReplySeq))
|
||||
}
|
||||
}
|
||||
for _, elem := range e {
|
||||
for i, elem := range e {
|
||||
switch o := elem.(type) {
|
||||
case *message.ReplyElement:
|
||||
if conf.Message.RemoveReplyAt && len(e) > i+1 {
|
||||
elem, ok := e[i+1].(*message.AtElement)
|
||||
if ok && elem.Target == o.Sender {
|
||||
e[i+1] = nil
|
||||
}
|
||||
}
|
||||
case *message.TextElement:
|
||||
r += CQCodeEscapeText(o.Content)
|
||||
case *message.AtElement:
|
||||
@ -331,13 +366,13 @@ func ToStringMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r st
|
||||
if ur {
|
||||
r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image")
|
||||
} else {
|
||||
r += fmt.Sprintf("[CQ:image,file=%s,url=%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeText(o.Url))
|
||||
r += fmt.Sprintf("[CQ:image,file=%s,url=%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeValue(o.Url))
|
||||
}
|
||||
case *message.FriendImageElement:
|
||||
if ur {
|
||||
r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image")
|
||||
} else {
|
||||
r += fmt.Sprintf("[CQ:image,file=%s,url=%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeText(o.Url))
|
||||
r += fmt.Sprintf("[CQ:image,file=%s,url=%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeValue(o.Url))
|
||||
}
|
||||
case *message.GroupFlashImgElement:
|
||||
return fmt.Sprintf("[CQ:image,type=flash,file=%s]", o.Filename)
|
||||
@ -360,7 +395,7 @@ func ToStringMessage(e []message.IMessageElement, id int64, isRaw ...bool) (r st
|
||||
// ConvertStringMessage 将消息字符串转为消息元素数组
|
||||
func (bot *CQBot) ConvertStringMessage(s string, isGroup bool) (r []message.IMessageElement) {
|
||||
var t, key string
|
||||
var d = map[string]string{}
|
||||
d := map[string]string{}
|
||||
ptr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)
|
||||
l := len(s)
|
||||
i, j, CQBegin := 0, 0, 0
|
||||
@ -375,7 +410,49 @@ func (bot *CQBot) ConvertStringMessage(s string, isGroup bool) (r []message.IMes
|
||||
}
|
||||
mid, err := strconv.Atoi(d["id"])
|
||||
customText := d["text"]
|
||||
if err == nil {
|
||||
switch {
|
||||
case customText != "":
|
||||
var elem *message.ReplyElement
|
||||
var org MSG
|
||||
sender, senderErr := strconv.ParseInt(d["qq"], 10, 64)
|
||||
if senderErr != nil && err != nil {
|
||||
log.Warnf("警告: 自定义 Reply 元素中必须包含 Uin 或 id")
|
||||
break
|
||||
}
|
||||
msgTime, timeErr := strconv.ParseInt(d["time"], 10, 64)
|
||||
if timeErr != nil {
|
||||
msgTime = time.Now().Unix()
|
||||
}
|
||||
messageSeq, seqErr := strconv.ParseInt(d["seq"], 10, 64)
|
||||
if err == nil {
|
||||
org = bot.GetMessage(int32(mid))
|
||||
}
|
||||
if org != nil {
|
||||
elem = &message.ReplyElement{
|
||||
ReplySeq: org["message-id"].(int32),
|
||||
Sender: org["sender"].(message.Sender).Uin,
|
||||
Time: org["time"].(int32),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
}
|
||||
if senderErr != nil {
|
||||
elem.Sender = sender
|
||||
}
|
||||
if timeErr != nil {
|
||||
elem.Time = int32(msgTime)
|
||||
}
|
||||
if seqErr != nil {
|
||||
elem.ReplySeq = int32(messageSeq)
|
||||
}
|
||||
} else {
|
||||
elem = &message.ReplyElement{
|
||||
ReplySeq: int32(messageSeq),
|
||||
Sender: sender,
|
||||
Time: int32(msgTime),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
}
|
||||
}
|
||||
r = append([]message.IMessageElement{elem}, r...)
|
||||
case err == nil:
|
||||
org := bot.GetMessage(int32(mid))
|
||||
if org != nil {
|
||||
r = append([]message.IMessageElement{
|
||||
@ -386,38 +463,23 @@ func (bot *CQBot) ConvertStringMessage(s string, isGroup bool) (r []message.IMes
|
||||
Elements: bot.ConvertStringMessage(org["message"].(string), isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
}
|
||||
} else if customText != "" {
|
||||
sender, err := strconv.ParseInt(d["qq"], 10, 64)
|
||||
if err != nil {
|
||||
log.Warnf("警告:自定义 Reply 元素中必须包含 Uin")
|
||||
return
|
||||
}
|
||||
msgTime, err := strconv.ParseInt(d["time"], 10, 64)
|
||||
if err != nil {
|
||||
msgTime = time.Now().Unix()
|
||||
}
|
||||
messageSeq, err := strconv.ParseInt(d["seq"], 10, 64)
|
||||
if err != nil {
|
||||
messageSeq = 0
|
||||
}
|
||||
r = append([]message.IMessageElement{
|
||||
&message.ReplyElement{
|
||||
ReplySeq: int32(messageSeq),
|
||||
Sender: sender,
|
||||
Time: int32(msgTime),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
default:
|
||||
log.Warnf("警告: Reply 元素中必须包含 text 或 id")
|
||||
}
|
||||
return
|
||||
}
|
||||
if t == "forward" { // 单独处理转发
|
||||
if id, ok := d["id"]; ok {
|
||||
r = []message.IMessageElement{bot.Client.DownloadForwardMessage(id)}
|
||||
return
|
||||
if fwdMsg := bot.Client.DownloadForwardMessage(id); fwdMsg == nil {
|
||||
log.Warnf("警告: Forward 信息不存在或已过期")
|
||||
} else {
|
||||
r = []message.IMessageElement{fwdMsg}
|
||||
}
|
||||
} else {
|
||||
log.Warnf("警告: Forward 元素中必须包含 id")
|
||||
}
|
||||
return
|
||||
}
|
||||
elem, err := bot.ToElement(t, d, isGroup)
|
||||
if err != nil {
|
||||
@ -443,7 +505,13 @@ S1: // Plain Text
|
||||
if *(*byte)(add(ptr, uintptr(i))) == '[' && i+4 < l &&
|
||||
*(*uint32)(add(ptr, uintptr(i))) == magicCQ { // Magic :uint32([]byte("[CQ:"))
|
||||
if i > j {
|
||||
r = append(r, message.NewText(CQCodeUnescapeText(s[j:i])))
|
||||
if SplitURL {
|
||||
for _, str := range global.SplitURL(CQCodeUnescapeText(s[j:i])) {
|
||||
r = append(r, message.NewText(str))
|
||||
}
|
||||
} else {
|
||||
r = append(r, message.NewText(CQCodeUnescapeText(s[j:i])))
|
||||
}
|
||||
}
|
||||
CQBegin = i
|
||||
i += 4
|
||||
@ -501,7 +569,13 @@ S4: // CQCode param value
|
||||
goto End
|
||||
End:
|
||||
if i > j {
|
||||
r = append(r, message.NewText(CQCodeUnescapeText(s[j:i])))
|
||||
if SplitURL {
|
||||
for _, str := range global.SplitURL(CQCodeUnescapeText(s[j:i])) {
|
||||
r = append(r, message.NewText(str))
|
||||
}
|
||||
} else {
|
||||
r = append(r, message.NewText(CQCodeUnescapeText(s[j:i])))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -517,9 +591,51 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
|
||||
return
|
||||
}
|
||||
}
|
||||
mid, err := strconv.Atoi(e.Get("data").Get("id").String())
|
||||
customText := e.Get("data").Get("text").String()
|
||||
if err == nil {
|
||||
mid, err := strconv.Atoi(e.Get("data.id").String())
|
||||
customText := e.Get("data.text").String()
|
||||
switch {
|
||||
case customText != "":
|
||||
var elem *message.ReplyElement
|
||||
var org MSG
|
||||
sender, senderErr := strconv.ParseInt(e.Get("data.qq").String(), 10, 64)
|
||||
if senderErr != nil && err != nil {
|
||||
log.Warnf("警告: 自定义 Reply 元素中必须包含 Uin 或 id")
|
||||
break
|
||||
}
|
||||
msgTime, timeErr := strconv.ParseInt(e.Get("data.time").String(), 10, 64)
|
||||
if timeErr != nil {
|
||||
msgTime = time.Now().Unix()
|
||||
}
|
||||
messageSeq, seqErr := strconv.ParseInt(e.Get("data.seq").String(), 10, 64)
|
||||
if err == nil {
|
||||
org = bot.GetMessage(int32(mid))
|
||||
}
|
||||
if org != nil {
|
||||
elem = &message.ReplyElement{
|
||||
ReplySeq: org["message-id"].(int32),
|
||||
Sender: org["sender"].(message.Sender).Uin,
|
||||
Time: org["time"].(int32),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
}
|
||||
if senderErr != nil {
|
||||
elem.Sender = sender
|
||||
}
|
||||
if timeErr != nil {
|
||||
elem.Time = int32(msgTime)
|
||||
}
|
||||
if seqErr != nil {
|
||||
elem.ReplySeq = int32(messageSeq)
|
||||
}
|
||||
} else {
|
||||
elem = &message.ReplyElement{
|
||||
ReplySeq: int32(messageSeq),
|
||||
Sender: sender,
|
||||
Time: int32(msgTime),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
}
|
||||
}
|
||||
r = append([]message.IMessageElement{elem}, r...)
|
||||
case err == nil:
|
||||
org := bot.GetMessage(int32(mid))
|
||||
if org != nil {
|
||||
r = append([]message.IMessageElement{
|
||||
@ -530,35 +646,23 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
|
||||
Elements: bot.ConvertStringMessage(org["message"].(string), isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
}
|
||||
} else if customText != "" {
|
||||
sender, err := strconv.ParseInt(e.Get("data").Get("qq").String(), 10, 64)
|
||||
if err != nil {
|
||||
log.Warnf("警告:自定义 Reply 元素中必须包含 Uin")
|
||||
return
|
||||
}
|
||||
msgTime, err := strconv.ParseInt(e.Get("data").Get("time").String(), 10, 64)
|
||||
if err != nil {
|
||||
msgTime = time.Now().Unix()
|
||||
}
|
||||
messageSeq, err := strconv.ParseInt(e.Get("data").Get("seq").String(), 10, 64)
|
||||
if err != nil {
|
||||
messageSeq = 0
|
||||
}
|
||||
r = append([]message.IMessageElement{
|
||||
&message.ReplyElement{
|
||||
ReplySeq: int32(messageSeq),
|
||||
Sender: sender,
|
||||
Time: int32(msgTime),
|
||||
Elements: bot.ConvertStringMessage(customText, isGroup),
|
||||
},
|
||||
}, r...)
|
||||
return
|
||||
default:
|
||||
log.Warnf("警告: Reply 元素中必须包含 text 或 id")
|
||||
}
|
||||
return
|
||||
}
|
||||
if t == "forward" {
|
||||
r = []message.IMessageElement{bot.Client.DownloadForwardMessage(e.Get("data.id").String())}
|
||||
id := e.Get("data.id").String()
|
||||
if id == "" {
|
||||
log.Warnf("警告: Forward 元素中必须包含 id")
|
||||
} else {
|
||||
if fwdMsg := bot.Client.DownloadForwardMessage(id); fwdMsg == nil {
|
||||
log.Warnf("警告: Forward 信息不存在或已过期")
|
||||
} else {
|
||||
r = []message.IMessageElement{fwdMsg}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
d := make(map[string]string)
|
||||
@ -699,7 +803,11 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
|
||||
return message.AtAll(), nil
|
||||
}
|
||||
t, _ := strconv.ParseInt(qq, 10, 64)
|
||||
return message.NewAt(t), nil
|
||||
name := strings.TrimSpace(d["name"])
|
||||
if len(name) > 0 {
|
||||
name = "@" + name
|
||||
}
|
||||
return message.NewAt(t, name), nil
|
||||
case "share":
|
||||
return message.NewUrlShare(d["url"], d["title"], d["content"], d["image"]), nil
|
||||
case "music":
|
||||
@ -762,14 +870,14 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
|
||||
}
|
||||
if d["type"] == "custom" {
|
||||
if d["subtype"] != "" {
|
||||
var subtype = map[string]int{
|
||||
subtype := map[string]int{
|
||||
"qq": message.QQMusic,
|
||||
"163": message.CloudMusic,
|
||||
"migu": message.MiguMusic,
|
||||
"kugou": message.KugouMusic,
|
||||
"kuwo": message.KuwoMusic,
|
||||
}
|
||||
var musicType = 0
|
||||
musicType := 0
|
||||
if tp, ok := subtype[d["subtype"]]; ok {
|
||||
musicType = tp
|
||||
}
|
||||
@ -860,7 +968,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var header = make([]byte, 4)
|
||||
header := make([]byte, 4)
|
||||
_, err = video.Read(header)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -972,7 +1080,7 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
|
||||
}
|
||||
hash := md5.Sum([]byte(f))
|
||||
cacheFile := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache")
|
||||
var maxSize = func() int64 {
|
||||
maxSize := func() int64 {
|
||||
if video {
|
||||
return maxVideoSize
|
||||
}
|
||||
|
@ -103,10 +103,11 @@ func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage)
|
||||
bot.dispatchEventMessage(gm)
|
||||
}
|
||||
|
||||
func (bot *CQBot) tempMessageEvent(c *client.QQClient, m *message.TempMessage) {
|
||||
func (bot *CQBot) tempMessageEvent(c *client.QQClient, e *client.TempMessageEvent) {
|
||||
m := e.Message
|
||||
bot.checkMedia(m.Elements)
|
||||
cqm := ToStringMessage(m.Elements, m.Sender.Uin, true)
|
||||
bot.tempMsgCache.Store(m.Sender.Uin, m.GroupCode)
|
||||
bot.tempSessionCache.Store(m.Sender.Uin, e.Session)
|
||||
id := m.Id
|
||||
if bot.db != nil {
|
||||
id = bot.InsertTempMessage(m.Sender.Uin, m)
|
||||
@ -116,6 +117,7 @@ func (bot *CQBot) tempMessageEvent(c *client.QQClient, m *message.TempMessage) {
|
||||
"post_type": "message",
|
||||
"message_type": "private",
|
||||
"sub_type": "group",
|
||||
"temp_source": e.Session.Source,
|
||||
"message_id": id,
|
||||
"user_id": m.Sender.Uin,
|
||||
"message": ToFormattedMessage(m.Elements, m.Sender.Uin, false),
|
||||
@ -384,7 +386,7 @@ func (bot *CQBot) friendRequestEvent(c *client.QQClient, e *client.NewFriendRequ
|
||||
|
||||
func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent) {
|
||||
log.Infof("添加了新好友: %v(%v)", e.Friend.Nickname, e.Friend.Uin)
|
||||
bot.tempMsgCache.Delete(e.Friend.Uin)
|
||||
bot.tempSessionCache.Delete(e.Friend.Uin)
|
||||
bot.dispatchEventMessage(MSG{
|
||||
"post_type": "notice",
|
||||
"notice_type": "friend_add",
|
||||
|
208
docs/config.md
208
docs/config.md
@ -1,97 +1,137 @@
|
||||
# 配置
|
||||
|
||||
go-cqhttp 包含 `config.hjson` 和 `device.json` 两个配置文件, 其中 `config.json` 为运行配置 `device.json` 为虚拟设备信息.
|
||||
|
||||
## 从原CQHTTP导入配置
|
||||
|
||||
go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
|
||||
|
||||
1. 找到CQHTTP原配置文件 `{CQ工作目录}/app/io.github.richardchien.coolqhttpapi/config/{qq号}.json`
|
||||
2. 将文件复制到go-cqhttp根目录并重命名为 `cqhttp.json`
|
||||
3. 重启go-cqhttp后将自动导入配置
|
||||
go-cqhttp 包含 `config.yml` 和 `device.json` 两个配置文件, 其中 `config.yml` 为运行配置 `device.json` 为虚拟设备信息.
|
||||
|
||||
## 配置信息
|
||||
|
||||
go-cqhttp 的配置文件采用 YAML , 在使用之前希望你能了解 YAML 的语法([教程](https://www.runoob.com/w3cnote/yaml-intro.html))
|
||||
|
||||
默认生成的配置文件如下所示:
|
||||
|
||||
````json
|
||||
{
|
||||
"uin": 0,
|
||||
"password": "",
|
||||
"encrypt_password": false,
|
||||
"password_encrypted": "",
|
||||
"enable_db": true,
|
||||
"enable_self_message": false,
|
||||
"access_token": "",
|
||||
"relogin": {
|
||||
"enabled": true,
|
||||
"relogin_delay": 3,
|
||||
"max_relogin_times": 0
|
||||
},
|
||||
"_rate_limit": {
|
||||
"enabled": false,
|
||||
"frequency": 1,
|
||||
"bucket_size": 1
|
||||
},
|
||||
"post_message_format": "string",
|
||||
"ignore_invalid_cqcode": false,
|
||||
"force_fragmented": true,
|
||||
"heartbeat_interval": 5,
|
||||
"use_sso_address": false,
|
||||
"http_config": {
|
||||
"enabled": true,
|
||||
"host": "0.0.0.0",
|
||||
"port": 5700,
|
||||
"timeout": 5,
|
||||
"post_urls": {
|
||||
"url:port": "secret"
|
||||
}
|
||||
},
|
||||
"ws_config": {
|
||||
"enabled": true,
|
||||
"host": "0.0.0.0",
|
||||
"port": 6700
|
||||
},
|
||||
"ws_reverse_servers": [
|
||||
{
|
||||
"enabled": false,
|
||||
"reverse_url": "ws://you_websocket_universal.server",
|
||||
"reverse_api_url": "ws://you_websocket_api.server",
|
||||
"reverse_event_url": "ws://you_websocket_event.server",
|
||||
"reverse_reconnect_interval": 3000
|
||||
}
|
||||
]
|
||||
}
|
||||
````yaml
|
||||
# go-cqhttp 默认配置文件
|
||||
|
||||
account: # 账号相关
|
||||
uin: 1233456 # QQ账号
|
||||
password: '' # 密码为空时使用扫码登录
|
||||
encrypt: false # 是否开启密码加密
|
||||
relogin: # 重连设置
|
||||
disabled: false
|
||||
delay: 3 # 重连延迟, 单位秒
|
||||
interval: 0 # 重连间隔
|
||||
max-times: 0 # 最大重连次数, 0为无限制
|
||||
|
||||
# 是否使用服务器下发的新地址进行重连
|
||||
# 注意, 此设置可能导致在海外服务器上连接情况更差
|
||||
use-sso-address: true
|
||||
|
||||
heartbeat:
|
||||
disabled: false # 是否开启心跳事件上报
|
||||
# 心跳频率, 单位秒
|
||||
# -1 为关闭心跳
|
||||
interval: 5
|
||||
|
||||
message:
|
||||
# 上报数据类型
|
||||
# 可选: string,array
|
||||
post-format: string
|
||||
# 是否忽略无效的CQ码, 如果为假将原样发送
|
||||
ignore-invalid-cqcode: false
|
||||
# 是否强制分片发送消息
|
||||
# 分片发送将会带来更快的速度
|
||||
# 但是兼容性会有些问题
|
||||
force-fragment: false
|
||||
# 是否将url分片发送
|
||||
fix-url: false
|
||||
# 下载图片等请求网络代理
|
||||
proxy-rewrite: ''
|
||||
# 是否上报自身消息
|
||||
report-self-message: false
|
||||
|
||||
output:
|
||||
# 日志等级 trace,debug,info,warn,error日志等级 trace,debug,info,warn,error
|
||||
log-level: warn
|
||||
# 是否启用 DEBUG
|
||||
debug: false # 开启调试模式
|
||||
|
||||
# 默认中间件锚点
|
||||
default-middlewares: &default
|
||||
# 访问密钥, 强烈推荐在公网的服务器设置
|
||||
access-token: ''
|
||||
# 事件过滤器文件目录
|
||||
filter: ''
|
||||
# API限速设置
|
||||
# 该设置为全局生效
|
||||
# 原 cqhttp 虽然启用了 rate_limit 后缀, 但是基本没插件适配
|
||||
# 目前该限速设置为令牌桶算法, 请参考:
|
||||
# https://baike.baidu.com/item/%E4%BB%A4%E7%89%8C%E6%A1%B6%E7%AE%97%E6%B3%95/6597000?fr=aladdin
|
||||
rate-limit:
|
||||
enabled: false # 是否启用限速
|
||||
frequency: 1 # 令牌回复频率, 单位秒
|
||||
bucket: 1 # 令牌桶大小
|
||||
|
||||
servers:
|
||||
# HTTP 通信设置
|
||||
- http:
|
||||
# 是否关闭正向HTTP服务器
|
||||
disabled: false
|
||||
# 服务端监听地址
|
||||
host: 127.0.0.1
|
||||
# 服务端监听端口
|
||||
port: 5700
|
||||
# 反向HTTP超时时间, 单位秒
|
||||
# 最小值为5,小于5将会忽略本项设置
|
||||
timeout: 5
|
||||
middlewares:
|
||||
<<: *default # 引用默认中间件
|
||||
# 反向HTTP POST地址列表
|
||||
post:
|
||||
#- url: '' # 地址
|
||||
# secret: '' # 密钥
|
||||
#- url: 127.0.0.1:5701 # 地址
|
||||
# secret: '' # 密钥
|
||||
|
||||
# 正向WS设置
|
||||
- ws:
|
||||
# 是否禁用正向WS服务器
|
||||
disabled: true
|
||||
# 正向WS服务器监听地址
|
||||
host: 127.0.0.1
|
||||
# 正向WS服务器监听端口
|
||||
port: 6700
|
||||
middlewares:
|
||||
<<: *default # 引用默认中间件
|
||||
|
||||
- ws-reverse:
|
||||
# 是否禁用当前反向WS服务
|
||||
disabled: true
|
||||
# 反向WS Universal 地址
|
||||
# 注意 设置了此项地址后下面两项将会被忽略
|
||||
universal: ws://your_websocket_universal.server
|
||||
# 反向WS API 地址
|
||||
api: ws://your_websocket_api.server
|
||||
# 反向WS Event 地址
|
||||
event: ws://your_websocket_event.server
|
||||
# 重连间隔 单位毫秒
|
||||
reconnect-interval: 3000
|
||||
middlewares:
|
||||
<<: *default # 引用默认中间件
|
||||
|
||||
# 可添加更多
|
||||
#- ws-reverse:
|
||||
#- ws:
|
||||
#- http:
|
||||
|
||||
database: # 数据库相关设置
|
||||
leveldb:
|
||||
# 是否启用内置leveldb数据库
|
||||
# 启用将会增加10-20MB的内存占用和一定的磁盘空间
|
||||
# 关闭将无法使用 撤回 回复 get_msg 等上下文相关功能
|
||||
enable: true
|
||||
````
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --------------------- | -------- | ---------------------------------------------------------------------------------------- |
|
||||
| uin | int64 | 登录用QQ号 |
|
||||
| password | string | 登录用密码 |
|
||||
| encrypt_password | bool | 是否对密码进行加密. |
|
||||
| password_encrypted | string | 加密后的密码(请勿修改) |
|
||||
| enable_db | bool | 是否开启内置数据库, 关闭后将无法使用 **回复/撤回** 等上下文相关接口 |
|
||||
| enable_self_message | bool | 是否启用 `message_sent` 事件 |
|
||||
| access_token | string | 同CQHTTP的 `access_token` 用于身份验证 |
|
||||
| relogin | bool | 是否自动重新登录 |
|
||||
| relogin_delay | int | 重登录延时(秒) |
|
||||
| max_relogin_times | uint | 最大重登录次数,若0则不设置上限 |
|
||||
| _rate_limit | bool | 是否启用API调用限速 |
|
||||
| frequency | float64 | 1s内能调用API的次数 |
|
||||
| bucket_size | int | 令牌桶的大小,默认为1,修改此值可允许一定程度内连续调用api |
|
||||
| post_message_format | string | 上报信息类型 |
|
||||
| ignore_invalid_cqcode | bool | 是否忽略错误的CQ码 |
|
||||
| force_fragmented | bool | 是否强制分片发送群长消息 |
|
||||
| fix_url | bool | 是否对链接的发送进行预处理, 可缓解链接信息被风控导致无法发送的情况, 但可能影响客户端着色(不影响内容)|
|
||||
| use_sso_address | bool | 是否使用服务器下发的地址 |
|
||||
| heartbeat_interval | int64 | 心跳间隔时间,单位秒。小于0则关闭心跳,等于0使用默认值(5秒) |
|
||||
| http_config | object | HTTP API配置 |
|
||||
| ws_config | object | Websocket API 配置 |
|
||||
| ws_reverse_servers | object[] | 反向 Websocket API 配置 |
|
||||
| log_level | string | 指定日志收集级别,将收集的日志单独存放到固定文件中,便于查看日志线索 当前支持 warn,error |
|
||||
|
||||
> 注: 开启密码加密后程序将在每次启动时要求输入解密密钥, 密钥错误会导致登录时提示密码错误.
|
||||
> 解密后密码将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取.
|
||||
> 解密后密码的哈希将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取.
|
||||
> 解密密钥在使用完成后并不会留存在内存中, 所以可用相对简单的字符串作为密钥
|
||||
|
||||
> 注2: 分片发送为原酷Q发送长消息的老方案, 发送速度更优/兼容性更好,但在有发言频率限制的群里,可能无法发送。关闭后将优先使用新方案, 能发送更长的消息, 但发送速度更慢,在部分老客户端将无法解析.
|
||||
|
320
global/config.go
320
global/config.go
@ -1,327 +1,11 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/hjson/hjson-go"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
|
||||
var currentPath = getCurrentPath()
|
||||
var DefaultConfFile = path.Join(currentPath, "config.hjson")
|
||||
|
||||
// DefaultConfigWithComments 为go-cqhttp的默认配置文件
|
||||
var DefaultConfigWithComments = `
|
||||
/*
|
||||
go-cqhttp 默认配置文件
|
||||
*/
|
||||
|
||||
{
|
||||
// QQ号
|
||||
uin: 0
|
||||
// QQ密码
|
||||
password: ""
|
||||
// 是否启用密码加密
|
||||
encrypt_password: false
|
||||
// 加密后的密码, 如未启用密码加密将为空, 请勿随意修改.
|
||||
password_encrypted: ""
|
||||
// 是否启用内置数据库
|
||||
// 启用将会增加10-20MB的内存占用和一定的磁盘空间
|
||||
// 关闭将无法使用 撤回 回复 get_msg 等上下文相关功能
|
||||
enable_db: true
|
||||
// 访问密钥, 强烈推荐在公网的服务器设置
|
||||
access_token: ""
|
||||
// 重连设置
|
||||
relogin: {
|
||||
// 是否启用自动重连
|
||||
// 如不启用掉线后将不会自动重连
|
||||
enabled: true
|
||||
// 重连延迟, 单位秒
|
||||
relogin_delay: 3
|
||||
// 最大重连次数, 0为无限制
|
||||
max_relogin_times: 0
|
||||
}
|
||||
// API限速设置
|
||||
// 该设置为全局生效
|
||||
// 原 cqhttp 虽然启用了 rate_limit 后缀, 但是基本没插件适配
|
||||
// 目前该限速设置为令牌桶算法, 请参考:
|
||||
// https://baike.baidu.com/item/%E4%BB%A4%E7%89%8C%E6%A1%B6%E7%AE%97%E6%B3%95/6597000?fr=aladdin
|
||||
_rate_limit: {
|
||||
// 是否启用限速
|
||||
enabled: false
|
||||
// 令牌回复频率, 单位秒
|
||||
frequency: 1
|
||||
// 令牌桶大小
|
||||
bucket_size: 1
|
||||
}
|
||||
// 是否忽略无效的CQ码
|
||||
// 如果为假将原样发送
|
||||
ignore_invalid_cqcode: false
|
||||
// 是否强制分片发送消息
|
||||
// 分片发送将会带来更快的速度
|
||||
// 但是兼容性会有些问题
|
||||
force_fragmented: false
|
||||
// 心跳频率, 单位秒
|
||||
// -1 为关闭心跳
|
||||
heartbeat_interval: 0
|
||||
// HTTP设置
|
||||
http_config: {
|
||||
// 是否启用正向HTTP服务器
|
||||
enabled: true
|
||||
// 服务端监听地址
|
||||
host: 0.0.0.0
|
||||
// 服务端监听端口
|
||||
port: 5700
|
||||
// 反向HTTP超时时间, 单位秒
|
||||
// 最小值为5,小于5将会忽略本项设置
|
||||
timeout: 0
|
||||
// 反向HTTP POST地址列表
|
||||
// 格式:
|
||||
// {
|
||||
// 地址: secret
|
||||
// }
|
||||
post_urls: {}
|
||||
}
|
||||
// 正向WS设置
|
||||
ws_config: {
|
||||
// 是否启用正向WS服务器
|
||||
enabled: true
|
||||
// 正向WS服务器监听地址
|
||||
host: 0.0.0.0
|
||||
// 正向WS服务器监听端口
|
||||
port: 6700
|
||||
}
|
||||
// 反向WS设置
|
||||
ws_reverse_servers: [
|
||||
// 可以添加多个反向WS推送
|
||||
{
|
||||
// 是否启用该推送
|
||||
enabled: false
|
||||
// 反向WS Universal 地址
|
||||
// 注意 设置了此项地址后下面两项将会被忽略
|
||||
// 留空请使用 ""
|
||||
reverse_url: ws://you_websocket_universal.server
|
||||
// 反向WS API 地址
|
||||
reverse_api_url: ws://you_websocket_api.server
|
||||
// 反向WS Event 地址
|
||||
reverse_event_url: ws://you_websocket_event.server
|
||||
// 重连间隔 单位毫秒
|
||||
reverse_reconnect_interval: 3000
|
||||
}
|
||||
]
|
||||
// 上报数据类型
|
||||
// 可选: string array
|
||||
post_message_format: string
|
||||
// 是否使用服务器下发的新地址进行重连
|
||||
// 注意, 此设置可能导致在海外服务器上连接情况更差
|
||||
use_sso_address: false
|
||||
// 是否启用 DEBUG
|
||||
debug: false
|
||||
// 日志等级 trace,debug,info,warn,error
|
||||
log_level: "info"
|
||||
// WebUi 设置
|
||||
web_ui: {
|
||||
// 是否启用 WebUi
|
||||
enabled: true
|
||||
// 监听地址
|
||||
host: 127.0.0.1
|
||||
// 监听端口
|
||||
web_ui_port: 9999
|
||||
// 是否接收来自web的输入
|
||||
web_input: false
|
||||
}
|
||||
}
|
||||
`
|
||||
// AccountToken 存储AccountToken供登录使用
|
||||
var AccountToken []byte
|
||||
|
||||
// PasswordHash 存储QQ密码哈希供登录使用
|
||||
var PasswordHash [16]byte
|
||||
|
||||
// JSONConfig Config对应的结构体
|
||||
type JSONConfig struct {
|
||||
Uin int64 `json:"uin"`
|
||||
Password string `json:"password"`
|
||||
EncryptPassword bool `json:"encrypt_password"`
|
||||
PasswordEncrypted string `json:"password_encrypted"`
|
||||
EnableDB bool `json:"enable_db"`
|
||||
EnableSelfMessage bool `json:"enable_self_message"`
|
||||
AccessToken string `json:"access_token"`
|
||||
ReLogin struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReLoginDelay int `json:"relogin_delay"`
|
||||
MaxReloginTimes uint `json:"max_relogin_times"`
|
||||
} `json:"relogin"`
|
||||
RateLimit struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Frequency float64 `json:"frequency"`
|
||||
BucketSize int `json:"bucket_size"`
|
||||
} `json:"_rate_limit"`
|
||||
IgnoreInvalidCQCode bool `json:"ignore_invalid_cqcode"`
|
||||
ForceFragmented bool `json:"force_fragmented"`
|
||||
FixURL bool `json:"fix_url"`
|
||||
ProxyRewrite string `json:"proxy_rewrite"`
|
||||
HeartbeatInterval time.Duration `json:"heartbeat_interval"`
|
||||
HTTPConfig *GoCQHTTPConfig `json:"http_config"`
|
||||
WSConfig *GoCQWebSocketConfig `json:"ws_config"`
|
||||
ReverseServers []*GoCQReverseWebSocketConfig `json:"ws_reverse_servers"`
|
||||
PostMessageFormat string `json:"post_message_format"`
|
||||
UseSSOAddress bool `json:"use_sso_address"`
|
||||
Debug bool `json:"debug"`
|
||||
LogLevel string `json:"log_level"`
|
||||
// WebUI *GoCQWebUI `json:"web_ui"`
|
||||
}
|
||||
|
||||
// CQHTTPAPIConfig HTTPAPI对应的Config结构体
|
||||
type CQHTTPAPIConfig struct {
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
UseHTTP bool `json:"use_http"`
|
||||
WSHost string `json:"ws_host"`
|
||||
WSPort uint16 `json:"ws_port"`
|
||||
UseWS bool `json:"use_ws"`
|
||||
WSReverseURL string `json:"ws_reverse_url"`
|
||||
WSReverseAPIURL string `json:"ws_reverse_api_url"`
|
||||
WSReverseEventURL string `json:"ws_reverse_event_url"`
|
||||
WSReverseReconnectInterval uint16 `json:"ws_reverse_reconnect_interval"`
|
||||
WSReverseReconnectOnCode1000 bool `json:"ws_reverse_reconnect_on_code_1000"`
|
||||
UseWsReverse bool `json:"use_ws_reverse"`
|
||||
PostURL string `json:"post_url"`
|
||||
AccessToken string `json:"access_token"`
|
||||
Secret string `json:"secret"`
|
||||
PostMessageFormat string `json:"post_message_format"`
|
||||
}
|
||||
|
||||
// GoCQHTTPConfig 正向HTTP对应config结构体
|
||||
type GoCQHTTPConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
Timeout int32 `json:"timeout"`
|
||||
PostUrls map[string]string `json:"post_urls"`
|
||||
}
|
||||
|
||||
// GoCQWebSocketConfig 正向WebSocket对应Config结构体
|
||||
type GoCQWebSocketConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
}
|
||||
|
||||
// GoCQReverseWebSocketConfig 反向WebSocket对应Config结构体
|
||||
type GoCQReverseWebSocketConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReverseURL string `json:"reverse_url"`
|
||||
ReverseAPIURL string `json:"reverse_api_url"`
|
||||
ReverseEventURL string `json:"reverse_event_url"`
|
||||
ReverseReconnectInterval uint16 `json:"reverse_reconnect_interval"`
|
||||
}
|
||||
|
||||
/*
|
||||
// GoCQWebUI WebUI对应Config结构体
|
||||
type GoCQWebUI struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Host string `json:"host"`
|
||||
WebUIPort uint64 `json:"web_ui_port"`
|
||||
WebInput bool `json:"web_input"`
|
||||
}
|
||||
*/
|
||||
|
||||
// DefaultConfig 返回一份默认配置对应结构体
|
||||
func DefaultConfig() *JSONConfig {
|
||||
return &JSONConfig{
|
||||
EnableDB: true,
|
||||
ReLogin: struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReLoginDelay int `json:"relogin_delay"`
|
||||
MaxReloginTimes uint `json:"max_relogin_times"`
|
||||
}{
|
||||
Enabled: true,
|
||||
ReLoginDelay: 3,
|
||||
MaxReloginTimes: 0,
|
||||
},
|
||||
RateLimit: struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Frequency float64 `json:"frequency"`
|
||||
BucketSize int `json:"bucket_size"`
|
||||
}{
|
||||
Enabled: false,
|
||||
Frequency: 1,
|
||||
BucketSize: 1,
|
||||
},
|
||||
PostMessageFormat: "string",
|
||||
ForceFragmented: false,
|
||||
HTTPConfig: &GoCQHTTPConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 5700,
|
||||
PostUrls: map[string]string{},
|
||||
},
|
||||
WSConfig: &GoCQWebSocketConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 6700,
|
||||
},
|
||||
ReverseServers: []*GoCQReverseWebSocketConfig{
|
||||
{
|
||||
Enabled: false,
|
||||
ReverseURL: "ws://you_websocket_universal.server",
|
||||
ReverseAPIURL: "ws://you_websocket_api.server",
|
||||
ReverseEventURL: "ws://you_websocket_event.server",
|
||||
ReverseReconnectInterval: 3000,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// LoadConfig 加载配置文件
|
||||
func LoadConfig(p string) *JSONConfig {
|
||||
if !PathExists(p) {
|
||||
log.Warnf("尝试加载配置文件 %v 失败: 文件不存在", p)
|
||||
return nil
|
||||
}
|
||||
var dat map[string]interface{}
|
||||
var c = JSONConfig{}
|
||||
err := hjson.Unmarshal([]byte(ReadAllText(p)), &dat)
|
||||
if err == nil {
|
||||
b, _ := json.Marshal(dat)
|
||||
err = json.Unmarshal(b, &c)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warnf("尝试加载配置文件 %v 时出现错误: %v", p, err)
|
||||
log.Infoln("原文件已备份")
|
||||
_ = os.Rename(p, p+".backup"+strconv.FormatInt(time.Now().Unix(), 10))
|
||||
return nil
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
// Save 写入配置文件至path
|
||||
func (c *JSONConfig) Save(path string) error {
|
||||
data, err := hjson.MarshalWithOptions(c, hjson.EncoderOptions{
|
||||
Eol: "\n",
|
||||
BracesSameLine: true,
|
||||
IndentBy: " ",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return WriteAllText(path, string(data))
|
||||
}
|
||||
|
||||
// getCurrentPath 获取当前文件的路径,直接返回string
|
||||
func getCurrentPath() string {
|
||||
cwd, e := os.Getwd()
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return cwd
|
||||
}
|
||||
|
||||
/*
|
||||
// GetCurrentPath 预留,获取当前目录地址
|
||||
func GetCurrentPath() (string, error) {
|
||||
|
133
global/config/config.go
Normal file
133
global/config/config.go
Normal file
@ -0,0 +1,133 @@
|
||||
// Package config 包含go-cqhttp操作配置文件的相关函数
|
||||
package config
|
||||
|
||||
import (
|
||||
_ "embed" // embed the default config file
|
||||
"os"
|
||||
"path"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// DefaultConfig 默认配置文件
|
||||
//go:embed default_config.yml
|
||||
var DefaultConfig string
|
||||
|
||||
var currentPath = getCurrentPath()
|
||||
|
||||
// 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"`
|
||||
ReLogin struct {
|
||||
Disabled bool `yaml:"disabled"`
|
||||
Delay int `yaml:"delay"`
|
||||
MaxTimes uint `yaml:"max-times"`
|
||||
Interval int `yaml:"interval"`
|
||||
}
|
||||
UseSSOAddress bool `yaml:"use-sso-address"`
|
||||
} `yaml:"account"`
|
||||
|
||||
Heartbeat struct {
|
||||
Disabled bool `yaml:"disabled"`
|
||||
Interval int `yaml:"interval"`
|
||||
} `yaml:"heartbeat"`
|
||||
|
||||
Message struct {
|
||||
PostFormat string `yaml:"post-format"`
|
||||
IgnoreInvalidCQCode bool `yaml:"ignore-invalid-cqcode"`
|
||||
ForceFragment bool `yaml:"force-fragment"`
|
||||
FixURL bool `yaml:"fix-url"`
|
||||
ProxyRewrite string `yaml:"proxy-rewrite"`
|
||||
ReportSelfMessage bool `yaml:"report-self-message"`
|
||||
RemoveReplyAt bool `yaml:"remove-reply-at"`
|
||||
ExtraReplyData bool `yaml:"extra-reply-data"`
|
||||
} `yaml:"message"`
|
||||
|
||||
Output struct {
|
||||
LogLevel string `yaml:"log-level"`
|
||||
Debug bool `yaml:"debug"`
|
||||
} `yaml:"output"`
|
||||
|
||||
Servers []map[string]yaml.Node `yaml:"servers"`
|
||||
Database map[string]yaml.Node `yaml:"database"`
|
||||
}
|
||||
|
||||
// MiddleWares 通信中间件
|
||||
type MiddleWares struct {
|
||||
AccessToken string `yaml:"access-token"`
|
||||
Filter string `yaml:"filter"`
|
||||
RateLimit struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
Frequency float64 `yaml:"frequency"`
|
||||
Bucket int `yaml:"bucket"`
|
||||
} `yaml:"rate-limit"`
|
||||
}
|
||||
|
||||
// HTTPServer HTTP通信相关配置
|
||||
type HTTPServer struct {
|
||||
Disabled bool `yaml:"disabled"`
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
Timeout int32 `yaml:"timeout"`
|
||||
Post []struct {
|
||||
URL string `yaml:"url"`
|
||||
Secret string `yaml:"secret"`
|
||||
}
|
||||
|
||||
MiddleWares `yaml:"middlewares"`
|
||||
}
|
||||
|
||||
// WebsocketServer 正向WS相关配置
|
||||
type WebsocketServer struct {
|
||||
Disabled bool `yaml:"disabled"`
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
|
||||
MiddleWares `yaml:"middlewares"`
|
||||
}
|
||||
|
||||
// WebsocketReverse 反向WS相关配置
|
||||
type WebsocketReverse struct {
|
||||
Disabled bool `yaml:"disabled"`
|
||||
Universal string `yaml:"universal"`
|
||||
API string `yaml:"api"`
|
||||
Event string `yaml:"event"`
|
||||
ReconnectInterval int `yaml:"reconnect-interval"`
|
||||
|
||||
MiddleWares `yaml:"middlewares"`
|
||||
}
|
||||
|
||||
// LevelDBConfig leveldb 相关配置
|
||||
type LevelDBConfig struct {
|
||||
Enable bool `yaml:"enable"`
|
||||
}
|
||||
|
||||
// Get 从默认配置文件路径中获取
|
||||
func Get() *Config {
|
||||
file, err := os.Open(DefaultConfigFile)
|
||||
if err != nil {
|
||||
log.Error("获取配置文件失败: ", err)
|
||||
return nil
|
||||
}
|
||||
config := &Config{}
|
||||
if yaml.NewDecoder(file).Decode(config) != nil {
|
||||
log.Fatal("配置文件不合法!", err)
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
// getCurrentPath 获取当前文件的路径,直接返回string
|
||||
func getCurrentPath() string {
|
||||
cwd, e := os.Getwd()
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return cwd
|
||||
}
|
123
global/config/default_config.yml
Normal file
123
global/config/default_config.yml
Normal file
@ -0,0 +1,123 @@
|
||||
# go-cqhttp 默认配置文件
|
||||
|
||||
account: # 账号相关
|
||||
uin: 1233456 # QQ账号
|
||||
password: '' # 密码为空时使用扫码登录
|
||||
encrypt: false # 是否开启密码加密
|
||||
relogin: # 重连设置
|
||||
disabled: false
|
||||
delay: 3 # 重连延迟, 单位秒
|
||||
interval: 0 # 重连间隔
|
||||
max-times: 0 # 最大重连次数, 0为无限制
|
||||
|
||||
# 是否使用服务器下发的新地址进行重连
|
||||
# 注意, 此设置可能导致在海外服务器上连接情况更差
|
||||
use-sso-address: true
|
||||
|
||||
heartbeat:
|
||||
disabled: false # 是否开启心跳事件上报
|
||||
# 心跳频率, 单位秒
|
||||
# -1 为关闭心跳
|
||||
interval: 5
|
||||
|
||||
message:
|
||||
# 上报数据类型
|
||||
# 可选: string,array
|
||||
post-format: string
|
||||
# 是否忽略无效的CQ码, 如果为假将原样发送
|
||||
ignore-invalid-cqcode: false
|
||||
# 是否强制分片发送消息
|
||||
# 分片发送将会带来更快的速度
|
||||
# 但是兼容性会有些问题
|
||||
force-fragment: false
|
||||
# 是否将url分片发送
|
||||
fix-url: false
|
||||
# 下载图片等请求网络代理
|
||||
proxy-rewrite: ''
|
||||
# 是否上报自身消息
|
||||
report-self-message: false
|
||||
# 移除服务端的Reply附带的At
|
||||
remove-reply-at: false
|
||||
# 为Reply附加更多信息
|
||||
extra-reply-data: false
|
||||
|
||||
output:
|
||||
# 日志等级 trace,debug,info,warn,error日志等级 trace,debug,info,warn,error
|
||||
log-level: warn
|
||||
# 是否启用 DEBUG
|
||||
debug: false # 开启调试模式
|
||||
|
||||
# 默认中间件锚点
|
||||
default-middlewares: &default
|
||||
# 访问密钥, 强烈推荐在公网的服务器设置
|
||||
access-token: ''
|
||||
# 事件过滤器文件目录
|
||||
filter: ''
|
||||
# API限速设置
|
||||
# 该设置为全局生效
|
||||
# 原 cqhttp 虽然启用了 rate_limit 后缀, 但是基本没插件适配
|
||||
# 目前该限速设置为令牌桶算法, 请参考:
|
||||
# https://baike.baidu.com/item/%E4%BB%A4%E7%89%8C%E6%A1%B6%E7%AE%97%E6%B3%95/6597000?fr=aladdin
|
||||
rate-limit:
|
||||
enabled: false # 是否启用限速
|
||||
frequency: 1 # 令牌回复频率, 单位秒
|
||||
bucket: 1 # 令牌桶大小
|
||||
|
||||
servers:
|
||||
# HTTP 通信设置
|
||||
- http:
|
||||
# 是否关闭正向HTTP服务器
|
||||
disabled: false
|
||||
# 服务端监听地址
|
||||
host: 127.0.0.1
|
||||
# 服务端监听端口
|
||||
port: 5700
|
||||
# 反向HTTP超时时间, 单位秒
|
||||
# 最小值为5,小于5将会忽略本项设置
|
||||
timeout: 5
|
||||
middlewares:
|
||||
<<: *default # 引用默认中间件
|
||||
# 反向HTTP POST地址列表
|
||||
post:
|
||||
#- url: '' # 地址
|
||||
# secret: '' # 密钥
|
||||
#- url: 127.0.0.1:5701 # 地址
|
||||
# secret: '' # 密钥
|
||||
|
||||
# 正向WS设置
|
||||
- ws:
|
||||
# 是否禁用正向WS服务器
|
||||
disabled: true
|
||||
# 正向WS服务器监听地址
|
||||
host: 127.0.0.1
|
||||
# 正向WS服务器监听端口
|
||||
port: 6700
|
||||
middlewares:
|
||||
<<: *default # 引用默认中间件
|
||||
|
||||
- ws-reverse:
|
||||
# 是否禁用当前反向WS服务
|
||||
disabled: true
|
||||
# 反向WS Universal 地址
|
||||
# 注意 设置了此项地址后下面两项将会被忽略
|
||||
universal: ws://your_websocket_universal.server
|
||||
# 反向WS API 地址
|
||||
api: ws://your_websocket_api.server
|
||||
# 反向WS Event 地址
|
||||
event: ws://your_websocket_event.server
|
||||
# 重连间隔 单位毫秒
|
||||
reconnect-interval: 3000
|
||||
middlewares:
|
||||
<<: *default # 引用默认中间件
|
||||
|
||||
# 可添加更多
|
||||
#- ws-reverse:
|
||||
#- ws:
|
||||
#- http:
|
||||
|
||||
database: # 数据库相关设置
|
||||
leveldb:
|
||||
# 是否启用内置leveldb数据库
|
||||
# 启用将会增加10-20MB的内存占用和一定的磁盘空间
|
||||
# 关闭将无法使用 撤回 回复 get_msg 等上下文相关功能
|
||||
enable: true
|
@ -1,51 +1,15 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// MSG 消息Map
|
||||
type MSG map[string]interface{}
|
||||
|
||||
// Get 尝试从消息Map中取出key为s的值,若不存在则返回MSG{}
|
||||
//
|
||||
// 若所给key对应的值的类型是global.MSG,则返回此值
|
||||
//
|
||||
// 若所给key对应值的类型不是global.MSG,则返回MSG{"__str__": Val}
|
||||
func (m MSG) Get(s string) MSG {
|
||||
if v, ok := m[s]; ok {
|
||||
if msg, ok := v.(MSG); ok {
|
||||
return msg
|
||||
}
|
||||
return MSG{"__str__": v} // 用这个名字应该没问题吧
|
||||
}
|
||||
return nil // 不存在为空
|
||||
}
|
||||
|
||||
// String 将消息Map转化为String。若Map存在key "__str__",则返回此key对应的值,否则将输出整张消息Map对应的JSON字符串
|
||||
func (m MSG) String() string {
|
||||
if m == nil {
|
||||
return "" // 空 JSON
|
||||
}
|
||||
if str, ok := m["__str__"]; ok {
|
||||
if str == nil {
|
||||
return "" // 空 JSON
|
||||
}
|
||||
return fmt.Sprint(str)
|
||||
}
|
||||
str, _ := json.MarshalToString(m)
|
||||
return str
|
||||
}
|
||||
|
||||
// Filter 定义了一个消息上报过滤接口
|
||||
type Filter interface {
|
||||
Eval(payload MSG) bool
|
||||
Eval(payload gjson.Result) bool
|
||||
}
|
||||
|
||||
type operationNode struct {
|
||||
@ -68,7 +32,7 @@ func notOperatorConstruct(argument gjson.Result) *NotOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行Not过滤
|
||||
func (op *NotOperator) Eval(payload MSG) bool {
|
||||
func (op *NotOperator) Eval(payload gjson.Result) bool {
|
||||
return !op.operand.Eval(payload)
|
||||
}
|
||||
|
||||
@ -110,7 +74,7 @@ func andOperatorConstruct(argument gjson.Result) *AndOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行And过滤
|
||||
func (op *AndOperator) Eval(payload MSG) bool {
|
||||
func (op *AndOperator) Eval(payload gjson.Result) bool {
|
||||
res := true
|
||||
for _, operand := range op.operands {
|
||||
if len(operand.key) == 0 {
|
||||
@ -147,7 +111,7 @@ func orOperatorConstruct(argument gjson.Result) *OrOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行Or过滤
|
||||
func (op *OrOperator) Eval(payload MSG) bool {
|
||||
func (op *OrOperator) Eval(payload gjson.Result) bool {
|
||||
res := false
|
||||
for _, operand := range op.operands {
|
||||
res = res || operand.Eval(payload)
|
||||
@ -170,7 +134,7 @@ func equalOperatorConstruct(argument gjson.Result) *EqualOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行Equal过滤
|
||||
func (op *EqualOperator) Eval(payload MSG) bool {
|
||||
func (op *EqualOperator) Eval(payload gjson.Result) bool {
|
||||
return payload.String() == op.operand
|
||||
}
|
||||
|
||||
@ -186,7 +150,7 @@ func notEqualOperatorConstruct(argument gjson.Result) *NotEqualOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行NotEqual过滤
|
||||
func (op *NotEqualOperator) Eval(payload MSG) bool {
|
||||
func (op *NotEqualOperator) Eval(payload gjson.Result) bool {
|
||||
return !(payload.String() == op.operand)
|
||||
}
|
||||
|
||||
@ -214,7 +178,7 @@ func inOperatorConstruct(argument gjson.Result) *InOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行In过滤
|
||||
func (op *InOperator) Eval(payload MSG) bool {
|
||||
func (op *InOperator) Eval(payload gjson.Result) bool {
|
||||
payloadStr := payload.String()
|
||||
if op.operandArray != nil {
|
||||
for _, value := range op.operandArray {
|
||||
@ -242,7 +206,7 @@ func containsOperatorConstruct(argument gjson.Result) *ContainsOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行Contains过滤
|
||||
func (op *ContainsOperator) Eval(payload MSG) bool {
|
||||
func (op *ContainsOperator) Eval(payload gjson.Result) bool {
|
||||
return strings.Contains(payload.String(), op.operand)
|
||||
}
|
||||
|
||||
@ -261,7 +225,7 @@ func regexOperatorConstruct(argument gjson.Result) *RegexOperator {
|
||||
}
|
||||
|
||||
// Eval 对payload执行RegexO过滤
|
||||
func (op *RegexOperator) Eval(payload MSG) bool {
|
||||
func (op *RegexOperator) Eval(payload gjson.Result) bool {
|
||||
matched := op.regex.MatchString(payload.String())
|
||||
return matched
|
||||
}
|
||||
@ -289,24 +253,3 @@ func Generate(opName string, argument gjson.Result) Filter {
|
||||
panic("the operator " + opName + " is not supported")
|
||||
}
|
||||
}
|
||||
|
||||
// EventFilter 初始化一个nil过滤器
|
||||
var EventFilter Filter
|
||||
|
||||
// BootFilter 启动事件过滤器
|
||||
func BootFilter() {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
log.Warnf("事件过滤器启动失败: %v", e)
|
||||
EventFilter = nil
|
||||
} else {
|
||||
log.Info("事件过滤器启动成功.")
|
||||
}
|
||||
}()
|
||||
f, err := ioutil.ReadFile("filter.json")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
EventFilter = Generate("and", gjson.ParseBytes(f))
|
||||
}
|
||||
}
|
||||
|
105
global/fs.go
105
global/fs.go
@ -1,28 +1,20 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/bzip2"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kardianos/osext"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@ -72,8 +64,11 @@ func WriteAllText(path, text string) error {
|
||||
}
|
||||
|
||||
// Check 检测err是否为nil
|
||||
func Check(err error) {
|
||||
func Check(err error, deleteSession bool) {
|
||||
if err != nil {
|
||||
if deleteSession && PathExists("session.token") {
|
||||
_ = os.Remove("session.token")
|
||||
}
|
||||
log.Fatalf("遇到错误: %v", err)
|
||||
}
|
||||
}
|
||||
@ -160,95 +155,3 @@ func ReadAddrFile(path string) []*net.TCPAddr {
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// WriteCounter 写入量计算实例
|
||||
type WriteCounter struct {
|
||||
Total uint64
|
||||
}
|
||||
|
||||
// Write 方法将写入的byte长度追加至写入的总长度Total中
|
||||
func (wc *WriteCounter) Write(p []byte) (int, error) {
|
||||
n := len(p)
|
||||
wc.Total += uint64(n)
|
||||
wc.PrintProgress()
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// PrintProgress 方法将打印当前的总写入量
|
||||
func (wc *WriteCounter) PrintProgress() {
|
||||
fmt.Printf("\r%s", strings.Repeat(" ", 35))
|
||||
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
|
||||
}
|
||||
|
||||
// UpdateFromStream copy form getlantern/go-update
|
||||
func UpdateFromStream(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
|
||||
var fileHeader []byte
|
||||
bufBytes := bufio.NewReader(updateWith)
|
||||
fileHeader, err = bufBytes.Peek(2)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// The content is always bzip2 compressed except when running test, in
|
||||
// which case is not prefixed with the magic byte sequence for sure.
|
||||
if bytes.Equal([]byte{0x42, 0x5a}, fileHeader) {
|
||||
// Identifying bzip2 files.
|
||||
updateWith = bzip2.NewReader(bufBytes)
|
||||
} else {
|
||||
updateWith = io.Reader(bufBytes)
|
||||
}
|
||||
newBytes, err = ioutil.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, 0755)
|
||||
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
|
||||
}
|
||||
|
@ -54,7 +54,6 @@ func (hook *LocalHook) pathWrite(entry *logrus.Entry) error {
|
||||
defer fd.Close()
|
||||
|
||||
log, err := hook.formatter.Format(entry)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -142,24 +141,36 @@ func NewLocalHook(args interface{}, formatter logrus.Formatter, levels ...logrus
|
||||
func GetLogLevel(level string) []logrus.Level {
|
||||
switch level {
|
||||
case "trace":
|
||||
return []logrus.Level{logrus.TraceLevel, logrus.DebugLevel,
|
||||
return []logrus.Level{
|
||||
logrus.TraceLevel, logrus.DebugLevel,
|
||||
logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel}
|
||||
logrus.FatalLevel, logrus.PanicLevel,
|
||||
}
|
||||
case "debug":
|
||||
return []logrus.Level{logrus.DebugLevel, logrus.InfoLevel,
|
||||
return []logrus.Level{
|
||||
logrus.DebugLevel, logrus.InfoLevel,
|
||||
logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel}
|
||||
logrus.FatalLevel, logrus.PanicLevel,
|
||||
}
|
||||
case "info":
|
||||
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel,
|
||||
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}
|
||||
return []logrus.Level{
|
||||
logrus.InfoLevel, logrus.WarnLevel,
|
||||
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel,
|
||||
}
|
||||
case "warn":
|
||||
return []logrus.Level{logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel}
|
||||
return []logrus.Level{
|
||||
logrus.WarnLevel, logrus.ErrorLevel,
|
||||
logrus.FatalLevel, logrus.PanicLevel,
|
||||
}
|
||||
case "error":
|
||||
return []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel,
|
||||
logrus.PanicLevel}
|
||||
return []logrus.Level{
|
||||
logrus.ErrorLevel, logrus.FatalLevel,
|
||||
logrus.PanicLevel,
|
||||
}
|
||||
default:
|
||||
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel,
|
||||
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}
|
||||
return []logrus.Level{
|
||||
logrus.InfoLevel, logrus.WarnLevel,
|
||||
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -217,7 +217,7 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int,
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("response status unsuccessful: " + strconv.FormatInt(int64(resp.StatusCode), 10))
|
||||
}
|
||||
var buffer = make([]byte, 1024)
|
||||
buffer := make([]byte, 1024)
|
||||
i, err := resp.Body.Read(buffer)
|
||||
for {
|
||||
if err != nil && err != io.EOF {
|
||||
|
@ -1,23 +0,0 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
var limiter *rate.Limiter
|
||||
var limitEnable = false
|
||||
|
||||
// RateLimit 执行API调用速率限制
|
||||
func RateLimit(ctx context.Context) {
|
||||
if limitEnable {
|
||||
_ = limiter.Wait(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// InitLimiter 初始化速率限制器
|
||||
func InitLimiter(frequency float64, bucketSize int) {
|
||||
limitEnable = true
|
||||
limiter = rate.NewLimiter(rate.Limit(frequency), bucketSize)
|
||||
}
|
2
global/terminal/doc.go
Normal file
2
global/terminal/doc.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package terminal 包含用于检测在windows下是否通过双击运行go-cqhttp的函数
|
||||
package terminal
|
@ -2,6 +2,7 @@
|
||||
|
||||
package terminal
|
||||
|
||||
// RunningByDoubleClick 检查是否通过双击直接运行,非Windows系统永远返回false
|
||||
func RunningByDoubleClick() bool {
|
||||
return false
|
||||
}
|
||||
|
97
global/update/update.go
Normal file
97
global/update/update.go
Normal file
@ -0,0 +1,97 @@
|
||||
// Package update 包含go-cqhttp自我更新相关函数
|
||||
package update
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/kardianos/osext"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// WriteCounter 写入量计算实例
|
||||
type WriteCounter struct {
|
||||
Total uint64
|
||||
}
|
||||
|
||||
// Write 方法将写入的byte长度追加至写入的总长度Total中
|
||||
func (wc *WriteCounter) Write(p []byte) (int, error) {
|
||||
n := len(p)
|
||||
wc.Total += uint64(n)
|
||||
wc.PrintProgress()
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// PrintProgress 方法将打印当前的总写入量
|
||||
func (wc *WriteCounter) PrintProgress() {
|
||||
fmt.Printf("\r%s", strings.Repeat(" ", 35))
|
||||
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
|
||||
}
|
||||
|
||||
// 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 = ioutil.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, 0755)
|
||||
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
|
||||
}
|
51
global/update/update_others.go
Normal file
51
global/update/update_others.go
Normal file
@ -0,0 +1,51 @@
|
||||
// +build !windows
|
||||
|
||||
package update
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Update go-cqhttp自我更新
|
||||
func Update(url string) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Error("更新失败: ", err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
wc := WriteCounter{}
|
||||
data, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
|
||||
if err != nil {
|
||||
log.Error("更新失败: ", err)
|
||||
return
|
||||
}
|
||||
gr, err := gzip.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
log.Error("更新失败: ", err)
|
||||
return
|
||||
}
|
||||
tr := tar.NewReader(gr)
|
||||
for {
|
||||
header, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if header.Name == "go-cqhttp" {
|
||||
err, _ := FromStream(tr)
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
log.Error("更新失败!", err)
|
||||
return
|
||||
}
|
||||
log.Info("更新完成!")
|
||||
}
|
||||
}
|
||||
}
|
36
global/update/update_windows.go
Normal file
36
global/update/update_windows.go
Normal file
@ -0,0 +1,36 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Update go-cqhttp自我更新
|
||||
func Update(url string) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Error("更新失败: ", err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
wc := WriteCounter{}
|
||||
rsp, _ := io.ReadAll(io.TeeReader(resp.Body, &wc))
|
||||
reader, _ := zip.NewReader(bytes.NewReader(rsp), resp.ContentLength)
|
||||
file, err := reader.Open("go-cqhttp.exe")
|
||||
if err != nil {
|
||||
log.Error("更新失败!", err)
|
||||
return
|
||||
}
|
||||
err, _ = FromStream(file)
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
log.Error("更新失败!", err)
|
||||
return
|
||||
}
|
||||
log.Info("更新完成!")
|
||||
}
|
12
go.mod
12
go.mod
@ -4,12 +4,11 @@ go 1.16
|
||||
|
||||
require (
|
||||
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210323143736-d233c90d5083
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210406093140-5ec6c651b797
|
||||
github.com/dustin/go-humanize v1.0.0
|
||||
github.com/gin-gonic/gin v1.6.3
|
||||
github.com/gorilla/websocket v1.4.2
|
||||
github.com/guonaihong/gout v0.1.5
|
||||
github.com/hjson/hjson-go v3.1.0+incompatible
|
||||
github.com/guonaihong/gout v0.1.6
|
||||
github.com/jonboulle/clockwork v0.2.2 // indirect
|
||||
github.com/json-iterator/go v1.1.10
|
||||
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
|
||||
@ -21,11 +20,12 @@ require (
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
|
||||
github.com/syndtr/goleveldb v1.0.0
|
||||
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
|
||||
github.com/tidwall/gjson v1.6.8
|
||||
github.com/tidwall/gjson v1.7.3
|
||||
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2
|
||||
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60
|
||||
github.com/willf/bitset v1.1.11 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b
|
||||
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2
|
||||
golang.org/x/term v0.0.0-20210317153231-de623e64d2a6
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c
|
||||
)
|
||||
|
26
go.sum
26
go.sum
@ -2,8 +2,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT
|
||||
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f h1:2dk3eOnYllh+wUOuDhOoC2vUVoJF/5z478ryJ+wzEII=
|
||||
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f/go.mod h1:4a58ifQTEe2uwwsaqbh3i2un5/CBPg+At/qHpt18Tmk=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210323143736-d233c90d5083 h1:ELaNvv80OTwHTYhKwoQpgV4dneKPM1qE5Geu3A1kM/8=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210323143736-d233c90d5083/go.mod h1:NjiWhlvGxwv1ftOWIoiFa/OzklnAYI4YqNexFOKSZKw=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210406093140-5ec6c651b797 h1:u6jJ6bbYghAEM1DVe0SQKoIVva6od7fsdFRRC15DKMw=
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210406093140-5ec6c651b797/go.mod h1:NjiWhlvGxwv1ftOWIoiFa/OzklnAYI4YqNexFOKSZKw=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@ -54,10 +54,8 @@ github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/guonaihong/gout v0.1.5 h1:1FeFFJWWdWYApBW9d6vzMDB4eR4Zr8T/gaVrjDVcl5U=
|
||||
github.com/guonaihong/gout v0.1.5/go.mod h1:0rFYAYyzbcxEg11eY2qUbffJs7hHRPeugAnlVYSp8Ic=
|
||||
github.com/hjson/hjson-go v3.1.0+incompatible h1:DY/9yE8ey8Zv22bY+mHV1uk2yRy0h8tKhZ77hEdi0Aw=
|
||||
github.com/hjson/hjson-go v3.1.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio=
|
||||
github.com/guonaihong/gout v0.1.6 h1:Txej4NYvVJLZkW0Xgw1HuWfSWow5BgLF6vqlM2kRdno=
|
||||
github.com/guonaihong/gout v0.1.6/go.mod h1:P6P8+0+toYgmhFqzLxVde+9vQbCDHrxn56V9TglC5io=
|
||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
|
||||
@ -116,12 +114,12 @@ github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFd
|
||||
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
|
||||
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 h1:J6v8awz+me+xeb/cUTotKgceAYouhIB3pjzgRd6IlGk=
|
||||
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816/go.mod h1:tzym/CEb5jnFI+Q0k4Qq3+LvRF4gO3E2pxS8fHP8jcA=
|
||||
github.com/tidwall/gjson v1.6.8 h1:CTmXMClGYPAmln7652e69B7OLXfTi5ABcPPwjIWUv7w=
|
||||
github.com/tidwall/gjson v1.6.8/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI=
|
||||
github.com/tidwall/gjson v1.7.3 h1:9dOulDrkCJf1mwljVMhXNQr9ZL2NvajRX7A1R8c6Qxw=
|
||||
github.com/tidwall/gjson v1.7.3/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
|
||||
github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
|
||||
github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
|
||||
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/tidwall/pretty v1.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8=
|
||||
github.com/tidwall/pretty v1.1.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 h1:BWVtt2VBY+lmVDu9MGKqLGKl04B+iRHcrW1Ptyi/8tg=
|
||||
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2/go.mod h1:lPnW9HVS0vJdeYyQtOvIvlXgZPNhUAhwz+z5r8AJk0Y=
|
||||
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||
@ -133,8 +131,8 @@ github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60/go.mod h1:ecFKZ
|
||||
github.com/willf/bitset v1.1.11 h1:N7Z7E9UvjW+sGsEl7k/SJrvY2reP1A07MrGuCjIOjRE=
|
||||
github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr3+MjI=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b h1:wSOdpTq0/eI46Ez/LkDwIsAKA71YP2SRKBODiRWM0as=
|
||||
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w=
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
@ -162,8 +160,8 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20201126233918-771906719818 h1:f1CIuDlJhwANEC2MM87MBEVMr3jl5bifgsfj90XAF9c=
|
||||
golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE=
|
||||
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210317153231-de623e64d2a6 h1:EC6+IGYTjPpRfv9a2b/6Puw0W+hLtAhkV1tPsXhutqs=
|
||||
golang.org/x/term v0.0.0-20210317153231-de623e64d2a6/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
|
||||
|
56
login.go
56
login.go
@ -25,6 +25,22 @@ var readLine = func() (str string) {
|
||||
return
|
||||
}
|
||||
|
||||
var readLineTimeout = func(t time.Duration, de string) (str string) {
|
||||
r := make(chan string)
|
||||
go func() {
|
||||
select {
|
||||
case r <- readLine():
|
||||
case <-time.After(t):
|
||||
}
|
||||
}()
|
||||
str = de
|
||||
select {
|
||||
case str = <-r:
|
||||
case <-time.After(t):
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var cli *client.QQClient
|
||||
|
||||
// ErrSMSRequestError SMS请求出错
|
||||
@ -48,6 +64,7 @@ func qrcodeLogin() error {
|
||||
return err
|
||||
}
|
||||
_ = ioutil.WriteFile("qrcode.png", rsp.ImageData, 0644)
|
||||
defer func() { _ = os.Remove("qrcode.png") }()
|
||||
log.Infof("请使用手机QQ扫描二维码 (qrcode.png) : ")
|
||||
time.Sleep(time.Second)
|
||||
qrcodeTerminal.New().Get(fi.Content).Print()
|
||||
@ -78,7 +95,7 @@ func qrcodeLogin() error {
|
||||
if s.State == client.QRCodeConfirmed {
|
||||
res, err := cli.QRCodeLogin(s.LoginInfo)
|
||||
if err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
return loginResponseProcessor(res)
|
||||
}
|
||||
@ -98,16 +115,23 @@ func loginResponseProcessor(res *client.LoginResponse) error {
|
||||
switch res.Error {
|
||||
case client.SliderNeededError:
|
||||
log.Warnf("登录需要滑条验证码. ")
|
||||
log.Warnf("请参考文档 -> https://github.com/Mrs4s/go-cqhttp/blob/master/docs/slider.md <- 抓包获取 Ticket")
|
||||
println()
|
||||
log.Warnf("请用浏览器打开 -> %v <- 并获取Ticket.", res.VerifyUrl)
|
||||
println()
|
||||
log.Warn("请输入Ticket: (Enter 提交)")
|
||||
text = readLine()
|
||||
res, err = cli.SubmitTicket(text)
|
||||
continue
|
||||
log.Warnf("请参考文档 -> https://github.com/Mrs4s/go-cqhttp/blob/master/docs/slider.md <- 进行处理")
|
||||
log.Warnf("1. 自行抓包并获取 Ticket 输入.")
|
||||
log.Warnf("2. 使用手机QQ扫描二维码登入. (推荐)")
|
||||
log.Warn("请输入(1 - 2) (将在10秒后自动选择2):")
|
||||
text = readLineTimeout(time.Second*10, "2")
|
||||
if strings.Contains(text, "1") {
|
||||
println()
|
||||
log.Warnf("请用浏览器打开 -> %v <- 并获取Ticket.", res.VerifyUrl)
|
||||
println()
|
||||
log.Warn("请输入Ticket: (Enter 提交)")
|
||||
text = readLine()
|
||||
res, err = cli.SubmitTicket(text)
|
||||
continue
|
||||
}
|
||||
return qrcodeLogin()
|
||||
case client.NeedCaptcha:
|
||||
log.Warnf("登录需要滑条验证码.")
|
||||
log.Warnf("登录需要验证码.")
|
||||
_ = ioutil.WriteFile("captcha.jpg", res.CaptchaImage, 0644)
|
||||
log.Warnf("请输入验证码 (captcha.jpg): (Enter 提交)")
|
||||
text = readLine()
|
||||
@ -129,8 +153,8 @@ func loginResponseProcessor(res *client.LoginResponse) error {
|
||||
log.Warnf("账号已开启设备锁,请选择验证方式:")
|
||||
log.Warnf("1. 向手机 %v 发送短信验证码", res.SMSPhone)
|
||||
log.Warnf("2. 使用手机QQ扫码验证.")
|
||||
log.Warn("请输入(1 - 2):")
|
||||
text = readLine()
|
||||
log.Warn("请输入(1 - 2) (将在10秒后自动选择2):")
|
||||
text = readLineTimeout(time.Second*10, "2")
|
||||
if strings.Contains(text, "1") {
|
||||
if !cli.RequestSMS() {
|
||||
log.Warnf("发送验证码失败,可能是请求过于频繁.")
|
||||
@ -144,8 +168,8 @@ func loginResponseProcessor(res *client.LoginResponse) error {
|
||||
fallthrough
|
||||
case client.UnsafeDeviceError:
|
||||
log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证后重启Bot.", res.VerifyUrl)
|
||||
log.Infof("按 Enter 继续....")
|
||||
readLine()
|
||||
log.Infof("按 Enter 或等待 5s 后继续....")
|
||||
readLineTimeout(time.Second*5, "")
|
||||
os.Exit(0)
|
||||
case client.OtherLoginError, client.UnknownLoginError, client.TooManySMSRequestError:
|
||||
msg := res.ErrorMessage
|
||||
@ -156,8 +180,8 @@ func loginResponseProcessor(res *client.LoginResponse) error {
|
||||
log.Fatalf("账号被冻结")
|
||||
}
|
||||
log.Warnf("登录失败: %v", msg)
|
||||
log.Infof("按 Enter 继续....")
|
||||
readLine()
|
||||
log.Infof("按 Enter 或等待 5s 后继续....")
|
||||
readLineTimeout(time.Second*5, "")
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
392
main.go
392
main.go
@ -5,18 +5,14 @@ import (
|
||||
"crypto/aes"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
@ -24,13 +20,13 @@ import (
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"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/client"
|
||||
"github.com/guonaihong/gout"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
log "github.com/sirupsen/logrus"
|
||||
easy "github.com/t-tomalak/logrus-easy-formatter"
|
||||
@ -39,23 +35,24 @@ import (
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var json = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
var conf *global.JSONConfig
|
||||
var isFastStart = false
|
||||
var c string
|
||||
var d bool
|
||||
var h bool
|
||||
var (
|
||||
conf *config.Config
|
||||
isFastStart = false
|
||||
c string
|
||||
d bool
|
||||
h bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
var debug bool
|
||||
flag.StringVar(&c, "c", global.DefaultConfFile, "configuration filename default is config.hjson")
|
||||
flag.StringVar(&c, "c", config.DefaultConfigFile, "configuration filename default is config.hjson")
|
||||
flag.BoolVar(&d, "d", false, "running as a daemon")
|
||||
flag.BoolVar(&debug, "D", false, "debug mode")
|
||||
flag.BoolVar(&h, "h", false, "this help")
|
||||
flag.Parse()
|
||||
|
||||
// 通过-c 参数替换 配置文件路径
|
||||
global.DefaultConfFile = c
|
||||
config.DefaultConfigFile = c
|
||||
logFormatter := &easy.Formatter{
|
||||
TimestampFormat: "2006-01-02 15:04:05",
|
||||
LogFormat: "[%time%] [%lvl%]: %msg% \n",
|
||||
@ -66,50 +63,23 @@ func init() {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
conf = getConfig()
|
||||
conf = config.Get()
|
||||
if conf == nil {
|
||||
os.Exit(1)
|
||||
_ = os.WriteFile("config.yml", []byte(config.DefaultConfig), 0644)
|
||||
log.Error("未找到配置文件,默认配置文件已生成!")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if debug {
|
||||
conf.Debug = true
|
||||
conf.Output.Debug = true
|
||||
}
|
||||
// 在debug模式下,将在标准输出中打印当前执行行数
|
||||
if conf.Debug {
|
||||
if conf.Output.Debug {
|
||||
log.SetReportCaller(true)
|
||||
}
|
||||
|
||||
log.AddHook(global.NewLocalHook(w, logFormatter, global.GetLogLevel(conf.LogLevel)...))
|
||||
|
||||
if global.PathExists("cqhttp.json") {
|
||||
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
|
||||
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.hjson 文件.")
|
||||
time.Sleep(time.Second * 5)
|
||||
conf := global.CQHTTPAPIConfig{}
|
||||
if err := json.Unmarshal([]byte(global.ReadAllText("cqhttp.json")), &conf); err != nil {
|
||||
log.Fatalf("读取文件 cqhttp.json 失败: %v", err)
|
||||
}
|
||||
goConf := global.DefaultConfig()
|
||||
goConf.AccessToken = conf.AccessToken
|
||||
goConf.HTTPConfig.Host = conf.Host
|
||||
goConf.HTTPConfig.Port = conf.Port
|
||||
goConf.WSConfig.Host = conf.WSHost
|
||||
goConf.WSConfig.Port = conf.WSPort
|
||||
if conf.PostURL != "" {
|
||||
goConf.HTTPConfig.PostUrls[conf.PostURL] = conf.Secret
|
||||
}
|
||||
if conf.UseWsReverse {
|
||||
goConf.ReverseServers[0].Enabled = true
|
||||
goConf.ReverseServers[0].ReverseURL = conf.WSReverseURL
|
||||
goConf.ReverseServers[0].ReverseAPIURL = conf.WSReverseAPIURL
|
||||
goConf.ReverseServers[0].ReverseEventURL = conf.WSReverseEventURL
|
||||
goConf.ReverseServers[0].ReverseReconnectInterval = conf.WSReverseReconnectInterval
|
||||
}
|
||||
if err := goConf.Save(global.DefaultConfFile); err != nil {
|
||||
log.Fatalf("保存 %s 时出现错误: %v", global.DefaultConfFile, err)
|
||||
}
|
||||
_ = os.Remove("cqhttp.json")
|
||||
}
|
||||
log.AddHook(global.NewLocalHook(w, logFormatter, global.GetLogLevel(conf.Output.LogLevel)...))
|
||||
|
||||
if !global.PathExists(global.ImagePath) {
|
||||
if err := os.MkdirAll(global.ImagePath, 0755); err != nil {
|
||||
@ -153,8 +123,7 @@ func main() {
|
||||
}
|
||||
case "key":
|
||||
if len(arg) > i+1 {
|
||||
b := []byte(arg[i+1])
|
||||
byteKey = b
|
||||
byteKey = []byte(arg[i+1])
|
||||
}
|
||||
case "faststart":
|
||||
isFastStart = true
|
||||
@ -166,7 +135,8 @@ func main() {
|
||||
log.Warning("将等待10s后启动")
|
||||
time.Sleep(time.Second * 10)
|
||||
}
|
||||
if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") {
|
||||
|
||||
if (conf.Account.Uin == 0 || (conf.Account.Password == "" && !conf.Account.Encrypt)) && !global.PathExists("session.token") {
|
||||
log.Warn("账号密码未配置, 将使用二维码登录.")
|
||||
if !isFastStart {
|
||||
log.Warn("将在 5秒 后继续.")
|
||||
@ -175,11 +145,10 @@ func main() {
|
||||
}
|
||||
|
||||
log.Info("当前版本:", coolq.Version)
|
||||
if conf.Debug {
|
||||
if conf.Output.Debug {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
log.Warnf("已开启Debug模式.")
|
||||
log.Debugf("开发交流群: 192548878")
|
||||
server.Debug = true
|
||||
/*
|
||||
if conf.WebUI == nil || !conf.WebUI.Enabled {
|
||||
log.Warnf("警告: 在Debug模式下未启用WebUi服务, 将无法进行性能分析.")
|
||||
@ -198,52 +167,58 @@ func main() {
|
||||
log.Fatalf("加载设备信息失败: %v", err)
|
||||
}
|
||||
}
|
||||
if conf.EncryptPassword && conf.PasswordEncrypted == "" {
|
||||
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
|
||||
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
|
||||
global.PasswordHash = md5.Sum([]byte(conf.Password))
|
||||
conf.Password = ""
|
||||
conf.PasswordEncrypted = "AES:" + PasswordHashEncrypt(global.PasswordHash[:], byteKey)
|
||||
_ = conf.Save(global.DefaultConfFile)
|
||||
}
|
||||
if conf.PasswordEncrypted != "" {
|
||||
if len(byteKey) == 0 {
|
||||
log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)")
|
||||
cancel := make(chan struct{}, 1)
|
||||
go func() {
|
||||
select {
|
||||
case <-cancel:
|
||||
return
|
||||
case <-time.After(time.Second * 45):
|
||||
log.Infof("解密key输入超时")
|
||||
time.Sleep(3 * time.Second)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
|
||||
if conf.Account.Encrypt {
|
||||
if !global.PathExists("password.encrypt") {
|
||||
if conf.Account.Password == "" {
|
||||
log.Error("无法进行加密,请在配置文件中的添加密码后重新启动.")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
}
|
||||
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
|
||||
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
|
||||
cancel <- struct{}{}
|
||||
global.PasswordHash = md5.Sum([]byte(conf.Account.Password))
|
||||
_ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(global.PasswordHash[:], byteKey)), 0644)
|
||||
log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
} else {
|
||||
log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.")
|
||||
}
|
||||
if conf.Account.Password != "" {
|
||||
log.Error("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// 升级客户端密码加密方案,MD5+TEA 加密密码 -> PBKDF2+AES 加密 MD5
|
||||
// 升级后的 PasswordEncrypted 字符串以"AES:"开始,其后为 Hex 编码的16字节加密 MD5
|
||||
if !strings.HasPrefix(conf.PasswordEncrypted, "AES:") {
|
||||
password := OldPasswordDecrypt(conf.PasswordEncrypted, byteKey)
|
||||
passwordHash := md5.Sum([]byte(password))
|
||||
newPasswordHash := PasswordHashEncrypt(passwordHash[:], byteKey)
|
||||
conf.PasswordEncrypted = "AES:" + newPasswordHash
|
||||
_ = conf.Save(global.DefaultConfFile)
|
||||
log.Debug("密码加密方案升级完成")
|
||||
}
|
||||
if len(byteKey) == 0 {
|
||||
log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)")
|
||||
cancel := make(chan struct{}, 1)
|
||||
state, _ := term.GetState(int(os.Stdin.Fd()))
|
||||
go func() {
|
||||
select {
|
||||
case <-cancel:
|
||||
return
|
||||
case <-time.After(time.Second * 45):
|
||||
log.Infof("解密key输入超时")
|
||||
time.Sleep(3 * time.Second)
|
||||
_ = term.Restore(int(os.Stdin.Fd()), state)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
|
||||
cancel <- struct{}{}
|
||||
} else {
|
||||
log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.")
|
||||
}
|
||||
|
||||
ph, err := PasswordHashDecrypt(conf.PasswordEncrypted[4:], byteKey)
|
||||
if err != nil {
|
||||
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
|
||||
encrypt, _ := os.ReadFile("password.encrypt")
|
||||
ph, err := PasswordHashDecrypt(string(encrypt), byteKey)
|
||||
if err != nil {
|
||||
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
|
||||
}
|
||||
copy(global.PasswordHash[:], ph)
|
||||
}
|
||||
copy(global.PasswordHash[:], ph)
|
||||
} else if conf.Password != "" {
|
||||
global.PasswordHash = md5.Sum([]byte(conf.Password))
|
||||
} else {
|
||||
global.PasswordHash = md5.Sum([]byte(conf.Account.Password))
|
||||
}
|
||||
if !isFastStart {
|
||||
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
|
||||
@ -264,8 +239,8 @@ func main() {
|
||||
return "未知"
|
||||
}())
|
||||
cli = client.NewClientEmpty()
|
||||
if conf.Uin != 0 && global.PasswordHash != [16]byte{} {
|
||||
cli.Uin = conf.Uin
|
||||
if conf.Account.Uin != 0 && global.PasswordHash != [16]byte{} {
|
||||
cli.Uin = conf.Account.Uin
|
||||
cli.PasswordMd5 = global.PasswordHash
|
||||
}
|
||||
cli.OnLog(func(c *client.QQClient, e *client.LogEvent) {
|
||||
@ -287,7 +262,7 @@ func main() {
|
||||
log.Infof("读取到 %v 个自定义地址.", len(addr))
|
||||
}
|
||||
cli.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool {
|
||||
if !conf.UseSSOAddress {
|
||||
if !conf.Account.UseSSOAddress {
|
||||
log.Infof("收到服务器地址更新通知, 根据配置文件已忽略.")
|
||||
return false
|
||||
}
|
||||
@ -310,41 +285,64 @@ func main() {
|
||||
conf.WebUI.Host = "127.0.0.1"
|
||||
}
|
||||
*/
|
||||
global.Proxy = conf.ProxyRewrite
|
||||
global.Proxy = conf.Message.ProxyRewrite
|
||||
// b := server.WebServer.Run(fmt.Sprintf("%s:%d", conf.WebUI.Host, conf.WebUI.WebUIPort), cli)
|
||||
// c := server.Console
|
||||
isQRCodeLogin := (conf.Uin == 0 || len(conf.Password) == 0) && len(conf.PasswordEncrypted) == 0
|
||||
if !isQRCodeLogin {
|
||||
if err := commonLogin(); err != nil {
|
||||
log.Fatalf("登录时发生致命错误: %v", err)
|
||||
}
|
||||
} else {
|
||||
if err := qrcodeLogin(); err != nil {
|
||||
log.Fatalf("登录时发生致命错误: %v", err)
|
||||
isQRCodeLogin := (conf.Account.Uin == 0 || len(conf.Account.Password) == 0) && !conf.Account.Encrypt
|
||||
isTokenLogin := false
|
||||
if global.PathExists("session.token") {
|
||||
token, err := ioutil.ReadFile("session.token")
|
||||
if err == nil {
|
||||
if err = cli.TokenLogin(token); err != nil {
|
||||
_ = os.Remove("session.token")
|
||||
log.Warnf("恢复会话失败: %v , 尝试使用正常流程登录.", err)
|
||||
} else {
|
||||
isTokenLogin = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !isTokenLogin {
|
||||
if !isQRCodeLogin {
|
||||
if err := commonLogin(); err != nil {
|
||||
log.Fatalf("登录时发生致命错误: %v", err)
|
||||
}
|
||||
} else {
|
||||
if err := qrcodeLogin(); err != nil {
|
||||
log.Fatalf("登录时发生致命错误: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
saveToken := func() {
|
||||
global.AccountToken = cli.GenToken()
|
||||
_ = ioutil.WriteFile("session.token", global.AccountToken, 0677)
|
||||
}
|
||||
saveToken()
|
||||
var times uint = 1 // 重试次数
|
||||
var reLoginLock sync.Mutex
|
||||
cli.OnDisconnected(func(q *client.QQClient, e *client.ClientDisconnectedEvent) {
|
||||
reLoginLock.Lock()
|
||||
defer reLoginLock.Unlock()
|
||||
log.Warnf("Bot已离线: %v", e.Message)
|
||||
if !conf.ReLogin.Enabled {
|
||||
if conf.Account.ReLogin.Disabled {
|
||||
os.Exit(1)
|
||||
}
|
||||
if isQRCodeLogin {
|
||||
log.Fatalf("二维码登录暂不支持重连.")
|
||||
}
|
||||
if times > conf.ReLogin.MaxReloginTimes && conf.ReLogin.MaxReloginTimes != 0 {
|
||||
if times > conf.Account.ReLogin.MaxTimes && conf.Account.ReLogin.MaxTimes != 0 {
|
||||
log.Fatalf("Bot重连次数超过限制, 停止")
|
||||
}
|
||||
if conf.ReLogin.ReLoginDelay > 0 {
|
||||
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", conf.ReLogin.ReLoginDelay, times, conf.ReLogin.MaxReloginTimes)
|
||||
if conf.Account.ReLogin.Interval > 0 {
|
||||
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", conf.Account.ReLogin.Interval, times, conf.Account.ReLogin.MaxTimes)
|
||||
}
|
||||
log.Warnf("尝试重连...")
|
||||
if cli.Online {
|
||||
return
|
||||
}
|
||||
if err := cli.TokenLogin(global.AccountToken); err == nil {
|
||||
saveToken()
|
||||
return
|
||||
}
|
||||
if isQRCodeLogin {
|
||||
log.Fatalf("快速重连失败")
|
||||
}
|
||||
if err := commonLogin(); err != nil {
|
||||
log.Fatalf("登录时发生致命错误: %v", err)
|
||||
}
|
||||
@ -352,37 +350,48 @@ func main() {
|
||||
cli.AllowSlider = true
|
||||
log.Infof("登录成功 欢迎使用: %v", cli.Nickname)
|
||||
log.Info("开始加载好友列表...")
|
||||
global.Check(cli.ReloadFriendList())
|
||||
global.Check(cli.ReloadFriendList(), true)
|
||||
log.Infof("共加载 %v 个好友.", len(cli.FriendList))
|
||||
log.Infof("开始加载群列表...")
|
||||
global.Check(cli.ReloadGroupList())
|
||||
global.Check(cli.ReloadGroupList(), true)
|
||||
log.Infof("共加载 %v 个群.", len(cli.GroupList))
|
||||
bot := coolq.NewQQBot(cli, conf)
|
||||
if conf.PostMessageFormat != "string" && conf.PostMessageFormat != "array" {
|
||||
log.Warnf("post_message_format 配置错误, 将自动使用 string")
|
||||
_ = bot.Client
|
||||
if conf.Message.PostFormat != "string" && conf.Message.PostFormat != "array" {
|
||||
log.Warnf("post-format 配置错误, 将自动使用 string")
|
||||
coolq.SetMessageFormat("string")
|
||||
} else {
|
||||
coolq.SetMessageFormat(conf.PostMessageFormat)
|
||||
}
|
||||
if conf.RateLimit.Enabled {
|
||||
global.InitLimiter(conf.RateLimit.Frequency, conf.RateLimit.BucketSize)
|
||||
coolq.SetMessageFormat(conf.Message.PostFormat)
|
||||
}
|
||||
log.Info("正在加载事件过滤器.")
|
||||
global.BootFilter()
|
||||
coolq.IgnoreInvalidCQCode = conf.IgnoreInvalidCQCode
|
||||
coolq.SplitURL = conf.FixURL
|
||||
coolq.ForceFragmented = conf.ForceFragmented
|
||||
if conf.HTTPConfig != nil && conf.HTTPConfig.Enabled {
|
||||
go server.CQHTTPApiServer.Run(fmt.Sprintf("%s:%d", conf.HTTPConfig.Host, conf.HTTPConfig.Port), conf.AccessToken, bot)
|
||||
for k, v := range conf.HTTPConfig.PostUrls {
|
||||
server.NewHTTPClient().Run(k, v, conf.HTTPConfig.Timeout, bot)
|
||||
coolq.IgnoreInvalidCQCode = conf.Message.IgnoreInvalidCQCode
|
||||
coolq.SplitURL = conf.Message.FixURL
|
||||
coolq.ForceFragmented = conf.Message.ForceFragment
|
||||
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("读取http配置失败 :", 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("读取http配置失败 :", err)
|
||||
} else {
|
||||
go server.RunWebSocketClient(bot, rc)
|
||||
}
|
||||
}
|
||||
}
|
||||
if conf.WSConfig != nil && conf.WSConfig.Enabled {
|
||||
go server.WebSocketServer.Run(fmt.Sprintf("%s:%d", conf.WSConfig.Host, conf.WSConfig.Port), conf.AccessToken, bot)
|
||||
}
|
||||
for _, rc := range conf.ReverseServers {
|
||||
go server.NewWebSocketClient(rc, conf.AccessToken, bot).Run()
|
||||
}
|
||||
log.Info("资源初始化完成, 开始处理信息.")
|
||||
log.Info("アトリは、高性能ですから!")
|
||||
@ -423,25 +432,6 @@ func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, erro
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// OldPasswordDecrypt 使用key解密老password,仅供兼容使用
|
||||
func OldPasswordDecrypt(encryptedPassword string, key []byte) string {
|
||||
defer func() {
|
||||
if pan := recover(); pan != nil {
|
||||
log.Fatalf("密码解密失败: %v", pan)
|
||||
}
|
||||
}()
|
||||
encKey := md5.Sum(key)
|
||||
encrypted, err := base64.StdEncoding.DecodeString(encryptedPassword)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
tea := binary.NewTeaCipher(encKey[:])
|
||||
if tea == nil {
|
||||
panic("密钥错误")
|
||||
}
|
||||
return string(tea.Decrypt(encrypted))
|
||||
}
|
||||
|
||||
func checkUpdate() {
|
||||
log.Infof("正在检查更新.")
|
||||
if coolq.Version == "(devel)" {
|
||||
@ -488,45 +478,31 @@ func selfUpdate(imageURL string) {
|
||||
log.Info("当前最新版本为 ", version)
|
||||
log.Warn("是否更新(y/N): ")
|
||||
r := strings.TrimSpace(readLine())
|
||||
|
||||
doUpdate := func() {
|
||||
if r != "y" && r != "Y" {
|
||||
log.Warn("已取消更新!")
|
||||
} else {
|
||||
log.Info("正在更新,请稍等...")
|
||||
url := fmt.Sprintf(
|
||||
"%v/Mrs4s/go-cqhttp/releases/download/%v/go-cqhttp-%v-%v-%v",
|
||||
"%v/Mrs4s/go-cqhttp/releases/download/%v/go-cqhttp_%v_%v",
|
||||
func() string {
|
||||
if imageURL != "" {
|
||||
return imageURL
|
||||
}
|
||||
return "https://github.com"
|
||||
}(),
|
||||
version,
|
||||
version,
|
||||
runtime.GOOS,
|
||||
runtime.GOARCH,
|
||||
version, runtime.GOOS, func() string {
|
||||
if runtime.GOARCH == "arm" {
|
||||
return "armv7"
|
||||
}
|
||||
return runtime.GOARCH
|
||||
}(),
|
||||
)
|
||||
if runtime.GOOS == "windows" {
|
||||
url += ".exe"
|
||||
url += ".zip"
|
||||
} else {
|
||||
url += ".tar.gz"
|
||||
}
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Error("更新失败: ", err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
wc := global.WriteCounter{}
|
||||
err, _ = global.UpdateFromStream(io.TeeReader(resp.Body, &wc))
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
log.Error("更新失败!")
|
||||
return
|
||||
}
|
||||
log.Info("更新完成!")
|
||||
}
|
||||
|
||||
if r == "y" || r == "Y" {
|
||||
doUpdate()
|
||||
} else {
|
||||
log.Warn("已取消更新!")
|
||||
update.Update(url)
|
||||
}
|
||||
} else {
|
||||
log.Info("当前版本已经是最新版本!")
|
||||
@ -569,56 +545,6 @@ func restart(args []string) {
|
||||
}
|
||||
*/
|
||||
|
||||
func getConfig() *global.JSONConfig {
|
||||
var conf *global.JSONConfig
|
||||
switch {
|
||||
case global.PathExists("config.json"):
|
||||
conf = global.LoadConfig("config.json")
|
||||
_ = conf.Save("config.hjson")
|
||||
_ = os.Remove("config.json")
|
||||
case os.Getenv("UIN") != "":
|
||||
log.Infof("将从环境变量加载配置.")
|
||||
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
|
||||
pwd := os.Getenv("PASS")
|
||||
post := os.Getenv("HTTP_POST")
|
||||
conf = &global.JSONConfig{
|
||||
Uin: uin,
|
||||
Password: pwd,
|
||||
HTTPConfig: &global.GoCQHTTPConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 5700,
|
||||
PostUrls: map[string]string{},
|
||||
},
|
||||
WSConfig: &global.GoCQWebSocketConfig{
|
||||
Enabled: true,
|
||||
Host: "0.0.0.0",
|
||||
Port: 6700,
|
||||
},
|
||||
PostMessageFormat: "string",
|
||||
Debug: os.Getenv("DEBUG") == "true",
|
||||
}
|
||||
if post != "" {
|
||||
conf.HTTPConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
|
||||
}
|
||||
default:
|
||||
conf = global.LoadConfig(global.DefaultConfFile)
|
||||
}
|
||||
if conf == nil {
|
||||
err := global.WriteAllText(global.DefaultConfFile, global.DefaultConfigWithComments)
|
||||
if err != nil {
|
||||
log.Fatalf("创建默认配置文件时出现错误: %v", err)
|
||||
return nil
|
||||
}
|
||||
log.Infof("默认配置文件已生成, 请编辑 %s 后重启程序.", global.DefaultConfFile)
|
||||
if !isFastStart {
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return conf
|
||||
}
|
||||
|
||||
// help cli命令行-h的帮助提示
|
||||
func help() {
|
||||
fmt.Printf(`go-cqhttp service
|
||||
|
19
scripts/upload_dist.sh
Normal file
19
scripts/upload_dist.sh
Normal file
@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [ "$GITHUB_ACTIONS" != "true" ]; then
|
||||
echo "This script is only meant to be run in GitHub Actions."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cp -f dist/*.tar.gz upstream/dist/downloads
|
||||
cp -f dist/*.zip upstream/dist/downloads
|
||||
cd upstream/dist || exit
|
||||
LATEST_VERSION="${GITHUB_REF#"refs/tags/"}"
|
||||
git config --local user.name 'Github Actions'
|
||||
git config --local user.email 'github-actions@users.noreply.github.com'
|
||||
git add --all
|
||||
git commit -m "update to $LATEST_VERSION"
|
||||
git tag -d "$LATEST_VERSION"
|
||||
git tag "$LATEST_VERSION"
|
||||
git push
|
||||
git push --tags
|
@ -13,8 +13,11 @@ type resultGetter interface {
|
||||
Get(string) gjson.Result
|
||||
}
|
||||
|
||||
type handler func(action string, p resultGetter) coolq.MSG
|
||||
|
||||
type apiCaller struct {
|
||||
bot *coolq.CQBot
|
||||
bot *coolq.CQBot
|
||||
handlers []handler
|
||||
}
|
||||
|
||||
func getLoginInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG {
|
||||
@ -39,9 +42,10 @@ func getGroupMemberList(bot *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
|
||||
func getGroupMemberInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
return bot.CQGetGroupMemberInfo(
|
||||
p.Get("group_id").Int(), p.Get("user_id").Int(),
|
||||
p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("no_cache").Bool(),
|
||||
)
|
||||
}
|
||||
|
||||
func sendMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
autoEscape := global.EnsureBool(p.Get("auto_escape"), false)
|
||||
if p.Get("message_type").Str == "private" {
|
||||
@ -258,8 +262,9 @@ func getVipInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
return bot.CQGetVipInfo(p.Get("user_id").Int())
|
||||
}
|
||||
|
||||
func reloadEventFilter(bot *coolq.CQBot, _ resultGetter) coolq.MSG {
|
||||
return bot.CQReloadEventFilter()
|
||||
func reloadEventFilter(_ *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
addFilter(p.Get("file").String())
|
||||
return coolq.OK(nil)
|
||||
}
|
||||
|
||||
func getGroupAtAllRemain(bot *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
@ -317,6 +322,7 @@ func handleQuickOperation(bot *coolq.CQBot, p resultGetter) coolq.MSG {
|
||||
return bot.CQHandleQuickOperation(p.Get("context"), p.Get("operation"))
|
||||
}
|
||||
|
||||
// API 是go-cqhttp当前支持的所有api的映射表
|
||||
var API = map[string]func(*coolq.CQBot, resultGetter) coolq.MSG{
|
||||
"get_login_info": getLoginInfo,
|
||||
"get_friend_list": getFriendList,
|
||||
@ -375,8 +381,24 @@ var API = map[string]func(*coolq.CQBot, resultGetter) coolq.MSG{
|
||||
}
|
||||
|
||||
func (api *apiCaller) callAPI(action string, p resultGetter) coolq.MSG {
|
||||
for _, fn := range api.handlers {
|
||||
if ret := fn(action, p); ret != nil {
|
||||
return ret
|
||||
}
|
||||
}
|
||||
if f, ok := API[action]; ok {
|
||||
return f(api.bot, p)
|
||||
}
|
||||
return coolq.Failed(404, "API_NOT_FOUND", "API不存在")
|
||||
}
|
||||
|
||||
func (api *apiCaller) use(middlewares ...handler) {
|
||||
api.handlers = append(api.handlers, middlewares...)
|
||||
}
|
||||
|
||||
func newAPICaller(bot *coolq.CQBot) *apiCaller {
|
||||
return &apiCaller{
|
||||
bot: bot,
|
||||
handlers: []handler{},
|
||||
}
|
||||
}
|
||||
|
@ -30,7 +30,6 @@ func Daemon() {
|
||||
|
||||
proc := exec.Command(os.Args[0], execArgs...)
|
||||
err := proc.Start()
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
@ -1,2 +1,2 @@
|
||||
// Package server 包含Admin子站,HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体
|
||||
// Package server 包含HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体
|
||||
package server
|
||||
|
@ -6,13 +6,14 @@ import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/global/config"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
@ -26,7 +27,7 @@ type httpServer struct {
|
||||
engine *gin.Engine
|
||||
bot *coolq.CQBot
|
||||
HTTP *http.Server
|
||||
api apiCaller
|
||||
api *apiCaller
|
||||
}
|
||||
|
||||
// HTTPClient 反向HTTP上报客户端
|
||||
@ -34,6 +35,7 @@ type HTTPClient struct {
|
||||
bot *coolq.CQBot
|
||||
secret string
|
||||
addr string
|
||||
filter string
|
||||
timeout int32
|
||||
}
|
||||
|
||||
@ -41,17 +43,23 @@ type httpContext struct {
|
||||
ctx *gin.Context
|
||||
}
|
||||
|
||||
// CQHTTPApiServer CQHTTPApiServer实例
|
||||
var CQHTTPApiServer = &httpServer{}
|
||||
|
||||
// Debug 是否启用Debug模式
|
||||
var Debug = false
|
||||
|
||||
func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
|
||||
// RunHTTPServerAndClients 启动HTTP服务器与HTTP上报客户端
|
||||
func RunHTTPServerAndClients(bot *coolq.CQBot, conf *config.HTTPServer) {
|
||||
if conf.Disabled {
|
||||
return
|
||||
}
|
||||
var (
|
||||
s = new(httpServer)
|
||||
authToken = conf.AccessToken
|
||||
addr = fmt.Sprintf("%s:%d", conf.Host, conf.Port)
|
||||
)
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
s.engine = gin.New()
|
||||
s.bot = bot
|
||||
s.api = apiCaller{s.bot}
|
||||
s.api = newAPICaller(s.bot)
|
||||
if conf.RateLimit.Enabled {
|
||||
s.api.use(rateLimit(conf.RateLimit.Frequency, conf.RateLimit.Bucket))
|
||||
}
|
||||
s.engine.Use(func(c *gin.Context) {
|
||||
if c.Request.Method != "GET" && c.Request.Method != "POST" {
|
||||
log.Warnf("已拒绝客户端 %v 的请求: 方法错误", c.Request.RemoteAddr)
|
||||
@ -79,9 +87,10 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
|
||||
s.engine.Use(func(c *gin.Context) {
|
||||
auth := c.Request.Header.Get("Authorization")
|
||||
switch {
|
||||
case auth != "" && strings.SplitN(auth, " ", 2)[1] != authToken:
|
||||
c.AbortWithStatus(401)
|
||||
return
|
||||
case auth != "":
|
||||
if strings.SplitN(auth, " ", 2)[1] != authToken {
|
||||
c.AbortWithStatus(401)
|
||||
}
|
||||
case c.Query("access_token") != authToken:
|
||||
c.AbortWithStatus(401)
|
||||
return
|
||||
@ -107,19 +116,27 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
for _, c := range conf.Post {
|
||||
if c.URL != "" {
|
||||
go newHTTPClient().Run(c.URL, c.Secret, conf.Filter, conf.Timeout, bot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewHTTPClient 返回反向HTTP客户端
|
||||
func NewHTTPClient() *HTTPClient {
|
||||
// newHTTPClient 返回反向HTTP客户端
|
||||
func newHTTPClient() *HTTPClient {
|
||||
return &HTTPClient{}
|
||||
}
|
||||
|
||||
// Run 运行反向HTTP服务
|
||||
func (c *HTTPClient) Run(addr, secret string, timeout int32, bot *coolq.CQBot) {
|
||||
func (c *HTTPClient) Run(addr, secret, filter string, timeout int32, bot *coolq.CQBot) {
|
||||
c.bot = bot
|
||||
c.secret = secret
|
||||
c.addr = addr
|
||||
c.timeout = timeout
|
||||
c.filter = filter
|
||||
addFilter(filter)
|
||||
if c.timeout < 5 {
|
||||
c.timeout = 5
|
||||
}
|
||||
@ -129,6 +146,14 @@ func (c *HTTPClient) Run(addr, secret string, timeout int32, bot *coolq.CQBot) {
|
||||
|
||||
func (c *HTTPClient) onBotPushEvent(m *bytes.Buffer) {
|
||||
var res string
|
||||
if c.filter != "" {
|
||||
filter := findFilter(c.filter)
|
||||
if filter != nil && !filter.Eval(gjson.Parse(utils.B2S(m.Bytes()))) {
|
||||
log.Debugf("上报Event %v 到 HTTP 服务器 %v 时被过滤.", c.addr, utils.B2S(m.Bytes()))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := gout.POST(c.addr).SetJSON(m.Bytes()).BindBody(&res).SetHeader(func() gout.H {
|
||||
h := gout.H{
|
||||
"X-Self-ID": c.bot.Client.Uin,
|
||||
@ -164,7 +189,6 @@ func (c *HTTPClient) onBotPushEvent(m *bytes.Buffer) {
|
||||
}
|
||||
|
||||
func (s *httpServer) HandleActions(c *gin.Context) {
|
||||
global.RateLimit(context.Background())
|
||||
action := strings.ReplaceAll(c.Param("action"), "_async", "")
|
||||
log.Debugf("HTTPServer接收到API调用: %v", action)
|
||||
c.JSON(200, s.api.callAPI(action, httpContext{ctx: c}))
|
||||
|
56
server/middlewares.go
Normal file
56
server/middlewares.go
Normal file
@ -0,0 +1,56 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
var (
|
||||
filters = make(map[string]global.Filter)
|
||||
filterMutex sync.RWMutex
|
||||
)
|
||||
|
||||
func rateLimit(frequency float64, bucketSize int) handler {
|
||||
limiter := rate.NewLimiter(rate.Limit(frequency), bucketSize)
|
||||
return func(_ string, _ resultGetter) coolq.MSG {
|
||||
_ = limiter.Wait(context.Background())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func addFilter(file string) {
|
||||
if file == "" {
|
||||
return
|
||||
}
|
||||
bs, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
log.Error("init filter error: ", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Error("init filter error: ", err)
|
||||
}
|
||||
}()
|
||||
filter := global.Generate("and", gjson.ParseBytes(bs))
|
||||
filterMutex.Lock()
|
||||
filters[file] = filter
|
||||
filterMutex.Unlock()
|
||||
}
|
||||
|
||||
func findFilter(file string) global.Filter {
|
||||
if file == "" {
|
||||
return nil
|
||||
}
|
||||
filterMutex.RLock()
|
||||
defer filterMutex.RUnlock()
|
||||
return filters[file]
|
||||
}
|
@ -2,7 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
@ -13,6 +12,7 @@ import (
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/global/config"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
"github.com/gorilla/websocket"
|
||||
@ -21,42 +21,53 @@ import (
|
||||
)
|
||||
|
||||
type webSocketServer struct {
|
||||
bot *coolq.CQBot
|
||||
token string
|
||||
bot *coolq.CQBot
|
||||
conf *config.WebsocketServer
|
||||
|
||||
eventConn []*webSocketConn
|
||||
eventConnMutex sync.Mutex
|
||||
token string
|
||||
handshake string
|
||||
filter string
|
||||
}
|
||||
|
||||
// WebSocketClient WebSocket客户端实例
|
||||
type WebSocketClient struct {
|
||||
conf *global.GoCQReverseWebSocketConfig
|
||||
token string
|
||||
bot *coolq.CQBot
|
||||
bot *coolq.CQBot
|
||||
conf *config.WebsocketReverse
|
||||
|
||||
universalConn *webSocketConn
|
||||
eventConn *webSocketConn
|
||||
token string
|
||||
filter string
|
||||
}
|
||||
|
||||
type webSocketConn struct {
|
||||
*websocket.Conn
|
||||
sync.Mutex
|
||||
apiCaller apiCaller
|
||||
apiCaller *apiCaller
|
||||
}
|
||||
|
||||
// WebSocketServer 初始化一个WebSocketServer实例
|
||||
var WebSocketServer = &webSocketServer{}
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
func (s *webSocketServer) Run(addr, authToken string, b *coolq.CQBot) {
|
||||
s.token = authToken
|
||||
// RunWebSocketServer 运行一个正向WS server
|
||||
func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) {
|
||||
if conf.Disabled {
|
||||
return
|
||||
}
|
||||
s := new(webSocketServer)
|
||||
s.conf = conf
|
||||
s.bot = b
|
||||
s.token = conf.AccessToken
|
||||
s.filter = conf.Filter
|
||||
addFilter(s.filter)
|
||||
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
|
||||
s.handshake = fmt.Sprintf(`{"_post_method":2,"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
|
||||
s.bot.Client.Uin, time.Now().Unix())
|
||||
b.Client.Uin, time.Now().Unix())
|
||||
b.OnEventPush(s.onBotPushEvent)
|
||||
http.HandleFunc("/event", s.event)
|
||||
http.HandleFunc("/api", s.api)
|
||||
@ -67,23 +78,24 @@ func (s *webSocketServer) Run(addr, authToken string, b *coolq.CQBot) {
|
||||
}()
|
||||
}
|
||||
|
||||
// NewWebSocketClient 初始化一个NWebSocket客户端
|
||||
func NewWebSocketClient(conf *global.GoCQReverseWebSocketConfig, authToken string, b *coolq.CQBot) *WebSocketClient {
|
||||
return &WebSocketClient{conf: conf, token: authToken, bot: b}
|
||||
}
|
||||
|
||||
// Run 运行实例
|
||||
func (c *WebSocketClient) Run() {
|
||||
if !c.conf.Enabled {
|
||||
// RunWebSocketClient 运行一个正向WS client
|
||||
func RunWebSocketClient(b *coolq.CQBot, conf *config.WebsocketReverse) {
|
||||
if conf.Disabled {
|
||||
return
|
||||
}
|
||||
if c.conf.ReverseURL != "" {
|
||||
c := new(WebSocketClient)
|
||||
c.bot = b
|
||||
c.conf = conf
|
||||
c.token = conf.AccessToken
|
||||
c.filter = conf.Filter
|
||||
addFilter(c.filter)
|
||||
if c.conf.Universal != "" {
|
||||
c.connectUniversal()
|
||||
} else {
|
||||
if c.conf.ReverseAPIURL != "" {
|
||||
if c.conf.API != "" {
|
||||
c.connectAPI()
|
||||
}
|
||||
if c.conf.ReverseEventURL != "" {
|
||||
if c.conf.Event != "" {
|
||||
c.connectEvent()
|
||||
}
|
||||
}
|
||||
@ -91,7 +103,7 @@ func (c *WebSocketClient) Run() {
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) connectAPI() {
|
||||
log.Infof("开始尝试连接到反向WebSocket API服务器: %v", c.conf.ReverseAPIURL)
|
||||
log.Infof("开始尝试连接到反向WebSocket API服务器: %v", c.conf.API)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"API"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
@ -100,22 +112,25 @@ func (c *WebSocketClient) connectAPI() {
|
||||
if c.token != "" {
|
||||
header["Authorization"] = []string{"Token " + c.token}
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.ReverseAPIURL, header) // nolint
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.API, header) // nolint
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向WebSocket API服务器 %v 时出现错误: %v", c.conf.ReverseAPIURL, err)
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
log.Warnf("连接到反向WebSocket API服务器 %v 时出现错误: %v", c.conf.API, err)
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
c.connectAPI()
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Infof("已连接到反向WebSocket API服务器 %v", c.conf.ReverseAPIURL)
|
||||
wrappedConn := &webSocketConn{Conn: conn, apiCaller: apiCaller{c.bot}}
|
||||
log.Infof("已连接到反向WebSocket API服务器 %v", c.conf.API)
|
||||
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))
|
||||
}
|
||||
go c.listenAPI(wrappedConn, false)
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) connectEvent() {
|
||||
log.Infof("开始尝试连接到反向WebSocket Event服务器: %v", c.conf.ReverseEventURL)
|
||||
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)},
|
||||
@ -124,11 +139,11 @@ func (c *WebSocketClient) connectEvent() {
|
||||
if c.token != "" {
|
||||
header["Authorization"] = []string{"Token " + c.token}
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.ReverseEventURL, header) // nolint
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.Event, header) // nolint
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向WebSocket Event服务器 %v 时出现错误: %v", c.conf.ReverseEventURL, err)
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
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
|
||||
@ -141,12 +156,12 @@ func (c *WebSocketClient) connectEvent() {
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
|
||||
log.Infof("已连接到反向WebSocket Event服务器 %v", c.conf.ReverseEventURL)
|
||||
c.eventConn = &webSocketConn{Conn: conn, apiCaller: apiCaller{c.bot}}
|
||||
log.Infof("已连接到反向WebSocket Event服务器 %v", c.conf.Event)
|
||||
c.eventConn = &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) connectUniversal() {
|
||||
log.Infof("开始尝试连接到反向WebSocket Universal服务器: %v", c.conf.ReverseURL)
|
||||
log.Infof("开始尝试连接到反向WebSocket Universal服务器: %v", c.conf.Universal)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"Universal"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
@ -155,11 +170,11 @@ func (c *WebSocketClient) connectUniversal() {
|
||||
if c.token != "" {
|
||||
header["Authorization"] = []string{"Token " + c.token}
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.ReverseURL, header) // nolint
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.Universal, header) // nolint
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向WebSocket Universal服务器 %v 时出现错误: %v", c.conf.ReverseURL, err)
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
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
|
||||
@ -171,7 +186,10 @@ func (c *WebSocketClient) connectUniversal() {
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
|
||||
wrappedConn := &webSocketConn{Conn: conn, apiCaller: apiCaller{c.bot}}
|
||||
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))
|
||||
}
|
||||
go c.listenAPI(wrappedConn, true)
|
||||
c.universalConn = wrappedConn
|
||||
}
|
||||
@ -199,8 +217,8 @@ func (c *WebSocketClient) listenAPI(conn *webSocketConn, u bool) {
|
||||
global.PutBuffer(buffer)
|
||||
}
|
||||
}
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
if !u {
|
||||
go c.connectAPI()
|
||||
}
|
||||
@ -208,6 +226,12 @@ func (c *WebSocketClient) listenAPI(conn *webSocketConn, u bool) {
|
||||
}
|
||||
|
||||
func (c *WebSocketClient) onBotPushEvent(m *bytes.Buffer) {
|
||||
filter := findFilter(c.filter)
|
||||
if filter != nil && !filter.Eval(gjson.Parse(utils.B2S(m.Bytes()))) {
|
||||
log.Debugf("上报Event %v 到 WS客户端 时被过滤.", utils.B2S(m.Bytes()))
|
||||
return
|
||||
}
|
||||
|
||||
if c.eventConn != nil {
|
||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.eventConn.RemoteAddr().String(), utils.B2S(m.Bytes()))
|
||||
conn := c.eventConn
|
||||
@ -217,8 +241,8 @@ func (c *WebSocketClient) onBotPushEvent(m *bytes.Buffer) {
|
||||
if err := c.eventConn.WriteMessage(websocket.TextMessage, m.Bytes()); err != nil {
|
||||
log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", c.eventConn.RemoteAddr().String(), err)
|
||||
_ = c.eventConn.Close()
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
c.connectEvent()
|
||||
}
|
||||
}
|
||||
@ -232,8 +256,8 @@ func (c *WebSocketClient) onBotPushEvent(m *bytes.Buffer) {
|
||||
if err := c.universalConn.WriteMessage(websocket.TextMessage, m.Bytes()); err != nil {
|
||||
log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", c.universalConn.RemoteAddr().String(), err)
|
||||
_ = c.universalConn.Close()
|
||||
if c.conf.ReverseReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
c.connectUniversal()
|
||||
}
|
||||
}
|
||||
@ -241,7 +265,7 @@ func (c *WebSocketClient) onBotPushEvent(m *bytes.Buffer) {
|
||||
}
|
||||
|
||||
func (s *webSocketServer) event(w http.ResponseWriter, r *http.Request) {
|
||||
if s.token != "" {
|
||||
if s.conf.AccessToken != "" {
|
||||
if auth := r.URL.Query().Get("access_token"); auth != s.token {
|
||||
if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) != 2 || auth[1] != s.token {
|
||||
log.Warnf("已拒绝 %v 的 WebSocket 请求: Token鉴权失败", r.RemoteAddr)
|
||||
@ -264,7 +288,7 @@ func (s *webSocketServer) event(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
log.Infof("接受 WebSocket 连接: %v (/event)", r.RemoteAddr)
|
||||
|
||||
conn := &webSocketConn{Conn: c, apiCaller: apiCaller{s.bot}}
|
||||
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
|
||||
s.eventConnMutex.Lock()
|
||||
s.eventConn = append(s.eventConn, conn)
|
||||
@ -287,7 +311,10 @@ func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
log.Infof("接受 WebSocket 连接: %v (/api)", r.RemoteAddr)
|
||||
conn := &webSocketConn{Conn: c, apiCaller: apiCaller{s.bot}}
|
||||
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
if s.conf.RateLimit.Enabled {
|
||||
conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket))
|
||||
}
|
||||
go s.listenAPI(conn)
|
||||
}
|
||||
|
||||
@ -313,7 +340,10 @@ func (s *webSocketServer) any(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
log.Infof("接受 WebSocket 连接: %v (/)", r.RemoteAddr)
|
||||
conn := &webSocketConn{Conn: c, apiCaller: apiCaller{s.bot}}
|
||||
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
if s.conf.RateLimit.Enabled {
|
||||
conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket))
|
||||
}
|
||||
s.eventConnMutex.Lock()
|
||||
s.eventConn = append(s.eventConn, conn)
|
||||
s.eventConnMutex.Unlock()
|
||||
@ -351,7 +381,6 @@ func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) {
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
global.RateLimit(context.Background())
|
||||
j := gjson.ParseBytes(payload)
|
||||
t := strings.ReplaceAll(j.Get("action").Str, "_async", "")
|
||||
log.Debugf("WS接收到API调用: %v 参数: %v", t, j.Get("params").Raw)
|
||||
@ -367,6 +396,13 @@ func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) {
|
||||
func (s *webSocketServer) onBotPushEvent(m *bytes.Buffer) {
|
||||
s.eventConnMutex.Lock()
|
||||
defer s.eventConnMutex.Unlock()
|
||||
|
||||
filter := findFilter(s.filter)
|
||||
if filter != nil && !filter.Eval(gjson.Parse(utils.B2S(m.Bytes()))) {
|
||||
log.Debugf("上报Event %v 到 WS客户端 时被过滤.", utils.B2S(m.Bytes()))
|
||||
return
|
||||
}
|
||||
|
||||
for i, l := 0, len(s.eventConn); i < l; i++ {
|
||||
conn := s.eventConn[i]
|
||||
log.Debugf("向WS客户端 %v 推送Event: %v", conn.RemoteAddr().String(), utils.B2S(m.Bytes()))
|
||||
|
Reference in New Issue
Block a user