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

Compare commits

..

57 Commits

Author SHA1 Message Date
2057e769da update MiraiGo. 2020-11-20 23:51:17 +08:00
0ea85e2fab Merge pull request #438 from wfjsw/patches/add-reject_add_request-to-group-kick
reject_add_request
2020-11-20 21:26:43 +08:00
36b081eeec reject_add_request
(cherry picked from commit 061a230c9fb723ad49e00776fa37aca080973ecd)
2020-11-20 14:05:17 +08:00
2a044a62d2 update MiraiGo. 2020-11-20 09:07:30 +08:00
e0ffb98665 add comments for default config. 2020-11-20 03:01:58 +08:00
861bcf30b1 Merge branch 'dev' of https://github.com/Mrs4s/go-cqhttp into dev 2020-11-20 02:21:17 +08:00
56d7815f6a Merge pull request #437 from fkx4-p/patch-3
Update quick_start.md
2020-11-20 01:56:58 +08:00
59934982b9 Update quick_start.md
1.Fixed Ink33's typo and my error.
2.Added a discription and an example to make the checking part more reasonable.
2020-11-19 22:48:30 +08:00
09c4801b56 fix config. 2020-11-19 09:16:32 +08:00
f1f58b4072 update MiraiGo. 2020-11-19 09:12:41 +08:00
86c2f3cb11 Merge branch 'master' into dev 2020-11-19 09:04:30 +08:00
03c3340954 Merge pull request #426 from Ink-33/master
Fix: set_restart api panic
2020-11-19 00:22:56 +08:00
64b1a223cc Fix #427 2020-11-18 22:46:52 +08:00
b2be595fb8 simplifies composite literals 2020-11-18 22:33:51 +08:00
22225f2b74 Merge pull request #429 from wdvxdr1123/dev
change config file to hjson
2020-11-18 21:47:30 +08:00
eb3d7434cc use hjson 2020-11-18 21:06:37 +08:00
8f7f207891 Merge remote-tracking branch 'upstream/master' into dev 2020-11-18 12:29:17 +08:00
83e0aaa0f8 Fix: set_restart api panic 2020-11-18 01:31:45 +08:00
8f76558317 fix actions. 2020-11-18 00:37:00 +08:00
d94d389843 doc update. 2020-11-18 00:17:05 +08:00
df0d5af07a update MiraiGo. 2020-11-18 00:04:33 +08:00
277629e784 Merge branch 'master' into dev 2020-11-18 00:00:24 +08:00
d66a99c5a3 Merge pull request #424 from wfjsw/patches/proper-flash-pic-support
proper flash pic support
2020-11-17 21:26:27 +08:00
55895e0de1 Update dependencies 2020-11-17 21:03:00 +08:00
39da163641 proper flash pic support 2020-11-17 21:01:28 +08:00
1dbd72c138 update MiraiGo. 2020-11-17 19:13:44 +08:00
31756e9e1d update MiraiGo. 2020-11-17 19:06:23 +08:00
5ab713e7d3 fix cqcode encoder. 2020-11-17 19:05:11 +08:00
b6eb559172 Merge pull request #419 from Ink-33/master
Feather support: set_restart #407
2020-11-17 19:00:54 +08:00
da2e34aaa5 Update http.go 2020-11-17 14:02:44 +08:00
beb1a2883a Update websocket.go 2020-11-17 14:02:44 +08:00
8f34003c6f Update websocket.go 2020-11-17 14:02:44 +08:00
7f3e58f97a Update ci.yml 2020-11-17 01:45:14 +08:00
0fc004077b delete unused import 2020-11-17 01:30:05 +08:00
e9a03b68b5 delete test function 2020-11-17 01:26:13 +08:00
e9b39f3379 Fix: set_restart delay不生效的问题 2020-11-17 01:24:16 +08:00
e053da62e1 Update adminApi.md 2020-11-17 01:23:44 +08:00
f87b5c8215 Fix seflUpdate 2020-11-17 00:26:51 +08:00
28f1594539 feather: faststart 2020-11-17 00:24:25 +08:00
990e7744a3 Update docs 2020-11-17 00:13:14 +08:00
8900839018 Improved restart method 2020-11-16 23:51:45 +08:00
4a3288cb8d feather: add set_restart api support 2020-11-16 22:36:47 +08:00
0f0f74ece8 feather: use startup params to decrypt password 2020-11-16 22:34:05 +08:00
79ba9474a3 update 2020-11-15 16:19:57 +08:00
cb9d872071 Fix ineffectual assignment. 2020-11-15 16:17:43 +08:00
4c3105fa24 Merge remote-tracking branch 'upstream/master' 2020-11-15 16:08:00 +08:00
a8176e69e6 Merge pull request #416 from TheresaQWQ/master
fix typo
2020-11-15 13:47:33 +08:00
afa356e551 Update adminApi.md 2020-11-14 19:30:32 +08:00
a52ae1c828 update MiraiGo. 2020-11-14 19:07:08 +08:00
b8ec05e1c1 feature private poke. 2020-11-14 19:03:36 +08:00
2cbf23bceb trim for custom ip file. 2020-11-14 18:54:17 +08:00
3e5c2bc8e3 update MiraiGo. 2020-11-14 15:18:41 +08:00
69a2360d02 Merge pull request #413 from wdvxdr1123/dev
add some gift id
2020-11-14 12:47:13 +08:00
5b0ede5346 add some gift id 2020-11-13 22:32:00 +08:00
80af002668 Merge remote-tracking branch 'upstream/dev' into dev 2020-11-13 21:03:50 +08:00
f9c0b94af6 Merge remote-tracking branch 'upstream/master' into master
Update Upstream
2020-10-11 10:41:44 +08:00
4c9f60da09 update Dockerfile 2020-10-11 10:39:33 +08:00
27 changed files with 844 additions and 464 deletions

View File

@ -28,7 +28,7 @@ jobs:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Setup Go environment - name: Setup Go environment
uses: actions/setup-go@v2.1.1 uses: actions/setup-go@v2.1.3
with: with:
go-version: 1.15 go-version: 1.15

View File

@ -20,7 +20,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set RELEASE_VERSION env - name: Set RELEASE_VERSION env
run: echo ::set-env name=RELEASE_VERSION::${GITHUB_REF:10} run: echo "RELEASE_VERSION=${GITHUB_REF:10}" >> $GITHUB_ENV
- uses: pcrbot/go-release-action@master - uses: pcrbot/go-release-action@master
env: env:
CGO_ENABLED: 0 CGO_ENABLED: 0

View File

@ -1,4 +1,4 @@
FROM golang:1.14.7-alpine AS builder FROM golang:1.15.5-alpine AS builder
RUN go env -w GO111MODULE=auto \ RUN go env -w GO111MODULE=auto \
&& go env -w CGO_ENABLED=0 \ && go env -w CGO_ENABLED=0 \

View File

@ -47,32 +47,33 @@
##### 注意: 部分API实现与CQHTTP原版略有差异请参考文档 ##### 注意: 部分API实现与CQHTTP原版略有差异请参考文档
| API | 功能 | | API | 功能 |
| ------------------------ | ------------------------------------------------------------ | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| /get_login_info | [获取登录号信息](https://cqhttp.cc/docs/4.15/#/API?id=get_login_info-获取登录号信息) | | /get_login_info | [获取登录号信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_login_info-%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E5%8F%B7%E4%BF%A1%E6%81%AF) |
| /get_friend_list | [获取好友列表](https://cqhttp.cc/docs/4.15/#/API?id=get_friend_list-获取好友列表) | | /get_friend_list | [获取好友列表](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_friend_list-%E8%8E%B7%E5%8F%96%E5%A5%BD%E5%8F%8B%E5%88%97%E8%A1%A8) |
| /get_group_list | [获取群列表](https://cqhttp.cc/docs/4.15/#/API?id=get_group_list-获取群列表) | | /get_group_list | [获取群列表](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_group_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%88%97%E8%A1%A8) |
| /get_group_info | [获取群信息](https://cqhttp.cc/docs/4.15/#/API?id=get_group_info-获取群信息) | | /get_group_info | [获取群信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_group_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E4%BF%A1%E6%81%AF) |
| /get_group_member_list | [获取群成员列表](https://cqhttp.cc/docs/4.15/#/API?id=get_group_member_list-获取群成员列表) | | /get_group_member_list | [获取群成员列表](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_group_member_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%88%90%E5%91%98%E5%88%97%E8%A1%A8) |
| /get_group_member_info | [获取群成员信息](https://cqhttp.cc/docs/4.15/#/API?id=get_group_member_info-获取群成员信息) | | /get_group_member_info | [获取群成员信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_group_member_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%88%90%E5%91%98%E4%BF%A1%E6%81%AF) |
| /send_msg | [发送消息](https://cqhttp.cc/docs/4.15/#/API?id=send_msg-发送消息) | | /send_msg | [发送消息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#send_msg-%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF) |
| /send_group_msg | [发送群消息](https://cqhttp.cc/docs/4.15/#/API?id=send_group_msg-发送群消息) | | /send_group_msg | [发送群消息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#send_group_msg-%E5%8F%91%E9%80%81%E7%BE%A4%E6%B6%88%E6%81%AF) |
| /send_private_msg | [发送私聊消息](https://cqhttp.cc/docs/4.15/#/API?id=send_private_msg-发送私聊消息) | | /send_private_msg | [发送私聊消息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#send_private_msg-%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF) |
| /delete_msg | [撤回信息](https://cqhttp.cc/docs/4.15/#/API?id=delete_msg-撤回消息) | | /delete_msg | [撤回信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF) |
| /set_friend_add_request | [处理加好友请求](https://cqhttp.cc/docs/4.15/#/API?id=set_friend_add_request-处理加好友请求) | | /set_friend_add_request | [处理加好友请求](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82) |
| /set_group_add_request | [处理加群请求/邀请](https://cqhttp.cc/docs/4.15/#/API?id=set_group_add_request-处理加群请求/邀请) | | /set_group_add_request | [处理加群请求/邀请](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%E9%82%80%E8%AF%B7) |
| /set_group_card | [设置群名片(群备注)](https://cqhttp.cc/docs/4.15/#/API?id=set_group_card-设置群名片(群备注)) | | /set_group_card | [设置群名片(群备注)](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_card-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%90%8D%E7%89%87%E7%BE%A4%E5%A4%87%E6%B3%A8) |
| /set_group_special_title | [设置群组专属头衔](https://cqhttp.cc/docs/4.15/#/API?id=set_group_special_title-设置群组专属头衔) | | /set_group_special_title | [设置群组专属头衔](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94) |
| /set_group_kick | [群组T人](https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-群组踢人) | | /set_group_kick | [群组T人](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA) |
| /set_group_ban | [群组单人禁言](https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-群组单人禁言) | | /set_group_ban | [群组单人禁言](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80) |
| /set_group_whole_ban | [群组全员禁言](https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-群组全员禁言) | | /set_group_whole_ban | [群组全员禁言](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80) |
| /set_group_leave | [退出群组](https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-退出群组) | | /set_group_leave | [退出群组](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84) |
| /set_group_name | 设置群组名(拓展API) | | /set_group_name | [设置群组名](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_name-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%90%8D) |
| /get_image | 获取图片信息(拓展API) | | /set_restart | [重启go-cqhttp](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_restart-%E9%87%8D%E5%90%AF-onebot-%E5%AE%9E%E7%8E%B0) |
| /get_msg | [获取消息]() | <!-- TODO 来人补个链接--> | /get_image | [获取图片信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_image-%E8%8E%B7%E5%8F%96%E5%9B%BE%E7%89%87) |
| /can_send_image | [检查是否可以发送图片](https://cqhttp.cc/docs/4.15/#/API?id=can_send_image-检查是否可以发送图片) | | /get_msg | [获取消息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_msg-%E8%8E%B7%E5%8F%96%E6%B6%88%E6%81%AF) |
| /can_send_record | [检查是否可以发送语音](https://cqhttp.cc/docs/4.15/#/API?id=can_send_record-检查是否可以发送语音) | | /can_send_image | [检查是否可以发送图片](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#can_send_image-%E6%A3%80%E6%9F%A5%E6%98%AF%E5%90%A6%E5%8F%AF%E4%BB%A5%E5%8F%91%E9%80%81%E5%9B%BE%E7%89%87) |
| /get_status | [获取插件运行状态](https://cqhttp.cc/docs/4.15/#/API?id=get_status-获取插件运行状态) | | /can_send_record | [检查是否可以发送语音](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#can_send_record-%E6%A3%80%E6%9F%A5%E6%98%AF%E5%90%A6%E5%8F%AF%E4%BB%A5%E5%8F%91%E9%80%81%E8%AF%AD%E9%9F%B3) |
| /get_version_info | [获取 酷Q 及 CQHTTP插件的版本信息](https://cqhttp.cc/docs/4.15/#/API?id=get_version_info-获取-酷q-及-cqhttp-插件的版本信息) | | /get_status | [获取插件运行状态](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_status-%E8%8E%B7%E5%8F%96%E8%BF%90%E8%A1%8C%E7%8A%B6%E6%80%81) |
| /get_version_info | [获取 酷Q 及 CQHTTP插件的版本信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_version_info-%E8%8E%B7%E5%8F%96%E7%89%88%E6%9C%AC%E4%BF%A1%E6%81%AF) |
</details> </details>
@ -81,19 +82,19 @@
##### 注意: 部分Event数据与CQHTTP原版略有差异请参考文档 ##### 注意: 部分Event数据与CQHTTP原版略有差异请参考文档
| Event | | Event |
| ------------------------------------------------------------ | | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| [私聊信息](https://cqhttp.cc/docs/4.15/#/Post?id=私聊消息) | | [私聊信息](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/message.md#%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF) |
| [群消息](https://cqhttp.cc/docs/4.15/#/Post?id=群消息) | | [群消息](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/message.md#%E7%BE%A4%E6%B6%88%E6%81%AF) |
| [群消息撤回(拓展Event)](docs/cqhttp.md#群消息撤回) | | [群消息撤回(拓展Event)](docs/cqhttp.md#群消息撤回) |
| [好友消息撤回(拓展Event)](docs/cqhttp.md#好友消息撤回) | | [好友消息撤回(拓展Event)](docs/cqhttp.md#好友消息撤回) |
| [群内提示事件(拓展Event)(龙王等事件)](docs/cqhttp.md#群内戳一戳) | | [群内提示事件(拓展Event)(龙王等事件)](docs/cqhttp.md#群内戳一戳) |
| [群管理员变动](https://cqhttp.cc/docs/4.15/#/Post?id=群管理员变动) | | [群管理员变动](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E7%AE%A1%E7%90%86%E5%91%98%E5%8F%98%E5%8A%A8) |
| [群成员减少](https://cqhttp.cc/docs/4.15/#/Post?id=群成员减少) | | [群成员减少](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E6%88%90%E5%91%98%E5%87%8F%E5%B0%91) |
| [群成员增加](https://cqhttp.cc/docs/4.15/#/Post?id=群成员增加) | | [群成员增加](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E6%88%90%E5%91%98%E5%A2%9E%E5%8A%A0) |
| [群禁言](https://cqhttp.cc/docs/4.15/#/Post?id=群禁言) | | [群禁言](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E7%A6%81%E8%A8%80) |
| [群文件上传](https://cqhttp.cc/docs/4.15/#/Post?id=群文件上传) | | [群文件上传](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0) |
| [加好友请求](https://cqhttp.cc/docs/4.15/#/Post?id=加好友请求) | | [加好友请求](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/request.md#%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82) |
| [加群请求/邀请](https://cqhttp.cc/docs/4.15/#/Post?id=加群请求/邀请) | | [加群请求/邀请](https://github.com/howmanybots/onebot/blob/master/v11/specs/event/request.md#%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%E9%82%80%E8%AF%B7) |
</details> </details>

View File

@ -382,10 +382,10 @@ func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG {
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA // https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA
func (bot *CQBot) CQSetGroupKick(groupId, userId int64, msg string) MSG { func (bot *CQBot) CQSetGroupKick(groupId, userId int64, msg string, block bool) MSG {
if g := bot.Client.FindGroup(groupId); g != nil { if g := bot.Client.FindGroup(groupId); g != nil {
if m := g.FindMember(userId); m != nil { if m := g.FindMember(userId); m != nil {
m.Kick(msg) m.Kick(msg, block)
return OK(nil) return OK(nil)
} }
} }
@ -516,12 +516,11 @@ func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG {
} }
func (bot *CQBot) CQGetVipInfo(userId int64) MSG { func (bot *CQBot) CQGetVipInfo(userId int64) MSG {
msg := MSG{}
vip, err := bot.Client.GetVipInfo(userId) vip, err := bot.Client.GetVipInfo(userId)
if err != nil { if err != nil {
return Failed(100) return Failed(100)
} }
msg = MSG{ msg := MSG{
"user_id": vip.Uin, "user_id": vip.Uin,
"nickname": vip.Name, "nickname": vip.Name,
"level": vip.Level, "level": vip.Level,
@ -640,7 +639,7 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
bot.CQDeleteMessage(int32(context.Get("message_id").Int())) bot.CQDeleteMessage(int32(context.Get("message_id").Int()))
} }
if operation.Get("kick").Bool() && !isAnonymous { if operation.Get("kick").Bool() && !isAnonymous {
bot.CQSetGroupKick(context.Get("group_id").Int(), context.Get("user_id").Int(), "") bot.CQSetGroupKick(context.Get("group_id").Int(), context.Get("user_id").Int(), "", operation.Get("reject_add_request").Bool())
} }
if operation.Get("ban").Bool() { if operation.Get("ban").Bool() {
var duration uint32 = 30 * 60 var duration uint32 = 30 * 60
@ -790,6 +789,7 @@ func (bot *CQBot) CQGetStatus() MSG {
"app_good": true, "app_good": true,
"online": bot.Client.Online, "online": bot.Client.Online,
"good": true, "good": true,
"stat": bot.Client.GetStatistics(),
}) })
} }

View File

@ -3,23 +3,26 @@ package coolq
import ( import (
"bytes" "bytes"
"encoding/gob" "encoding/gob"
"encoding/json"
"fmt" "fmt"
"github.com/syndtr/goleveldb/leveldb"
"hash/crc32" "hash/crc32"
"path" "path"
"sync" "sync"
"time" "time"
"github.com/syndtr/goleveldb/leveldb"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
jsoniter "github.com/json-iterator/go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type CQBot struct { type CQBot struct {
Client *client.QQClient Client *client.QQClient
@ -56,6 +59,7 @@ func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot {
bot.Client.OnGroupMuted(bot.groupMutedEvent) bot.Client.OnGroupMuted(bot.groupMutedEvent)
bot.Client.OnGroupMessageRecalled(bot.groupRecallEvent) bot.Client.OnGroupMessageRecalled(bot.groupRecallEvent)
bot.Client.OnGroupNotify(bot.groupNotifyEvent) bot.Client.OnGroupNotify(bot.groupNotifyEvent)
bot.Client.OnFriendNotify(bot.friendNotifyEvent)
bot.Client.OnFriendMessageRecalled(bot.friendRecallEvent) bot.Client.OnFriendMessageRecalled(bot.friendRecallEvent)
bot.Client.OnReceivedOfflineFile(bot.offlineFileEvent) bot.Client.OnReceivedOfflineFile(bot.offlineFileEvent)
bot.Client.OnJoinGroup(bot.joinGroupEvent) bot.Client.OnJoinGroup(bot.joinGroupEvent)
@ -235,6 +239,10 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
newElem = append(newElem, fm) newElem = append(newElem, fm)
continue continue
} }
if i, ok := elem.(*PokeElement); ok {
bot.Client.SendFriendPoke(i.Target)
return 0
}
if i, ok := elem.(*message.VoiceElement); ok { if i, ok := elem.(*message.VoiceElement); ok {
fv, err := bot.Client.UploadPrivatePtt(target, i.Data) fv, err := bot.Client.UploadPrivatePtt(target, i.Data)
if err != nil { if err != nil {

View File

@ -8,11 +8,6 @@ import (
xml2 "encoding/xml" xml2 "encoding/xml"
"errors" "errors"
"fmt" "fmt"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"io/ioutil" "io/ioutil"
"net/url" "net/url"
"path" "path"
@ -20,6 +15,12 @@ import (
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`) var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`)
@ -65,7 +66,7 @@ func (e *MusicElement) Type() message.ElementType {
return message.Service return message.Service
} }
var GiftId = []message.GroupGift{ var GiftId = [...]message.GroupGift{
message.SweetWink, message.SweetWink,
message.HappyCola, message.HappyCola,
message.LuckyBracelet, message.LuckyBracelet,
@ -75,6 +76,11 @@ var GiftId = []message.GroupGift{
message.RainbowCandy, message.RainbowCandy,
message.Stronger, message.Stronger,
message.LoveMicrophone, message.LoveMicrophone,
message.HoldingYourHand,
message.CuteCat,
message.MysteryMask,
message.ImBusy,
message.LoveMask,
} }
func (e *PokeElement) Type() message.ElementType { func (e *PokeElement) Type() message.ElementType {
@ -177,6 +183,16 @@ func ToArrayMessage(e []message.IMessageElement, code int64, raw ...bool) (r []M
"data": map[string]string{"file": o.Filename, "url": o.Url}, "data": map[string]string{"file": o.Filename, "url": o.Url},
} }
} }
case *message.GroupFlashImgElement:
return []MSG{{
"type": "image",
"data": map[string]string{"file": o.Filename, "type": "flash"},
}}
case *message.FriendFlashImgElement:
return []MSG{{
"type": "image",
"data": map[string]string{"file": o.Filename, "type": "flash"},
}}
case *message.ServiceElement: case *message.ServiceElement:
if isOk := strings.Contains(o.Content, "<?xml"); isOk { if isOk := strings.Contains(o.Content, "<?xml"); isOk {
m = MSG{ m = MSG{
@ -249,6 +265,10 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image") r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image")
case *message.FriendImageElement: case *message.FriendImageElement:
r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image") r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image")
case *message.GroupFlashImgElement:
return fmt.Sprintf("[CQ:image,type=flash,file=%s]", o.Filename)
case *message.FriendFlashImgElement:
return fmt.Sprintf("[CQ:image,type=flash,file=%s]", o.Filename)
case *message.ServiceElement: case *message.ServiceElement:
if isOk := strings.Contains(o.Content, "<?xml"); isOk { if isOk := strings.Contains(o.Content, "<?xml"); isOk {
r += fmt.Sprintf(`[CQ:xml,data=%s,resid=%d]`, CQCodeEscapeValue(o.Content), o.Id) r += fmt.Sprintf(`[CQ:xml,data=%s,resid=%d]`, CQCodeEscapeValue(o.Content), o.Id)
@ -429,9 +449,6 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
} }
case "poke": case "poke":
if !group {
return nil, errors.New("todo") // TODO: private poke
}
t, _ := strconv.ParseInt(d["qq"], 10, 64) t, _ := strconv.ParseInt(d["qq"], 10, 64)
return &PokeElement{Target: t}, nil return &PokeElement{Target: t}, nil
case "gift": case "gift":
@ -440,7 +457,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
} }
t, _ := strconv.ParseInt(d["qq"], 10, 64) t, _ := strconv.ParseInt(d["qq"], 10, 64)
id, _ := strconv.Atoi(d["id"]) id, _ := strconv.Atoi(d["id"])
if id < 0 || id >= 9 { if id < 0 || id >= 14 {
return nil, errors.New("invalid gift id") return nil, errors.New("invalid gift id")
} }
return &GiftElement{Target: t, GiftId: GiftId[id]}, nil return &GiftElement{Target: t, GiftId: GiftId[id]}, nil

View File

@ -2,16 +2,17 @@ package coolq
import ( import (
"encoding/hex" "encoding/hex"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"io/ioutil" "io/ioutil"
"path" "path"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
) )
var format = "string" var format = "string"
@ -220,7 +221,7 @@ func (bot *CQBot) groupRecallEvent(c *client.QQClient, e *client.GroupMessageRec
}) })
} }
func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.IGroupNotifyEvent) { func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
group := c.FindGroup(e.From()) group := c.FindGroup(e.From())
switch notify := e.(type) { switch notify := e.(type) {
case *client.GroupPokeNotifyEvent: case *client.GroupPokeNotifyEvent:
@ -279,6 +280,24 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.IGroupNotifyEven
} }
} }
func (bot *CQBot) friendNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
friend := c.FindFriend(e.From())
switch notify := e.(type) {
case *client.FriendPokeNotifyEvent:
log.Infof("好友 %v 戳了戳你.", friend.Nickname)
bot.dispatchEventMessage(MSG{
"post_type": "notice",
"notice_type": "notify",
"sub_type": "poke",
"self_id": c.Uin,
"user_id": notify.Sender,
"sender_id": notify.Sender,
"target_id": notify.Receiver,
"time": time.Now().Unix(),
})
}
}
func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageRecalledEvent) { func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageRecalledEvent) {
f := c.FindFriend(e.FriendUin) f := c.FindFriend(e.FriendUin)
gid := ToGlobalId(e.FriendUin, e.MessageId) gid := ToGlobalId(e.FriendUin, e.MessageId)
@ -509,6 +528,28 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteString(i.Url) w.WriteString(i.Url)
}), 0644) }), 0644)
} }
case *message.GroupFlashImgElement:
filename := hex.EncodeToString(i.Md5) + ".image"
if !global.PathExists(path.Join(global.IMAGE_PATH, filename)) {
_ = ioutil.WriteFile(path.Join(global.IMAGE_PATH, filename), binary.NewWriterF(func(w *binary.Writer) {
w.Write(i.Md5)
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.Filename)
w.WriteString("")
}), 0644)
}
i.Filename = filename
case *message.FriendFlashImgElement:
filename := hex.EncodeToString(i.Md5) + ".image"
if !global.PathExists(path.Join(global.IMAGE_PATH, filename)) {
_ = ioutil.WriteFile(path.Join(global.IMAGE_PATH, filename), binary.NewWriterF(func(w *binary.Writer) {
w.Write(i.Md5)
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.Filename)
w.WriteString("")
}), 0644)
}
i.Filename = filename
case *message.VoiceElement: case *message.VoiceElement:
i.Name = strings.ReplaceAll(i.Name, "{", "") i.Name = strings.ReplaceAll(i.Name, "{", "")
i.Name = strings.ReplaceAll(i.Name, "}", "") i.Name = strings.ReplaceAll(i.Name, "}", "")

View File

@ -111,7 +111,7 @@
下面列出所有运算符(「要求的参数类型」是指运算符的键所对应的值的类型,「可作用于的类型」是指在过滤时事件对象相应值的类型): 下面列出所有运算符(「要求的参数类型」是指运算符的键所对应的值的类型,「可作用于的类型」是指在过滤时事件对象相应值的类型):
| 运算符 | 要求的参数类型 | 可作用于的类型 | | 运算符 | 要求的参数类型 | 可作用于的类型 |
| ----- | ------------ | ----------- | | ----------- | -------------------------- | ----------------------------------------------------- |
| `.not` | object | 任何 | | `.not` | object | 任何 |
| `.and` | object | 若参数中全为运算符,则任何;若不全为运算符,则 object | | `.and` | object | 若参数中全为运算符,则任何;若不全为运算符,则 object |
| `.or` | array数组元素为 object | 任何 | | `.or` | array数组元素为 object | 任何 |

View File

@ -7,8 +7,8 @@
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | ------------ | ------ | --------------------------- |
| access_token | string | 校验口令config.json中配置 | | access_token | string | 校验口令config.hjson中配置 |
@ -25,7 +25,7 @@ method`POST/GET`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ---- | ------------------------------------- | | ------ | ---- | ---- |
| 无 | | | | 无 | | |
返回: 返回:
@ -45,7 +45,7 @@ method: `GET`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | ------ | ---- | ---- |
| 无 | | | | 无 | | |
返回: 返回:
@ -54,7 +54,7 @@ method: `GET`
{"data": {"ispic": true,"picbase64":"xxxxx"}, "retcode": 0, "status": "ok"} {"data": {"ispic": true,"picbase64":"xxxxx"}, "retcode": 0, "status": "ok"}
``` ```
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | -------- | ------ | --------------------------------------------------- |
| ispic | bool | 是否是验证码类型 true是false为不是比如设备锁 | | ispic | bool | 是否是验证码类型 true是false为不是比如设备锁 |
| picbas64 | string | 验证码的base64编码内容加上头放入img标签即可显示 | | picbas64 | string | 验证码的base64编码内容加上头放入img标签即可显示 |
@ -68,8 +68,8 @@ method: `POST` formdata
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | ------ | ------ | ---------- |
| input | string | 输入的容 | | input | string | 输入的容 |
返回: 返回:
@ -90,7 +90,26 @@ method: `POST`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | -----------| | ------ | ---- | ---- |
| 无 | | |
返回:
```json
{"data": {}, "retcode": 0, "status": "ok"}
```
### admin/do_process_restart
> 冷重启
method: `POST`
参数:
| 参数名 | 类型 | 说明 |
| ------ | ---- | ---- |
| 无 | | | | 无 | | |
返回: 返回:
@ -109,7 +128,7 @@ method: `POST` formdata
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------------ | ------ | ------------------------------------- |
| uin | string | qq号 | | uin | string | qq号 |
| password | string | qq密码 | | password | string | qq密码 |
| enable_db | string | 是否启动数据库,填 'true' 或者 'false' | | enable_db | string | 是否启动数据库,填 'true' 或者 'false' |
@ -131,7 +150,7 @@ method: `POST` formdata
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ----------- | ------ | --------------------------------------------- |
| port | string | 服务端口 | | port | string | 服务端口 |
| host | string | 服务监听地址 | | host | string | 服务监听地址 |
| enable | string | 是否启用 ,填 'true' 或者 'false' | | enable | string | 是否启用 ,填 'true' 或者 'false' |
@ -155,7 +174,7 @@ method: `POST` formdata
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | -------------------------------- |
| port | string | 服务端口 | | port | string | 服务端口 |
| host | string | 服务监听地址 | | host | string | 服务监听地址 |
| enable | string | 是否启用 ,填 'true' 或者 'false' | | enable | string | 是否启用 ,填 'true' 或者 'false' |
@ -176,7 +195,7 @@ method: `POST` formdata
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | -------------------------------- |
| port | string | 服务端口 | | port | string | 服务端口 |
| host | string | 服务监听地址 | | host | string | 服务监听地址 |
| enable | string | 是否启用 ,填 'true' 或者 'false' | | enable | string | 是否启用 ,填 'true' 或者 'false' |
@ -190,15 +209,15 @@ method: `POST` formdata
### admin/do_config_json ### admin/do_config_json
> 直接修改 config.json配置 > 直接修改 config.hjson配置
method: `POST` formdata method: `POST` formdata
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | ----------------------------------- |
| json | string | 完整的config.json的配合json字符串 | | json | string | 完整的config.hjson的配合json字符串 |
返回: 返回:
@ -209,14 +228,14 @@ method: `POST` formdata
### admin/get_config_json ### admin/get_config_json
> 获取当前 config.json配置 > 获取当前 config.hjson配置
method: `GET` method: `GET`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ---- | ---- |
| 无 | | | | 无 | | |
@ -227,6 +246,6 @@ method: `GET`
``` ```
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | ----------------------------------- |
| config | string | 完整的config.json的配合json字符串 | | config | string | 完整的config.hjson的配合json字符串 |

View File

@ -1,6 +1,6 @@
# 配置 # 配置
go-cqhttp 包含 `config.json``device.json` 两个配置文件, 其中 `config.json` 为运行配置 `device.json` 为虚拟设备信息. go-cqhttp 包含 `config.hjson``device.json` 两个配置文件, 其中 `config.json` 为运行配置 `device.json` 为虚拟设备信息.
## 从原CQHTTP导入配置 ## 从原CQHTTP导入配置
@ -62,7 +62,7 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
```` ````
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------------ | -------- | ------------------------------------------------------------------- | | --------------------- | -------- | ---------------------------------------------------------------------------------------- |
| uin | int64 | 登录用QQ号 | | uin | int64 | 登录用QQ号 |
| password | string | 登录用密码 | | password | string | 登录用密码 |
| encrypt_password | bool | 是否对密码进行加密. | | encrypt_password | bool | 是否对密码进行加密. |
@ -111,10 +111,11 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
在大部分情况下 我们只需要关心 `protocol` 字段: 在大部分情况下 我们只需要关心 `protocol` 字段:
| 值 | 类型 | 限制 | | 值 | 类型 | 限制 |
| ---- | ------------- | ----------------------------------------------------- | | --- | ------------- | ---------------------------------------------------------------- |
| 0 | iPad | 无 | | 0 | iPad | 无 |
| 1 | Android Phone | 无 | | 1 | Android Phone | 无法接收新版表情如 `/吃瓜 /汪汪`, 会自动转换为字符串 |
| 2 | Android Watch | 无法接收 `group_notify` 事件、无法接收口令红包、无法接收撤回消息 | | 2 | Android Watch | 除`Android Phone`的限制外, 无法接收 `notify` 事件、无法接收口令红包、无法接收撤回消息 |
| 3 | MacOS | 无 |
> 注意, 根据协议的不同, 各类消息有所限制 > 注意, 根据协议的不同, 各类消息有所限制

View File

@ -7,7 +7,7 @@
### 图片 ### 图片
| 参数名 | 可能的值 | 说明 | | 参数名 | 可能的值 | 说明 |
| --- | --- | --- | | ------- | --------------- | --------------------------------------------------------------- |
| `file` | - | 图片文件名 | | `file` | - | 图片文件名 |
| `type` | `flash``show` | 图片类型,`flash` 表示闪照,`show` 表示秀图,默认普通图片 | | `type` | `flash``show` | 图片类型,`flash` 表示闪照,`show` 表示秀图,默认普通图片 |
| `url` | - | 图片 URL | | `url` | - | 图片 URL |
@ -17,7 +17,7 @@
可用的特效ID: 可用的特效ID:
| id | 类型 | | id | 类型 |
| --- |-------| | ----- | ---- |
| 40000 | 普通 | | 40000 | 普通 |
| 40001 | 幻影 | | 40001 | 幻影 |
| 40002 | 抖动 | | 40002 | 抖动 |
@ -65,7 +65,7 @@ Type: `poke`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | ------ | ----- | ------------ |
| qq | int64 | 需要戳的成员 | | qq | int64 | 需要戳的成员 |
示例: `[CQ:poke,qq=123456]` 示例: `[CQ:poke,qq=123456]`
@ -81,14 +81,14 @@ Type: `gift`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | -----------| | ------ | ----- | -------------- |
| qq | int64 | 接收礼物的成员 | | qq | int64 | 接收礼物的成员 |
| id | int | 礼物的类型 | | id | int | 礼物的类型 |
目前支持的礼物ID: 目前支持的礼物ID:
| id | 类型 | | id | 类型 |
| ---| ---------| | --- | ---------- |
| 0 | 甜Wink | | 0 | 甜Wink |
| 1 | 快乐肥宅水 | | 1 | 快乐肥宅水 |
| 2 | 幸运手链 | | 2 | 幸运手链 |
@ -98,6 +98,12 @@ Type: `gift`
| 6 | 彩虹糖果 | | 6 | 彩虹糖果 |
| 7 | 坚强 | | 7 | 坚强 |
| 8 | 告白话筒 | | 8 | 告白话筒 |
| 9 | 牵你的手 |
| 10 | 可爱猫咪 |
| 11 | 神秘面具 |
| 12 | 我超忙的 |
| 13 | 爱心口罩 |
示例: `[CQ:gift,qq=123456,id=8]` 示例: `[CQ:gift,qq=123456,id=8]`
@ -111,7 +117,7 @@ Type: `forward`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | ------------------------------------------------------------- |
| id | string | 合并转发ID, 需要通过 `/get_forward_msg` API获取转发的具体内容 | | id | string | 合并转发ID, 需要通过 `/get_forward_msg` API获取转发的具体内容 |
示例: `[CQ:forward,id=xxxx]` 示例: `[CQ:forward,id=xxxx]`
@ -125,7 +131,7 @@ Type: `node`
参数: 参数:
| 参数名 | 类型 | 说明 | 特殊说明 | | 参数名 | 类型 | 说明 | 特殊说明 |
| ------- | ------- | -------------- | ------------------------------------------------------------ | | ------- | ------- | -------------- | -------------------------------------------------------------------------------------- |
| id | int32 | 转发消息id | 直接引用他人的消息合并转发, 实际查看顺序为原消息发送顺序 **与下面的自定义消息二选一** | | id | int32 | 转发消息id | 直接引用他人的消息合并转发, 实际查看顺序为原消息发送顺序 **与下面的自定义消息二选一** |
| name | string | 发送者显示名字 | 用于自定义消息 (自定义消息并合并转发,实际查看顺序为自定义消息段顺序) | | name | string | 发送者显示名字 | 用于自定义消息 (自定义消息并合并转发,实际查看顺序为自定义消息段顺序) |
| uin | int64 | 发送者QQ号 | 用于自定义消息 | | uin | int64 | 发送者QQ号 | 用于自定义消息 |
@ -212,7 +218,7 @@ Type: `xml`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | ----------------------------------------- |
| data | string | xml内容xml中的value部分记得实体化处理 | | data | string | xml内容xml中的value部分记得实体化处理 |
| resid | int32 | 可以不填 | | resid | int32 | 可以不填 |
@ -261,7 +267,7 @@ Type: `json`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | ------ | ------ | ----------------------------------------------- |
| data | string | json内容json的所有字符串记得实体化处理 | | data | string | json内容json的所有字符串记得实体化处理 |
| resid | int32 | 默认不填为0走小程序通道填了走富文本通道发送 | | resid | int32 | 默认不填为0走小程序通道填了走富文本通道发送 |
@ -294,7 +300,7 @@ Type: `cardimage`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------ | | --------- | ------ | ------------------------------------- |
| file | string | 和image的file字段对齐支持也是一样的 | | file | string | 和image的file字段对齐支持也是一样的 |
| minwidth | int64 | 默认不填为400最小width | | minwidth | int64 | 默认不填为400最小width |
| minheight | int64 | 默认不填为400最小height | | minheight | int64 | 默认不填为400最小height |
@ -320,7 +326,7 @@ Type: `tts`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | ------ | ------ | ---- |
| text | string | 内容 | | text | string | 内容 |
示例: `[CQ:tts,text=这是一条测试消息]` 示例: `[CQ:tts,text=这是一条测试消息]`
@ -334,7 +340,7 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| -------- | ------ | ---- | | ---------- | ------ | ---- |
| group_id | int64 | 群号 | | group_id | int64 | 群号 |
| group_name | string | 新名 | | group_name | string | 新名 |
@ -345,7 +351,7 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| -------- | ------ | ---- | | -------- | ------ | ------------------------ |
| group_id | int64 | 群号 | | group_id | int64 | 群号 |
| file | string | 图片文件名 | | file | string | 图片文件名 |
| cache | int | 表示是否使用已缓存的文件 | | cache | int | 表示是否使用已缓存的文件 |
@ -463,13 +469,13 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------ | ------ | ------ | | --------- | ------ | ---- |
| `content` | string | 内容 | | `content` | string | 内容 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | -------- | -------- | ---- |
| `slices` | string[] | 词组 | | `slices` | string[] | 词组 |
### 图片OCR ### 图片OCR
@ -481,20 +487,20 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------ | ------ | ------ | | ------- | ------ | ------ |
| `image` | string | 图片ID | | `image` | string | 图片ID |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ---------- | --------------- | ------- |
| `texts` | TextDetection[] | OCR结果 | | `texts` | TextDetection[] | OCR结果 |
| `language` | string | 语言 | | `language` | string | 语言 |
**TextDetection** **TextDetection**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ------------- | ------- | ------ |
| `text` | string | 文本 | | `text` | string | 文本 |
| `confidence` | int32 | 置信度 | | `confidence` | int32 | 置信度 |
| `coordinates` | vector2 | 坐标 | | `coordinates` | vector2 | 坐标 |
@ -507,7 +513,7 @@ Type: `tts`
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ------------------ | ---------------- | ------------ |
| `invited_requests` | InvitedRequest[] | 邀请消息列表 | | `invited_requests` | InvitedRequest[] | 邀请消息列表 |
| `join_requests` | JoinRequest[] | 进群消息列表 | | `join_requests` | JoinRequest[] | 进群消息列表 |
@ -516,7 +522,7 @@ Type: `tts`
**InvitedRequest** **InvitedRequest**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | -------------- | ------ | ----------------- |
| `request_id` | int64 | 请求ID | | `request_id` | int64 | 请求ID |
| `invitor_uin` | int64 | 邀请者 | | `invitor_uin` | int64 | 邀请者 |
| `invitor_nick` | string | 邀请者昵称 | | `invitor_nick` | string | 邀请者昵称 |
@ -528,7 +534,7 @@ Type: `tts`
**JoinRequest** **JoinRequest**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ---------------- | ------ | ----------------- |
| `request_id` | int64 | 请求ID | | `request_id` | int64 | 请求ID |
| `requester_uin` | int64 | 请求者ID | | `requester_uin` | int64 | 请求者ID |
| `requester_nick` | string | 请求者昵称 | | `requester_nick` | string | 请求者昵称 |
@ -545,13 +551,13 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------ | ------ | ------ | | ---------- | ----- | ---- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ------------- | ----- | ---------- |
| `file_count` | int32 | 文件总数 | | `file_count` | int32 | 文件总数 |
| `limit_count` | int32 | 文件上限 | | `limit_count` | int32 | 文件上限 |
| `used_space` | int64 | 已使用空间 | | `used_space` | int64 | 已使用空间 |
@ -566,13 +572,13 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------ | ------ | ------ | | ---------- | ----- | ---- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | --------- | -------- | ---------- |
| `files` | File[] | 文件列表 | | `files` | File[] | 文件列表 |
| `folders` | Folder[] | 文件夹列表 | | `folders` | Folder[] | 文件夹列表 |
@ -585,14 +591,14 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------ | ------ | ------ | | ----------- | ------ | --------------------------- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
| `folder_id` | string | 文件夹ID 参考 `Folder` 对象 | | `folder_id` | string | 文件夹ID 参考 `Folder` 对象 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | --------- | -------- | ---------- |
| `files` | File[] | 文件列表 | | `files` | File[] | 文件列表 |
| `folders` | Folder[] | 文件夹列表 | | `folders` | Folder[] | 文件夹列表 |
@ -605,7 +611,7 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------ | ------ | ------ | | ---------- | ------ | ------------------------- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
| `file_id` | string | 文件ID 参考 `File` 对象 | | `file_id` | string | 文件ID 参考 `File` 对象 |
| `busid` | int32 | 文件类型 参考 `File` 对象 | | `busid` | int32 | 文件类型 参考 `File` 对象 |
@ -613,13 +619,13 @@ Type: `tts`
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ----- | ------ | ------------ |
| `url` | string | 文件下载链接 | | `url` | string | 文件下载链接 |
**File** **File**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ---------------- | ------ | ---------------------- |
| `file_id` | string | 文件ID | | `file_id` | string | 文件ID |
| `file_name` | string | 文件名 | | `file_name` | string | 文件名 |
| `busid` | int32 | 文件类型 | | `busid` | int32 | 文件类型 |
@ -634,7 +640,7 @@ Type: `tts`
**Folder** **Folder**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----------------- | -------- | | ------------------ | ------ | ---------- |
| `folder_id` | string | 文件夹ID | | `folder_id` | string | 文件夹ID |
| `folder_name` | string | 文件名 | | `folder_name` | string | 文件名 |
| `create_time` | int64 | 创建时间 | | `create_time` | int64 | 创建时间 |
@ -662,7 +668,7 @@ Type: `tts`
**上报数据** **上报数据**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------------- | ------ | --------------- | -------------- |
| `post_type` | string | `notice` | 上报类型 | | `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `friend_recall` | 消息类型 | | `notice_type` | string | `friend_recall` | 消息类型 |
| `user_id` | int64 | | 好友id | | `user_id` | int64 | | 好友id |
@ -675,7 +681,7 @@ Type: `tts`
**上报数据** **上报数据**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------------- | ------ | -------- | -------- |
| `post_type` | string | `notice` | 上报类型 | | `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `notify` | 消息类型 | | `notice_type` | string | `notify` | 消息类型 |
| `group_id` | int64 | | 群号 | | `group_id` | int64 | | 群号 |
@ -690,7 +696,7 @@ Type: `tts`
**上报数据** **上报数据**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------------- | ------ | ------------ | ------------ |
| `post_type` | string | `notice` | 上报类型 | | `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `notify` | 消息类型 | | `notice_type` | string | `notify` | 消息类型 |
| `group_id` | int64 | | 群号 | | `group_id` | int64 | | 群号 |
@ -705,7 +711,7 @@ Type: `tts`
**上报数据** **上报数据**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------------- | ------ | -------------------------------------------------------- | -------- |
| `post_type` | string | `notice` | 上报类型 | | `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `notify` | 消息类型 | | `notice_type` | string | `notify` | 消息类型 |
| `group_id` | int64 | | 群号 | | `group_id` | int64 | | 群号 |
@ -720,7 +726,7 @@ Type: `tts`
**上报数据** **上报数据**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------------- | ------ | ------------ | -------- |
| `post_type` | string | `notice` | 上报类型 | | `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `group_card` | 消息类型 | | `notice_type` | string | `group_card` | 消息类型 |
| `group_id` | int64 | | 群号 | | `group_id` | int64 | | 群号 |
@ -735,7 +741,7 @@ Type: `tts`
**上报数据** **上报数据**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------------- | ------ | -------------- | -------- |
| `post_type` | string | `notice` | 上报类型 | | `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `offline_file` | 消息类型 | | `notice_type` | string | `offline_file` | 消息类型 |
| `user_id` | int64 | | 发送者id | | `user_id` | int64 | | 发送者id |
@ -744,7 +750,7 @@ Type: `tts`
**file object** **file object**
| 字段 | 类型 | 可能的值 | 说明 | | 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- | | ------ | ------ | -------- | -------- |
| `name` | string | | 文件名 | | `name` | string | | 文件名 |
| `size` | int64 | | 文件大小 | | `size` | int64 | | 文件大小 |
| `url` | string | | 下载链接 | | `url` | string | | 下载链接 |

View File

@ -5,7 +5,7 @@ go-cqhttp 默认生成的文件树如下所示:
```` ````
. .
├── go-cqhttp ├── go-cqhttp
├── config.json ├── config.hjson
├── device.json ├── device.json
├── logs ├── logs
│ └── xx-xx-xx.log │ └── xx-xx-xx.log
@ -18,7 +18,7 @@ go-cqhttp 默认生成的文件树如下所示:
| 文件 | 用途 | | 文件 | 用途 |
| ----------- | ------------------- | | ----------- | ------------------- |
| go-cqhttp | go-cqhttp可执行文件 | | go-cqhttp | go-cqhttp可执行文件 |
| config.json | 运行配置文件 | | config.hjson | 运行配置文件 |
| device.json | 虚拟设备配置文件 | | device.json | 虚拟设备配置文件 |
| logs | 日志存放目录 | | logs | 日志存放目录 |
| data | 数据目录 | | data | 数据目录 |

View File

@ -28,8 +28,8 @@
1. 双击`go-cqhttp.exe`此时将提示 1. 双击`go-cqhttp.exe`此时将提示
``` ```
[WARNING]: 尝试加载配置文件 config.json 失败: 文件不存在 [WARNING]: 尝试加载配置文件 config.hjson 失败: 文件不存在
[INFO]: 默认配置文件已生成,请编辑 config.json 后重启程序. [INFO]: 默认配置文件已生成,请编辑 config.hjson 后重启程序.
``` ```
2. 参照[config.md](https://github.com/Mrs4s/go-cqhttp/blob/master/docs/config.md)和你所用到的插件的 `README` 填入参数 2. 参照[config.md](https://github.com/Mrs4s/go-cqhttp/blob/master/docs/config.md)和你所用到的插件的 `README` 填入参数
3. 再次双击`go-cqhttp.exe` 3. 再次双击`go-cqhttp.exe`
@ -79,8 +79,8 @@ enable ws?(Y/n)
2. `cd`到解压目录 2. `cd`到解压目录
3. 输入 `./go-cqhttp``Enter`运行 ,此时将提示 3. 输入 `./go-cqhttp``Enter`运行 ,此时将提示
``` ```
[WARNING]: 尝试加载配置文件 config.json 失败: 文件不存在 [WARNING]: 尝试加载配置文件 config.hjson 失败: 文件不存在
[INFO]: 默认配置文件已生成,请编辑 config.json 后重启程序. [INFO]: 默认配置文件已生成,请编辑 config.hjson 后重启程序.
``` ```
4. 参照[config.md](https://github.com/Mrs4s/go-cqhttp/blob/master/docs/config.md)和你所用到的插件的 `README` 填入参数 4. 参照[config.md](https://github.com/Mrs4s/go-cqhttp/blob/master/docs/config.md)和你所用到的插件的 `README` 填入参数
@ -103,6 +103,8 @@ enable ws?(Y/n)
如果出现`{"data":{"message_id":balabala},"retcode":0,"status":"ok"}`则证明已经成功配置HTTP 如果出现`{"data":{"message_id":balabala},"retcode":0,"status":"ok"}`则证明已经成功配置HTTP
*注:请 连 中括号 也替换掉,就像这样:*`http://127.0.0.1:5700/send_private_msg?user_id=10001&message=ffeecoishp`
# 进阶指南 # 进阶指南
## 如何自己构建 ## 如何自己构建
@ -117,7 +119,29 @@ enable ws?(Y/n)
*注:可以使用*`go env -w GOPROXY=https://goproxy.cn,direct`*来加速国内依赖安装速度* *注:可以使用*`go env -w GOPROXY=https://goproxy.cn,direct`*来加速国内依赖安装速度*
*注:此时构建后的文件名为*`main`(Linux)或`main.exe`(Windows) ## 更新
### 方法一
从[release](https://github.com/Mrs4s/go-cqhttp/releases)界面下载最新版本的go-cqhttp
并替换之前的版本
### 方法二
使用更新参数在命令行中打开go-cqhttp所在目录
#### windows
输入指令
`go-cqhttp.exe update`
如果在国内连接github下载速度可能很慢可以使用镜像源下载
`go-cqhttp.exe update https://github.rc1844.workers.dev`
几个可用的镜像源
- `https://hub.fastgit.org`
- `https://github.com.cnpmjs.org`
- `https://github.bajins.com`
- `https://github.rc1844.workers.dev`
#### linux
方法与windows基本一致`go-cqhttp.exe` 替换为 `./go-cqhttp`即可

View File

@ -4,11 +4,12 @@ import (
"crypto/md5" "crypto/md5"
"errors" "errors"
"fmt" "fmt"
log "github.com/sirupsen/logrus"
"github.com/wdvxdr1123/go-silk/silk"
"io/ioutil" "io/ioutil"
"path" "path"
"sync" "sync"
log "github.com/sirupsen/logrus"
"github.com/wdvxdr1123/go-silk/silk"
) )
var codec silk.Encoder var codec silk.Encoder

View File

@ -1,14 +1,138 @@
package global package global
import ( import (
"encoding/json"
"os" "os"
"strconv" "strconv"
"time" "time"
"github.com/hjson/hjson-go"
jsoniter "github.com/json-iterator/go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary
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
// 日志等级
log_level: ""
// WebUi 设置
web_ui: {
// 是否启用 WebUi
enabled: true
// 监听地址
host: 127.0.0.1
// 监听端口
web_ui_port: 9999
// 是否接收来自web的输入
web_input: false
}
}
`
type JsonConfig struct { type JsonConfig struct {
Uin int64 `json:"uin"` Uin int64 `json:"uin"`
Password string `json:"password"` Password string `json:"password"`
@ -144,22 +268,30 @@ func Load(p string) *JsonConfig {
log.Warnf("尝试加载配置文件 %v 失败: 文件不存在", p) log.Warnf("尝试加载配置文件 %v 失败: 文件不存在", p)
return nil return nil
} }
c := JsonConfig{} var dat map[string]interface{}
err := json.Unmarshal([]byte(ReadAllText(p)), &c) 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 { if err != nil {
log.Warnf("尝试加载配置文件 %v 时出现错误: %v", p, err) log.Warnf("尝试加载配置文件 %v 时出现错误: %v", p, err)
log.Infoln("原文件已备份") log.Infoln("原文件已备份")
os.Rename(p, p+".backup"+strconv.FormatInt(time.Now().Unix(), 10)) _ = os.Rename(p, p+".backup"+strconv.FormatInt(time.Now().Unix(), 10))
return nil return nil
} }
return &c return &c
} }
func (c *JsonConfig) Save(p string) error { func (c *JsonConfig) Save(p string) error {
data, err := json.MarshalIndent(c, "", "\t") data, err := hjson.MarshalWithOptions(c, hjson.EncoderOptions{
Eol: "\n",
BracesSameLine: true,
IndentBy: " ",
})
if err != nil { if err != nil {
return err return err
} }
WriteAllText(p, string(data)) return WriteAllText(p, string(data))
return nil
} }

View File

@ -1,11 +1,12 @@
package global package global
import ( import (
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"io/ioutil" "io/ioutil"
"regexp" "regexp"
"strings" "strings"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
type Filter interface { type Filter interface {

View File

@ -7,8 +7,6 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"github.com/dustin/go-humanize"
log "github.com/sirupsen/logrus"
"io/ioutil" "io/ioutil"
"net" "net"
"net/url" "net/url"
@ -17,6 +15,9 @@ import (
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"github.com/dustin/go-humanize"
log "github.com/sirupsen/logrus"
) )
var ( var (
@ -42,8 +43,8 @@ func ReadAllText(path string) string {
return string(b) return string(b)
} }
func WriteAllText(path, text string) { func WriteAllText(path, text string) error {
_ = ioutil.WriteFile(path, []byte(text), 0644) return ioutil.WriteFile(path, []byte(text), 0644)
} }
func Check(err error) { func Check(err error) {
@ -121,7 +122,7 @@ func ReadAddrFile(path string) []*net.TCPAddr {
lines := strings.Split(str, "\n") lines := strings.Split(str, "\n")
var ret []*net.TCPAddr var ret []*net.TCPAddr
for _, l := range lines { for _, l := range lines {
ip := strings.Split(l, ":") ip := strings.Split(strings.TrimSpace(l), ":")
if len(ip) == 2 { if len(ip) == 2 {
port, _ := strconv.Atoi(ip[1]) port, _ := strconv.Atoi(ip[1])
ret = append(ret, &net.TCPAddr{IP: net.ParseIP(ip[0]), Port: port}) ret = append(ret, &net.TCPAddr{IP: net.ParseIP(ip[0]), Port: port})

View File

@ -4,11 +4,12 @@ import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"fmt" "fmt"
"github.com/tidwall/gjson"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/tidwall/gjson"
) )
var client = &http.Client{ var client = &http.Client{

View File

@ -1,11 +1,12 @@
package global package global
import ( import (
"github.com/tidwall/gjson"
"math" "math"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/tidwall/gjson"
) )
var trueSet = map[string]struct{}{ var trueSet = map[string]struct{}{

View File

@ -2,6 +2,7 @@ package global
import ( import (
"context" "context"
"golang.org/x/time/rate" "golang.org/x/time/rate"
) )

6
go.mod
View File

@ -1,15 +1,17 @@
module github.com/Mrs4s/go-cqhttp module github.com/Mrs4s/go-cqhttp
go 1.14 go 1.15
require ( require (
github.com/Mrs4s/MiraiGo v0.0.0-20201113113825-c1739dba15c9 github.com/Mrs4s/MiraiGo v0.0.0-20201120153907-26b45139c16f
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/getlantern/go-update v0.0.0-20190510022740-79c495ab728c github.com/getlantern/go-update v0.0.0-20190510022740-79c495ab728c
github.com/getlantern/golog v0.0.0-20201105130739-9586b8bde3a9 // indirect github.com/getlantern/golog v0.0.0-20201105130739-9586b8bde3a9 // indirect
github.com/gin-gonic/gin v1.6.3 github.com/gin-gonic/gin v1.6.3
github.com/gorilla/websocket v1.4.2 github.com/gorilla/websocket v1.4.2
github.com/guonaihong/gout v0.1.3 github.com/guonaihong/gout v0.1.3
github.com/hjson/hjson-go v3.1.0+incompatible
github.com/json-iterator/go v1.1.10
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect
github.com/kr/binarydist v0.1.0 // indirect github.com/kr/binarydist v0.1.0 // indirect
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible

10
go.sum
View File

@ -1,7 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Mrs4s/MiraiGo v0.0.0-20201113113825-c1739dba15c9 h1:7mFBaoEz2HCIkUqfiW1EtpsZEhxfupEda8+EMeuNS+4= github.com/Mrs4s/MiraiGo v0.0.0-20201120153907-26b45139c16f h1:pjxBE1VvJpookM2iUySfiqmuNyMz52oOhcvSRwWldqw=
github.com/Mrs4s/MiraiGo v0.0.0-20201113113825-c1739dba15c9/go.mod h1:pAsWtMIwqkBXr5DkUpTIHoWQJNduVnX9WSBPmPvkuCs= github.com/Mrs4s/MiraiGo v0.0.0-20201120153907-26b45139c16f/go.mod h1:pAsWtMIwqkBXr5DkUpTIHoWQJNduVnX9WSBPmPvkuCs=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -67,9 +67,13 @@ github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0U
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/guonaihong/gout v0.1.3 h1:BIiV6nnsA+R6dIB1P33uhCM8+TVAG3zHrXGZad7hDc8= github.com/guonaihong/gout v0.1.3 h1:BIiV6nnsA+R6dIB1P33uhCM8+TVAG3zHrXGZad7hDc8=
github.com/guonaihong/gout v0.1.3/go.mod h1:vXvv5Kxr70eM5wrp4F0+t9lnLWmq+YPW2GByll2f/EA= github.com/guonaihong/gout v0.1.3/go.mod h1:vXvv5Kxr70eM5wrp4F0+t9lnLWmq+YPW2GByll2f/EA=
github.com/hjson/hjson-go v3.1.0+incompatible h1:DY/9yE8ey8Zv22bY+mHV1uk2yRy0h8tKhZ77hEdi0Aw=
github.com/hjson/hjson-go v3.1.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
@ -86,7 +90,9 @@ github.com/lestrrat-go/strftime v1.0.3/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR7
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=

125
main.go
View File

@ -4,33 +4,38 @@ import (
"bufio" "bufio"
"crypto/md5" "crypto/md5"
"encoding/base64" "encoding/base64"
"encoding/json"
"fmt" "fmt"
"github.com/Mrs4s/go-cqhttp/server"
"github.com/guonaihong/gout"
"github.com/tidwall/gjson"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os" "os"
"os/exec"
"os/signal" "os/signal"
"path" "path"
"path/filepath"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/go-cqhttp/server"
"github.com/guonaihong/gout"
"github.com/tidwall/gjson"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/getlantern/go-update" "github.com/getlantern/go-update"
"github.com/lestrrat-go/file-rotatelogs" jsoniter "github.com/json-iterator/go"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook" "github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/t-tomalak/logrus-easy-formatter" easy "github.com/t-tomalak/logrus-easy-formatter"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary
func init() { func init() {
log.SetFormatter(&easy.Formatter{ log.SetFormatter(&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05", TimestampFormat: "2006-01-02 15:04:05",
@ -62,7 +67,7 @@ func init() {
} }
if global.PathExists("cqhttp.json") { if global.PathExists("cqhttp.json") {
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.") log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.json 文件.") log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.hjson 文件.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
conf := global.CQHttpApiConfig{} conf := global.CQHttpApiConfig{}
if err := json.Unmarshal([]byte(global.ReadAllText("cqhttp.json")), &conf); err != nil { if err := json.Unmarshal([]byte(global.ReadAllText("cqhttp.json")), &conf); err != nil {
@ -84,8 +89,8 @@ func init() {
goConf.ReverseServers[0].ReverseEventUrl = conf.WSReverseEventUrl goConf.ReverseServers[0].ReverseEventUrl = conf.WSReverseEventUrl
goConf.ReverseServers[0].ReverseReconnectInterval = conf.WSReverseReconnectInterval goConf.ReverseServers[0].ReverseReconnectInterval = conf.WSReverseReconnectInterval
} }
if err := goConf.Save("config.json"); err != nil { if err := goConf.Save("config.hjson"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err) log.Fatalf("保存 config.hjson 时出现错误: %v", err)
} }
_ = os.Remove("cqhttp.json") _ = os.Remove("cqhttp.json")
} }
@ -93,19 +98,35 @@ func init() {
func main() { func main() {
console := bufio.NewReader(os.Stdin) console := bufio.NewReader(os.Stdin)
var strKey string
var isFastStart bool = false
arg := os.Args arg := os.Args
if len(arg) > 1 && arg[1] == "update" { if len(arg) > 1 {
if len(arg) > 2 { for i := range arg {
selfUpdate(arg[2]) switch arg[i] {
case "update":
if len(arg) > i+1 {
selfUpdate(arg[i+1])
} else { } else {
selfUpdate("") selfUpdate("")
} }
case "key":
if len(arg) > i+1 {
b := []byte(arg[i+1])
b = append(b, 13, 10)
strKey = string(b[:])
}
case "faststart":
isFastStart = true
}
}
} }
var conf *global.JsonConfig var conf *global.JsonConfig
if global.PathExists("config.json") || os.Getenv("UIN") == "" { if global.PathExists("config.json") {
conf = global.Load("config.json") conf = global.Load("config.json")
_ = conf.Save("config.hjson")
_ = os.Remove("config.json")
} else if os.Getenv("UIN") != "" { } else if os.Getenv("UIN") != "" {
log.Infof("将从环境变量加载配置.") log.Infof("将从环境变量加载配置.")
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64) uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
@ -131,19 +152,21 @@ func main() {
if post != "" { if post != "" {
conf.HttpConfig.PostUrls[post] = os.Getenv("HTTP_SECRET") conf.HttpConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
} }
} else {
conf = global.Load("config.hjson")
} }
if conf == nil { if conf == nil {
err := global.DefaultConfig().Save("config.json") err := global.WriteAllText("config.hjson", global.DefaultConfigWithComments)
if err != nil { if err != nil {
log.Fatalf("创建默认配置文件时出现错误: %v", err) log.Fatalf("创建默认配置文件时出现错误: %v", err)
return return
} }
log.Infof("默认配置文件已生成, 请编辑 config.json 后重启程序.") log.Infof("默认配置文件已生成, 请编辑 config.hjson 后重启程序.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
return return
} }
if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") { if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") {
log.Warnf("请修改 config.json 以添加账号密码.") log.Warnf("请修改 config.hjson 以添加账号密码.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
return return
} }
@ -210,19 +233,37 @@ func main() {
if encrypted := EncryptPwd(conf.Password, key[:]); encrypted != "" { if encrypted := EncryptPwd(conf.Password, key[:]); encrypted != "" {
conf.Password = "" conf.Password = ""
conf.PasswordEncrypted = encrypted conf.PasswordEncrypted = encrypted
_ = conf.Save("config.json") _ = conf.Save("config.hjson")
} else { } else {
log.Warnf("加密时出现问题.") log.Warnf("加密时出现问题.")
} }
} }
if conf.PasswordEncrypted != "" { if conf.PasswordEncrypted != "" {
if strKey == "" {
log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)") log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)")
strKey, _ := console.ReadString('\n') 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)
}
}()
strKey, _ = console.ReadString('\n')
cancel <- struct{}{}
} else {
log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.")
}
key := md5.Sum([]byte(strKey)) key := md5.Sum([]byte(strKey))
conf.Password = DecryptPwd(conf.PasswordEncrypted, key[:]) conf.Password = DecryptPwd(conf.PasswordEncrypted, key[:])
} }
if !isFastStart {
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.") log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
}
log.Info("开始尝试登录并同步消息...") log.Info("开始尝试登录并同步消息...")
log.Infof("使用协议: %v", func() string { log.Infof("使用协议: %v", func() string {
switch client.SystemDeviceInfo.Protocol { switch client.SystemDeviceInfo.Protocol {
@ -232,6 +273,8 @@ func main() {
return "Android Phone" return "Android Phone"
case client.AndroidWatch: case client.AndroidWatch:
return "Android Watch" return "Android Watch"
case client.MacOS:
return "MacOS"
} }
return "未知" return "未知"
}()) }())
@ -276,16 +319,19 @@ func main() {
if conf.WebUi.Host == "" { if conf.WebUi.Host == "" {
conf.WebUi.Host = "127.0.0.1" conf.WebUi.Host = "127.0.0.1"
} }
confErr := conf.Save("config.json")
if confErr != nil {
log.Error("保存配置文件失败")
}
b := server.WebServer.Run(fmt.Sprintf("%s:%d", conf.WebUi.Host, conf.WebUi.WebUiPort), cli) b := server.WebServer.Run(fmt.Sprintf("%s:%d", conf.WebUi.Host, conf.WebUi.WebUiPort), cli)
c := server.Console c := server.Console
r := server.Restart
go checkUpdate() go checkUpdate()
signal.Notify(c, os.Interrupt, os.Kill) signal.Notify(c, os.Interrupt, os.Kill)
<-c select {
case <-c:
b.Release() b.Release()
case <-r:
log.Info("正在重启中...")
defer b.Release()
restart(arg)
}
} }
func EncryptPwd(pwd string, key []byte) string { func EncryptPwd(pwd string, key []byte) string {
@ -404,3 +450,34 @@ func selfUpdate(imageUrl string) {
readLine() readLine()
os.Exit(0) os.Exit(0)
} }
func restart(Args []string) {
cmd := &exec.Cmd{}
if runtime.GOOS == "windows" {
file, err := exec.LookPath(Args[0])
if err != nil {
log.Errorf("重启失败:%s", err.Error())
return
}
path, err := filepath.Abs(file)
if err != nil {
log.Errorf("重启失败:%s", err.Error())
}
Args = append([]string{"/c", "start ", path, "faststart"}, Args[1:]...)
cmd = &exec.Cmd{
Path: "cmd.exe",
Args: Args,
Stderr: os.Stderr,
Stdout: os.Stdout,
}
} else {
Args = append(Args, "faststart")
cmd = &exec.Cmd{
Path: Args[0],
Args: Args,
Stderr: os.Stderr,
Stdout: os.Stdout,
}
}
cmd.Start()
}

View File

@ -4,15 +4,7 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"encoding/json"
"fmt" "fmt"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/yinghau76/go-ascii-art"
"image" "image"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -21,12 +13,25 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/gin-gonic/gin"
jsoniter "github.com/json-iterator/go"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
asciiart "github.com/yinghau76/go-ascii-art"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary
var WebInput = make(chan string, 1) //长度1用于阻塞 var WebInput = make(chan string, 1) //长度1用于阻塞
var Console = make(chan os.Signal, 1) var Console = make(chan os.Signal, 1)
var Restart = make(chan struct{}, 1)
var JsonConfig *global.JsonConfig var JsonConfig *global.JsonConfig
type webServer struct { type webServer struct {
@ -42,6 +47,7 @@ var WebServer = &webServer{}
// admin 子站的 路由映射 // admin 子站的 路由映射
var HttpuriAdmin = map[string]func(s *webServer, c *gin.Context){ var HttpuriAdmin = map[string]func(s *webServer, c *gin.Context){
"do_restart": AdminDoRestart, //热重启 "do_restart": AdminDoRestart, //热重启
"do_process_restart": AdminProcessRestart, //进程重启
"get_web_write": AdminWebWrite, //获取是否验证码输入 "get_web_write": AdminWebWrite, //获取是否验证码输入
"do_web_write": AdminDoWebWrite, //web上进行输入操作 "do_web_write": AdminDoWebWrite, //web上进行输入操作
"do_restart_docker": AdminDoRestartDocker, //直接停止依赖supervisord/docker重新拉起 "do_restart_docker": AdminDoRestartDocker, //直接停止依赖supervisord/docker重新拉起
@ -279,7 +285,7 @@ func GetConf() *global.JsonConfig {
if JsonConfig != nil { if JsonConfig != nil {
return JsonConfig return JsonConfig
} }
conf := global.Load("config.json") conf := global.Load("config.hjson")
return conf return conf
} }
@ -346,6 +352,8 @@ func (s *webServer) DoReLogin() { // TODO: 协议层的 ReLogin
return "Android Phone" return "Android Phone"
case client.AndroidWatch: case client.AndroidWatch:
return "Android Watch" return "Android Watch"
case client.MacOS:
return "MacOS"
} }
return "未知" return "未知"
}()) }())
@ -421,6 +429,12 @@ func AdminDoRestart(s *webServer, c *gin.Context) {
return return
} }
// 进程重启
func AdminProcessRestart(s *webServer, c *gin.Context) {
Restart <- struct{}{}
c.JSON(200, coolq.OK(coolq.MSG{}))
}
// 冷重启 // 冷重启
func AdminDoRestartDocker(s *webServer, c *gin.Context) { func AdminDoRestartDocker(s *webServer, c *gin.Context) {
Console <- os.Kill Console <- os.Kill
@ -463,9 +477,9 @@ func AdminDoConfigBase(s *webServer, c *gin.Context) {
conf.EnableDB = false conf.EnableDB = false
} }
conf.AccessToken = c.PostForm("access_token") conf.AccessToken = c.PostForm("access_token")
if err := conf.Save("config.json"); err != nil { if err := conf.Save("config.hjson"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err) log.Fatalf("保存 config.hjson 时出现错误: %v", err)
c.JSON(200, Failed(502, "保存 config.json 时出现错误:"+fmt.Sprintf("%v", err))) c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
} else { } else {
JsonConfig = nil JsonConfig = nil
c.JSON(200, coolq.OK(coolq.MSG{})) c.JSON(200, coolq.OK(coolq.MSG{}))
@ -488,9 +502,9 @@ func AdminDoConfigHttp(s *webServer, c *gin.Context) {
if c.PostForm("post_url") != "" { if c.PostForm("post_url") != "" {
conf.HttpConfig.PostUrls[c.PostForm("post_url")] = c.PostForm("post_secret") conf.HttpConfig.PostUrls[c.PostForm("post_url")] = c.PostForm("post_secret")
} }
if err := conf.Save("config.json"); err != nil { if err := conf.Save("config.hjson"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err) log.Fatalf("保存 config.hjson 时出现错误: %v", err)
c.JSON(200, Failed(502, "保存 config.json 时出现错误:"+fmt.Sprintf("%v", err))) c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
} else { } else {
JsonConfig = nil JsonConfig = nil
c.JSON(200, coolq.OK(coolq.MSG{})) c.JSON(200, coolq.OK(coolq.MSG{}))
@ -508,9 +522,9 @@ func AdminDoConfigWs(s *webServer, c *gin.Context) {
} else { } else {
conf.WSConfig.Enabled = false conf.WSConfig.Enabled = false
} }
if err := conf.Save("config.json"); err != nil { if err := conf.Save("config.hjson"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err) log.Fatalf("保存 config.hjson 时出现错误: %v", err)
c.JSON(200, Failed(502, "保存 config.json 时出现错误:"+fmt.Sprintf("%v", err))) c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
} else { } else {
JsonConfig = nil JsonConfig = nil
c.JSON(200, coolq.OK(coolq.MSG{})) c.JSON(200, coolq.OK(coolq.MSG{}))
@ -530,9 +544,9 @@ func AdminDoConfigReverse(s *webServer, c *gin.Context) {
} else { } else {
conf.ReverseServers[0].Enabled = false conf.ReverseServers[0].Enabled = false
} }
if err := conf.Save("config.json"); err != nil { if err := conf.Save("config.hjson"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err) log.Fatalf("保存 config.hjson 时出现错误: %v", err)
c.JSON(200, Failed(502, "保存 config.json 时出现错误:"+fmt.Sprintf("%v", err))) c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
} else { } else {
JsonConfig = nil JsonConfig = nil
c.JSON(200, coolq.OK(coolq.MSG{})) c.JSON(200, coolq.OK(coolq.MSG{}))
@ -545,13 +559,13 @@ func AdminDoConfigJson(s *webServer, c *gin.Context) {
Json := c.PostForm("json") Json := c.PostForm("json")
err := json.Unmarshal([]byte(Json), &conf) err := json.Unmarshal([]byte(Json), &conf)
if err != nil { if err != nil {
log.Warnf("尝试加载配置文件 %v 时出现错误: %v", "config.json", err) log.Warnf("尝试加载配置文件 %v 时出现错误: %v", "config.hjson", err)
c.JSON(200, Failed(502, "保存 config.json 时出现错误:"+fmt.Sprintf("%v", err))) c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
return return
} }
if err := conf.Save("config.json"); err != nil { if err := conf.Save("config.hjson"); err != nil {
log.Fatalf("保存 config.json 时出现错误: %v", err) log.Fatalf("保存 config.hjson 时出现错误: %v", err)
c.JSON(200, Failed(502, "保存 config.json 时出现错误:"+fmt.Sprintf("%v", err))) c.JSON(200, Failed(502, "保存 config.hjson 时出现错误:"+fmt.Sprintf("%v", err)))
} else { } else {
JsonConfig = nil JsonConfig = nil
c.JSON(200, coolq.OK(coolq.MSG{})) c.JSON(200, coolq.OK(coolq.MSG{}))

View File

@ -5,13 +5,14 @@ import (
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"github.com/guonaihong/gout/dataflow"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/guonaihong/gout/dataflow"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -307,7 +308,8 @@ func SetGroupKick(s *httpServer, c *gin.Context) {
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64) gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64) uid, _ := strconv.ParseInt(getParam(c, "user_id"), 10, 64)
msg := getParam(c, "message") msg := getParam(c, "message")
c.JSON(200, s.bot.CQSetGroupKick(gid, uid, msg)) block := getParamOrDefault(c, "reject_add_request", "false")
c.JSON(200, s.bot.CQSetGroupKick(gid, uid, msg, block == "true"))
} }
func SetGroupBan(s *httpServer, c *gin.Context) { func SetGroupBan(s *httpServer, c *gin.Context) {
@ -343,6 +345,16 @@ func SetGroupLeave(s *httpServer, c *gin.Context) {
c.JSON(200, s.bot.CQSetGroupLeave(gid)) c.JSON(200, s.bot.CQSetGroupLeave(gid))
} }
func SetRestart(s *httpServer, c *gin.Context) {
delay, _ := strconv.ParseInt(getParam(c, "delay"), 10, 64)
c.JSON(200, coolq.MSG{"data": nil, "retcode": 0, "status": "async"})
go func(delay int64) {
time.Sleep(time.Duration(delay) * time.Millisecond)
Restart <- struct{}{}
}(delay)
}
func GetForwardMessage(s *httpServer, c *gin.Context) { func GetForwardMessage(s *httpServer, c *gin.Context) {
resId := getParam(c, "message_id") resId := getParam(c, "message_id")
c.JSON(200, s.bot.CQGetForwardMessage(resId)) c.JSON(200, s.bot.CQGetForwardMessage(resId))
@ -488,6 +500,7 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
"set_group_whole_ban": SetWholeBan, "set_group_whole_ban": SetWholeBan,
"set_group_name": SetGroupName, "set_group_name": SetGroupName,
"set_group_admin": SetGroupAdmin, "set_group_admin": SetGroupAdmin,
"set_restart": SetRestart,
"_send_group_notice": SendGroupNotice, "_send_group_notice": SendGroupNotice,
"set_group_leave": SetGroupLeave, "set_group_leave": SetGroupLeave,
"get_image": GetImage, "get_image": GetImage,

View File

@ -433,7 +433,7 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str) return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str)
}, },
"set_group_kick": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "set_group_kick": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str) return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str, p.Get("reject_add_request").Bool())
}, },
"set_group_ban": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "set_group_ban": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), func() uint32 { return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), func() uint32 {
@ -480,6 +480,19 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
"get_group_honor_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "get_group_honor_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str) return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str)
}, },
"set_restart": func(c *coolq.CQBot, p gjson.Result) coolq.MSG {
var delay int64 = 0
delay = p.Get("delay").Int()
if delay < 0 {
delay = 0
}
defer func(delay int64) {
time.Sleep(time.Duration(delay) * time.Millisecond)
Restart <- struct{}{}
}(delay)
return coolq.MSG{"data": nil, "retcode": 0, "status": "async"}
},
"can_send_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "can_send_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQCanSendImage() return bot.CQCanSendImage()
}, },