1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-06-30 11:53:25 +00:00

Compare commits

...

78 Commits

Author SHA1 Message Date
9a4b284559 update MiraiGo. 2020-12-10 02:05:09 +08:00
37abe25cd6 update MiraiGo. 2020-12-10 02:01:44 +08:00
e8e78b596d Merge branch 'dev' of https://github.com/Mrs4s/go-cqhttp into dev 2020-12-10 01:32:31 +08:00
054ad47da9 feature auto fragment. 2020-12-10 01:32:08 +08:00
e694e8b482 support event recover. 2020-12-09 14:24:39 +08:00
d07e1ee77a Merge branch 'master' into dev. 2020-12-09 14:18:41 +08:00
818cecc279 Merge pull request #461 from wdvxdr1123/patch/eventfilter 2020-12-08 22:51:18 +08:00
950011b694 update docs 2020-12-08 22:12:58 +08:00
53b857b721 Merge pull request #473 from Yiwen-Chan/master 2020-12-08 20:57:13 +08:00
26372c0939 improve doc 2020-12-08 20:28:10 +08:00
e6de0c33cd improve doc 2020-12-08 20:24:48 +08:00
302ae89a75 fix pprof. 2020-12-07 10:53:18 +08:00
d8b9eb611f add stacktrace on panic. 2020-12-07 10:51:30 +08:00
35a1a0f8b5 update MiraiGo. 2020-12-05 18:17:37 +08:00
7cd6475c6b Merge pull request #467 from shirokurakana/dev
补充并整理文档
2020-12-05 00:53:56 +08:00
b3c4cecdac 补充并整理文档 2020-12-04 22:01:50 +08:00
469054e5a3 more info for 当前上网环境异常. close #465. 2020-12-04 14:29:12 +08:00
14278190e3 fix msg. 2020-12-04 09:39:53 +08:00
cc6c042516 feature pprof service. 2020-12-04 09:36:03 +08:00
abd32556cb Merge branch 'dev' of https://github.com/Mrs4s/go-cqhttp into dev 2020-12-04 00:41:24 +08:00
de1cd8b314 Merge pull request #463 from wdvxdr1123/patch/voice
尝试修复ios无法播放语音
2020-12-04 00:24:56 +08:00
4883c05d67 Merge pull request #462 from wdvxdr1123/patch/group_info
feat get group info no cache
2020-12-04 00:21:52 +08:00
1f20f26c49 update go-silk 2020-12-03 23:57:13 +08:00
12ac895b21 feat get group info no cache 2020-12-03 23:04:27 +08:00
70e8ea07bd remove convert 2020-12-03 22:19:46 +08:00
947d165ac5 improve event filter 2020-12-03 20:52:13 +08:00
93d0d87fbb optimization cqcode converter. 2020-12-03 15:02:36 +08:00
1fbaa6107d feature remove test for ocr_image api. 2020-12-03 11:05:36 +08:00
a4ec4077e2 fix #458. 2020-12-03 11:02:19 +08:00
8a75a6e95a update MiraiGo. 2020-12-03 10:58:29 +08:00
d63d10b69e update MiraiGo. 2020-12-03 00:59:35 +08:00
dfeadef1a2 update MiraiGo. 2020-12-02 22:13:52 +08:00
b23f68e746 try to fix #422. 2020-12-02 22:13:02 +08:00
c5a5f71664 update MiraiGo. 2020-12-02 20:34:15 +08:00
6973a10b4b fix #455. 2020-12-02 19:29:31 +08:00
3468c38fbc clear code. 2020-12-02 15:05:20 +08:00
d76bcfb1f0 update MiraiGo. 2020-12-02 00:36:26 +08:00
716c38bab4 Merge branch 'master' into dev 2020-12-02 00:35:24 +08:00
03518b4823 more error message. 2020-12-01 21:14:48 +08:00
09eeff3ce6 feature new cqcode converter 2020-12-01 19:31:17 +08:00
6599bf6aa6 update MiraiGo. 2020-11-29 21:17:16 +08:00
ffb2faeae7 Merge pull request #452 from brownchow/master
remove mkdir, add set -ex
2020-11-29 21:05:54 +08:00
71e3e97aeb update MiraiGo. 2020-11-29 21:01:12 +08:00
dcb708e3e3 remove mkdir, add set -ex 2020-11-29 18:21:01 +08:00
b9fb833af4 Merge pull request #451 from daofeng2015/master
fix:Dockerfile增加代理源
2020-11-29 13:55:19 +08:00
b93df0250d fix:Dockerfile增加代理源 2020-11-28 23:24:24 +08:00
33d64b6e27 update README.md 2020-11-27 01:46:42 +08:00
7f831cf856 update MiraiGo. 2020-11-27 01:38:08 +08:00
7a713c9327 update MiraiGo. 2020-11-27 01:28:52 +08:00
28d536a3af update MiraiGo. 2020-11-25 20:12:35 +08:00
375fdc8dca update config comment. 2020-11-25 17:28:19 +08:00
d1c6053df8 update MiraiGo. 2020-11-25 16:32:41 +08:00
143d5ef8ab feature proxy rewrite. 2020-11-24 19:03:37 +08:00
439c3422fb doc update. 2020-11-24 18:21:33 +08:00
2c7b56a79c fix get_msg. 2020-11-23 14:59:00 +08:00
1549ef4a32 update MiraiGo. 2020-11-23 14:19:41 +08:00
4ad684061b Merge branch 'master' into dev 2020-11-23 14:17:46 +08:00
c7e6457e9e Merge pull request #446 from Shigma/patch-1
get_status: fix inconsistant bahavior compared to onebot spec
2020-11-22 23:32:17 +08:00
9d5842f09b fix inconsistant bahaviour compared to spec
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

good:状态符合预期,意味着各模块正常运行、功能正常,且 QQ 在线
2020-11-22 23:26:38 +08:00
b6f3c300ab fix #442. 2020-11-21 21:27:25 +08:00
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
21 changed files with 1043 additions and 463 deletions

View File

@ -2,14 +2,15 @@ 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 \
&& mkdir /build && go env -w GOPROXY=https://goproxy.cn,direct
WORKDIR /build WORKDIR /build
COPY ./ . COPY ./ .
RUN cd /build \ RUN set -ex \
&& go build -ldflags "-s -w -extldflags '-static'" -o cqhttp && cd /build \
&& go build -ldflags "-s -w -extldflags '-static'" -o cqhttp
FROM alpine:latest FROM alpine:latest

240
README.md
View File

@ -20,81 +20,205 @@
- [x] 消息撤回事件 - [x] 消息撤回事件
- [x] 解析/发送 回复消息 - [x] 解析/发送 回复消息
- [x] 解析/发送 合并转发 - [x] 解析/发送 合并转发
- [ ] 使用代理请求网络图片 - [x] 使用代理请求网络图片
#### 实现 #### 实现
<details> <details>
<summary>已实现CQ码</summary> <summary>已实现CQ码</summary>
- [CQ:image] ##### 符合Onebot标准的CQ码
- [CQ:record] | CQ码 | 功能 |
- [CQ:video] | ------------ | ---------------------------- |
- [CQ:face] | [CQ:face] | [QQ表情] |
- [CQ:at] | [CQ:record] | [语音] |
- [CQ:share] | [CQ:video] | [短视频] |
- [CQ:reply] | [CQ:at] | [@某人] |
- [CQ:forward] | [CQ:share] | [链接分享] |
- [CQ:node] | [CQ:music] | [音乐分享] [音乐自定义分享] |
- [CQ:gift] | [CQ:reply] | [回复] |
- [CQ:redbag] | [CQ:forward] | [合并转发] |
- [CQ:tts] | [CQ:node] | [合并转发节点] |
- [CQ:music] | [CQ:xml] | [XML消息] |
| [CQ:json] | [JSON消息] |
[QQ表情]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#qq-%E8%A1%A8%E6%83%85
[语音]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E8%AF%AD%E9%9F%B3
[短视频]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E7%9F%AD%E8%A7%86%E9%A2%91
[@某人]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E6%9F%90%E4%BA%BA
[链接分享]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E9%93%BE%E6%8E%A5%E5%88%86%E4%BA%AB
[音乐分享]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E9%9F%B3%E4%B9%90%E5%88%86%E4%BA%AB-
[音乐自定义分享]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E9%9F%B3%E4%B9%90%E8%87%AA%E5%AE%9A%E4%B9%89%E5%88%86%E4%BA%AB-
[回复]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E5%9B%9E%E5%A4%8D
[合并转发]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-
[合并转发节点]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91%E8%8A%82%E7%82%B9-
[XML消息]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#xml-%E6%B6%88%E6%81%AF
[JSON消息]: https://github.com/howmanybots/onebot/blob/master/v11/specs/message/segment.md#json-%E6%B6%88%E6%81%AF
##### 拓展CQ码及与Onebot标准有略微差异的CQ码
| 拓展CQ码 | 功能 |
| -------------- | ------------------------------- |
| [CQ:image] | [图片] |
| [CQ:redbag] | [红包] |
| [CQ:poke] | [戳一戳] |
| [CQ:gift] | [礼物] |
| [CQ:node] | [合并转发消息节点] |
| [CQ:cardimage] | [一种xml的图片消息装逼大图] |
| [CQ:tts] | [文本转语音] |
[图片]: docs/cqhttp.md#%E5%9B%BE%E7%89%87
[红包]: docs/cqhttp.md#%E7%BA%A2%E5%8C%85
[戳一戳]: docs/cqhttp.md#%E6%88%B3%E4%B8%80%E6%88%B3
[礼物]: docs/cqhttp.md#%E7%A4%BC%E7%89%A9
[合并转发消息节点]: docs/cqhttp.md#%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91%E6%B6%88%E6%81%AF%E8%8A%82%E7%82%B9
[一种xml的图片消息装逼大图]: docs/cqhttp.md#cardimage-%E4%B8%80%E7%A7%8Dxml%E7%9A%84%E5%9B%BE%E7%89%87%E6%B6%88%E6%81%AF%E8%A3%85%E9%80%BC%E5%A4%A7%E5%9B%BE
[文本转语音]: docs/cqhttp.md#%E6%96%87%E6%9C%AC%E8%BD%AC%E8%AF%AD%E9%9F%B3
</details> </details>
<details> <details>
<summary>已实现API</summary> <summary>已实现API</summary>
##### 注意: 部分API实现与CQHTTP原版略有差异请参考文档 ##### 符合Onebot标准的API
| API | 功能 | | API | 功能 |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ------------------------ | ---------------------- |
| /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) | | /send_private_msg | [发送私聊消息] |
| /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) | | /send_group_msg | [发送群消息] |
| /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) | | /send_msg | [发送消息] |
| /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) | | /delete_msg | [撤回信息] |
| /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) | | /set_group_kick | [群组踢人] |
| /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) | | /set_group_ban | [群组单人禁言] |
| /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) | | /set_group_whole_ban | [群组全员禁言] |
| /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) | | /set_group_admin | [群组设置管理员] |
| /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) | | /set_group_card | [设置群名片(群备注)] |
| /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_group_name | [设置群名] |
| /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_leave | [退出群组] |
| /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_special_title | [设置群组专属头衔] |
| /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_friend_add_request | [处理加好友请求] |
| /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_add_request | [处理加群请求/邀请] |
| /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) | | /get_login_info | [获取登录号信息] |
| /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) | | /get_stranger_info | [获取陌生人信息] |
| /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) | | /get_friend_list | [获取好友列表] |
| /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) | | /get_group_info | [获取群信息] |
| /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_group_list | [获取群列表] |
| /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_group_member_info | [获取群成员信息] |
| /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) | | /get_group_member_list | [获取群成员列表] |
| /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) | | /get_group_honor_info | [获取群荣誉信息] |
| /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) | | /can_send_image | [检查是否可以发送图片] |
| /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) | | /can_send_record | [检查是否可以发送语音] |
| /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 | [获取版本信息] |
| /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) | | /set_restart | [重启go-cqhttp] |
| /.handle_quick_operation | [对事件执行快速操作] |
[发送私聊消息]: 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
[发送群消息]: 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
[发送消息]: 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
[撤回信息]: 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
[群组踢人]: 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
[群组单人禁言]: 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
[群组全员禁言]: 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
[群组设置管理员]: https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#set_group_admin-%E7%BE%A4%E7%BB%84%E8%AE%BE%E7%BD%AE%E7%AE%A1%E7%90%86%E5%91%98
[设置群名片(群备注)]: 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
[设置群名]: 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
[退出群组]: 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
[设置群组专属头衔]: 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
[处理加好友请求]: 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
[处理加群请求/邀请]: 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
[获取登录号信息]: 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
[获取陌生人信息]: https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_stranger_info-%E8%8E%B7%E5%8F%96%E9%99%8C%E7%94%9F%E4%BA%BA%E4%BF%A1%E6%81%AF
[获取好友列表]: 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
[获取群信息]: 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
[获取群列表]: 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
[获取群成员信息]: 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
[获取群成员列表]: 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
[获取群荣誉信息]: https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_group_honor_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E8%8D%A3%E8%AA%89%E4%BF%A1%E6%81%AF
[检查是否可以发送图片]: 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
[检查是否可以发送语音]: 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
[获取版本信息]: 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
[重启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
[对事件执行快速操作]: https://github.com/howmanybots/onebot/blob/master/v11/specs/api/hidden.md#handle_quick_operation-%E5%AF%B9%E4%BA%8B%E4%BB%B6%E6%89%A7%E8%A1%8C%E5%BF%AB%E9%80%9F%E6%93%8D%E4%BD%9C
##### 拓展API及与Onebot标准有略微差异的API
| 拓展API | 功能 |
| --------------------------- | ---------------------- |
| /set_group_portrait | [设置群头像] |
| /get_image | [获取图片信息] |
| /get_msg | [获取消息] |
| /get_forward_msg | [获取合并转发内容] |
| /send_group_forward_msg | [发送合并转发(群)] |
| /.get_word_slices | [获取中文分词] |
| /.ocr_image | [图片OCR] |
| /get_group_system_msg | [获取群系统消息] |
| /get_group_file_system_info | [获取群文件系统信息] |
| /get_group_root_files | [获取群根目录文件列表] |
| /get_group_files_by_folder | [获取群子目录文件列表] |
| /get_group_file_url | [获取群文件资源链接] |
| /get_status | [获取状态] |
[设置群头像]: docs/cqhttp.md#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F
[获取图片信息]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E5%9B%BE%E7%89%87%E4%BF%A1%E6%81%AF
[获取消息]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E6%B6%88%E6%81%AF
[获取合并转发内容]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91%E5%86%85%E5%AE%B9
[发送合并转发(群)]: docs/cqhttp.md#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91%E7%BE%A4
[获取中文分词]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E4%B8%AD%E6%96%87%E5%88%86%E8%AF%8D
[图片OCR]: docs/cqhttp.md#%E5%9B%BE%E7%89%87ocr
[获取群系统消息]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E7%BE%A4%E7%B3%BB%E7%BB%9F%E6%B6%88%E6%81%AF
[获取群文件系统信息]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E4%BF%A1%E6%81%AF
[获取群根目录文件列表]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%A0%B9%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
[获取群子目录文件列表]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%AD%90%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
[获取群文件资源链接]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E8%B5%84%E6%BA%90%E9%93%BE%E6%8E%A5
[获取状态]: docs/cqhttp.md#%E8%8E%B7%E5%8F%96%E7%8A%B6%E6%80%81
</details> </details>
<details> <details>
<summary>已实现Event</summary> <summary>已实现Event</summary>
##### 注意: 部分Event数据与CQHTTP原版略有差异请参考文档 ##### 符合Onebot标准的Event部分Event比Onebot标准多上报几个字段不影响使用
| Event | | 事件类型 | Event |
| ---------------------------------------------------------------------------------------------------------------------------------------------------- | | -------- | ---------------- |
| [私聊信息](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://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#群内戳一戳) | | 通知事件 | [群成员减少] |
| [群管理员变动](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://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://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://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E7%A6%81%E8%A8%80) | | 通知事件 | [群消息撤回] |
| [群文件上传](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://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://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) | | 通知事件 | [群红包运气王] |
| 通知事件 | [群成员荣誉变更] |
| 请求事件 | [加好友请求] |
| 请求事件 | [加群请求/邀请] |
[私聊信息]: 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://github.com/howmanybots/onebot/blob/master/v11/specs/event/message.md#%E7%BE%A4%E6%B6%88%E6%81%AF
[群文件上传]: 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://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://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://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://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E7%A6%81%E8%A8%80
[好友添加]: https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E5%A5%BD%E5%8F%8B%E6%B7%BB%E5%8A%A0
[群消息撤回]: https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E6%B6%88%E6%81%AF%E6%92%A4%E5%9B%9E
[好友消息撤回]: https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E5%A5%BD%E5%8F%8B%E6%B6%88%E6%81%AF%E6%92%A4%E5%9B%9E
[群内戳一戳]: https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E5%86%85%E6%88%B3%E4%B8%80%E6%88%B3
[群红包运气王]: https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E7%BA%A2%E5%8C%85%E8%BF%90%E6%B0%94%E7%8E%8B
[群成员荣誉变更]: https://github.com/howmanybots/onebot/blob/master/v11/specs/event/notice.md#%E7%BE%A4%E6%88%90%E5%91%98%E8%8D%A3%E8%AA%89%E5%8F%98%E6%9B%B4
[加好友请求]: 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://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
##### 拓展Event
| 事件类型 | 拓展Event |
| -------- | ---------------- |
| 通知事件 | [好友戳一戳] |
| 通知事件 | [群成员名片更新] |
| 通知事件 | [接收到离线文件] |
[好友戳一戳]: docs/cqhttp.md#%E5%A5%BD%E5%8F%8B%E6%88%B3%E4%B8%80%E6%88%B3
[群成员名片更新]: docs/cqhttp.md#%E7%BE%A4%E6%88%90%E5%91%98%E5%90%8D%E7%89%87%E6%9B%B4%E6%96%B0
[接收到离线文件]: docs/cqhttp.md#%E6%8E%A5%E6%94%B6%E5%88%B0%E7%A6%BB%E7%BA%BF%E6%96%87%E4%BB%B6
</details> </details>

View File

@ -55,10 +55,17 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
} }
// https://cqhttp.cc/docs/4.15/#/API?id=get_group_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E4%BF%A1%E6%81%AF // https://cqhttp.cc/docs/4.15/#/API?id=get_group_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetGroupInfo(groupId int64) MSG { func (bot *CQBot) CQGetGroupInfo(groupId int64, noCache bool) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil { if group == nil {
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
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{ return OK(MSG{
"group_id": group.Code, "group_id": group.Code,
@ -72,13 +79,13 @@ func (bot *CQBot) CQGetGroupInfo(groupId int64) MSG {
func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil { if group == nil {
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
if noCache { if noCache {
t, err := bot.Client.GetGroupMembers(group) t, err := bot.Client.GetGroupMembers(group)
if err != nil { if err != nil {
log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err) log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err)
return Failed(100) return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
} }
group.Members = t group.Members = t
} }
@ -93,11 +100,11 @@ func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG {
func (bot *CQBot) CQGetGroupMemberInfo(groupId, userId int64) MSG { func (bot *CQBot) CQGetGroupMemberInfo(groupId, userId int64) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil { if group == nil {
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
member := group.FindMember(userId) member := group.FindMember(userId)
if member == nil { if member == nil {
return Failed(102) return Failed(100, "MEMBER_NOT_FOUND", "群员不存在")
} }
return OK(convertGroupMemberInfo(groupId, member)) return OK(convertGroupMemberInfo(groupId, member))
} }
@ -106,7 +113,7 @@ func (bot *CQBot) CQGetGroupFileSystemInfo(groupId int64) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupId) fs, err := bot.Client.GetGroupFileSystem(groupId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(fs) return OK(fs)
} }
@ -115,12 +122,12 @@ func (bot *CQBot) CQGetGroupRootFiles(groupId int64) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupId) fs, err := bot.Client.GetGroupFileSystem(groupId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
files, folders, err := fs.Root() files, folders, err := fs.Root()
if err != nil { if err != nil {
log.Errorf("获取群 %v 根目录文件失败: %v", groupId, err) log.Errorf("获取群 %v 根目录文件失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(MSG{
"files": files, "files": files,
@ -132,12 +139,12 @@ func (bot *CQBot) CQGetGroupFilesByFolderId(groupId int64, folderId string) MSG
fs, err := bot.Client.GetGroupFileSystem(groupId) fs, err := bot.Client.GetGroupFileSystem(groupId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
files, folders, err := fs.GetFilesByFolder(folderId) files, folders, err := fs.GetFilesByFolder(folderId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupId, folderId, err) log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupId, folderId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(MSG{
"files": files, "files": files,
@ -148,7 +155,7 @@ func (bot *CQBot) CQGetGroupFilesByFolderId(groupId int64, folderId string) MSG
func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) MSG { func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) MSG {
url := bot.Client.GetGroupFileUrl(groupId, fileId, busId) url := bot.Client.GetGroupFileUrl(groupId, fileId, busId)
if url == "" { if url == "" {
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR")
} }
return OK(MSG{ return OK(MSG{
"url": url, "url": url,
@ -158,7 +165,7 @@ func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) M
func (bot *CQBot) CQGetWordSlices(content string) MSG { func (bot *CQBot) CQGetWordSlices(content string) MSG {
slices, err := bot.Client.GetWordSegmentation(content) slices, err := bot.Client.GetWordSegmentation(content)
if err != nil { if err != nil {
return Failed(100) return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error())
} }
for i := 0; i < len(slices); i++ { for i := 0; i < len(slices); i++ {
slices[i] = strings.ReplaceAll(slices[i], "\u0000", "") slices[i] = strings.ReplaceAll(slices[i], "\u0000", "")
@ -188,7 +195,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
fixAt(elem) fixAt(elem)
mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem}) mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(m.String()), mid) log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -204,7 +211,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
} }
if str == "" { if str == "" {
log.Warnf("群消息发送失败: 信息为空. MSG: %v", i) log.Warnf("群消息发送失败: 信息为空. MSG: %v", i)
return Failed(100) return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
} }
var elem []message.IMessageElement var elem []message.IMessageElement
if autoEscape { if autoEscape {
@ -215,7 +222,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
fixAt(elem) fixAt(elem)
mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem}) mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(str), mid) log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(str), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -312,7 +319,7 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
elem := bot.ConvertObjectMessage(m, true) elem := bot.ConvertObjectMessage(m, true)
mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem}) mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(m.String()), mid) log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -327,7 +334,7 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
str = s str = s
} }
if str == "" { if str == "" {
return Failed(100) return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
} }
var elem []message.IMessageElement var elem []message.IMessageElement
if autoEscape { if autoEscape {
@ -337,7 +344,7 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
} }
mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem}) mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(str), mid) log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(str), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -351,7 +358,7 @@ func (bot *CQBot) CQSetGroupCard(groupId, userId int64, card string) MSG {
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94
@ -362,7 +369,7 @@ func (bot *CQBot) CQSetGroupSpecialTitle(groupId, userId int64, title string) MS
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG { func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG {
@ -370,7 +377,7 @@ func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG {
g.UpdateName(name) g.UpdateName(name)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG { func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG {
@ -378,18 +385,18 @@ func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG {
g.UpdateMemo(msg) g.UpdateMemo(msg)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA // 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)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80
@ -400,7 +407,7 @@ func (bot *CQBot) CQSetGroupBan(groupId, userId int64, duration uint32) MSG {
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80
@ -409,7 +416,7 @@ func (bot *CQBot) CQSetGroupWholeBan(groupId int64, enable bool) MSG {
g.MuteAll(enable) g.MuteAll(enable)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84
@ -418,14 +425,14 @@ func (bot *CQBot) CQSetGroupLeave(groupId int64) MSG {
g.Quit() g.Quit()
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82 // https://cqhttp.cc/docs/4.15/#/API?id=set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82
func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG { func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
req, ok := bot.friendReqCache.Load(flag) req, ok := bot.friendReqCache.Load(flag)
if !ok { if !ok {
return Failed(100) return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
} }
if approve { if approve {
req.(*client.NewFriendRequest).Accept() req.(*client.NewFriendRequest).Accept()
@ -440,14 +447,14 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
msgs, err := bot.Client.GetGroupSystemMessages() msgs, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Errorf("获取群系统消息失败: %v", err) log.Errorf("获取群系统消息失败: %v", err)
return Failed(100) return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
} }
if subType == "add" { if subType == "add" {
for _, req := range msgs.JoinRequests { for _, req := range msgs.JoinRequests {
if strconv.FormatInt(req.RequestId, 10) == flag { if strconv.FormatInt(req.RequestId, 10) == flag {
if req.Checked { if req.Checked {
log.Errorf("处理群系统消息失败: 无法操作已处理的消息.") log.Errorf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100) return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
} }
if approve { if approve {
req.Accept() req.Accept()
@ -462,7 +469,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
if strconv.FormatInt(req.RequestId, 10) == flag { if strconv.FormatInt(req.RequestId, 10) == flag {
if req.Checked { if req.Checked {
log.Errorf("处理群系统消息失败: 无法操作已处理的消息.") log.Errorf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100) return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
} }
if approve { if approve {
req.Accept() req.Accept()
@ -474,23 +481,29 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
} }
} }
log.Errorf("处理群系统消息失败: 消息 %v 不存在.", flag) log.Errorf("处理群系统消息失败: 消息 %v 不存在.", flag)
return Failed(100) return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF // https://cqhttp.cc/docs/4.15/#/API?id=delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF
func (bot *CQBot) CQDeleteMessage(messageId int32) MSG { func (bot *CQBot) CQDeleteMessage(messageId int32) MSG {
msg := bot.GetMessage(messageId) msg := bot.GetMessage(messageId)
if msg == nil { if msg == nil {
return Failed(100) return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
} }
if _, ok := msg["group"]; ok { if _, ok := msg["group"]; ok {
bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)) if err := bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageId, err)
return Failed(100, "RECALL_API_ERROR", err.Error())
}
} else { } else {
if msg["sender"].(message.Sender).Uin != bot.Client.Uin { if msg["sender"].(message.Sender).Uin != bot.Client.Uin {
log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.") log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageId)
return Failed(100) return Failed(100, "CANNOT_RECALL_FRIEND_MSG", "无法撤回对方消息")
}
if err := bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageId, err)
return Failed(100, "RECALL_API_ERROR", err.Error())
} }
bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32))
} }
return OK(nil) return OK(nil)
} }
@ -499,17 +512,17 @@ func (bot *CQBot) CQDeleteMessage(messageId int32) MSG {
func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG { func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil || group.OwnerUin != bot.Client.Uin { if group == nil || group.OwnerUin != bot.Client.Uin {
return Failed(100) return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足")
} }
mem := group.FindMember(userId) mem := group.FindMember(userId)
if mem == nil { if mem == nil {
return Failed(100) return Failed(100, "GROUP_MEMBER_NOT_FOUND", "群成员不存在")
} }
mem.SetAdmin(enable) mem.SetAdmin(enable)
t, err := bot.Client.GetGroupMembers(group) t, err := bot.Client.GetGroupMembers(group)
if err != nil { if err != nil {
log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err) log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err)
return Failed(100) return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
} }
group.Members = t group.Members = t
return OK(nil) return OK(nil)
@ -518,7 +531,7 @@ func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG {
func (bot *CQBot) CQGetVipInfo(userId int64) MSG { func (bot *CQBot) CQGetVipInfo(userId int64) 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, "VIP_API_ERROR", err.Error())
} }
msg := MSG{ msg := MSG{
"user_id": vip.Uin, "user_id": vip.Uin,
@ -591,7 +604,7 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupId int64, t string) MSG {
func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG { func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG {
info, err := bot.Client.GetSummaryInfo(userId) info, err := bot.Client.GetSummaryInfo(userId)
if err != nil { if err != nil {
return Failed(100) return Failed(100, "SUMMARY_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(MSG{
"user_id": info.Uin, "user_id": info.Uin,
@ -639,7 +652,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
@ -686,14 +699,15 @@ func (bot *CQBot) CQGetImage(file string) MSG {
} }
msg["file"] = local msg["file"] = local
return OK(msg) return OK(msg)
} else {
return Failed(100, "LOAD_FILE_ERROR", err.Error())
} }
return Failed(100)
} }
func (bot *CQBot) CQGetForwardMessage(resId string) MSG { func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
m := bot.Client.GetForwardMessage(resId) m := bot.Client.GetForwardMessage(resId)
if m == nil { if m == nil {
return Failed(100) return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
r := make([]MSG, 0) r := make([]MSG, 0)
for _, n := range m.Nodes { for _, n := range m.Nodes {
@ -715,20 +729,27 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
func (bot *CQBot) CQGetMessage(messageId int32) MSG { func (bot *CQBot) CQGetMessage(messageId int32) MSG {
msg := bot.GetMessage(messageId) msg := bot.GetMessage(messageId)
if msg == nil { if msg == nil {
return Failed(100) return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
sender := msg["sender"].(message.Sender) sender := msg["sender"].(message.Sender)
_, group := msg["group"] gid, isGroup := msg["group"]
raw := msg["message"].(string)
return OK(MSG{ return OK(MSG{
"message_id": messageId, "message_id": messageId,
"real_id": msg["message-id"], "real_id": msg["message-id"],
"group": group, "group": isGroup,
"group_id": gid,
"sender": MSG{ "sender": MSG{
"user_id": sender.Uin, "user_id": sender.Uin,
"nickname": sender.Nickname, "nickname": sender.Nickname,
}, },
"time": msg["time"], "time": msg["time"],
"message": msg["message"], "message": ToFormattedMessage(bot.ConvertStringMessage(raw, isGroup), func() int64 {
if isGroup {
return gid.(int64)
}
return sender.Uin
}(), false),
}) })
} }
@ -736,7 +757,7 @@ func (bot *CQBot) CQGetGroupSystemMessages() MSG {
msg, err := bot.Client.GetGroupSystemMessages() msg, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Warnf("获取群系统消息失败: %v", err) log.Warnf("获取群系统消息失败: %v", err)
return Failed(100) return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
} }
return OK(msg) return OK(msg)
} }
@ -753,12 +774,12 @@ func (bot *CQBot) CQOcrImage(imageId string) MSG {
img, err := bot.makeImageElem(map[string]string{"file": imageId}, true) img, err := bot.makeImageElem(map[string]string{"file": imageId}, true)
if err != nil { if err != nil {
log.Warnf("load image error: %v", err) log.Warnf("load image error: %v", err)
return Failed(100) return Failed(100, "LOAD_FILE_ERROR", err.Error())
} }
rsp, err := bot.Client.ImageOcr(img) rsp, err := bot.Client.ImageOcr(img)
if err != nil { if err != nil {
log.Warnf("ocr image error: %v", err) log.Warnf("ocr image error: %v", err)
return Failed(100) return Failed(100, "OCR_API_ERROR", err.Error())
} }
return OK(rsp) return OK(rsp)
} }
@ -773,14 +794,15 @@ func (bot *CQBot) CQSetGroupPortrait(groupId int64, file, cache string) MSG {
img, err := global.FindFile(file, cache, global.IMAGE_PATH) img, err := global.FindFile(file, cache, global.IMAGE_PATH)
if err != nil { if err != nil {
log.Warnf("set group portrait error: %v", err) log.Warnf("set group portrait error: %v", err)
return Failed(100) return Failed(100, "LOAD_FILE_ERROR", err.Error())
} }
g.UpdateGroupHeadPortrait(img) g.UpdateGroupHeadPortrait(img)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_status-%E8%8E%B7%E5%8F%96%E8%BF%90%E8%A1%8C%E7%8A%B6%E6%80%81
func (bot *CQBot) CQGetStatus() MSG { func (bot *CQBot) CQGetStatus() MSG {
return OK(MSG{ return OK(MSG{
"app_initialized": true, "app_initialized": true,
@ -788,7 +810,8 @@ func (bot *CQBot) CQGetStatus() MSG {
"plugins_good": nil, "plugins_good": nil,
"app_good": true, "app_good": true,
"online": bot.Client.Online, "online": bot.Client.Online,
"good": true, "good": bot.Client.Online,
"stat": bot.Client.GetStatistics(),
}) })
} }
@ -812,6 +835,8 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
return 1 return 1
case client.AndroidWatch: case client.AndroidWatch:
return 2 return 2
case client.MacOS:
return 3
default: default:
return -1 return -1
} }
@ -823,8 +848,16 @@ func OK(data interface{}) MSG {
return MSG{"data": data, "retcode": 0, "status": "ok"} return MSG{"data": data, "retcode": 0, "status": "ok"}
} }
func Failed(code int) MSG { func Failed(code int, msg ...string) MSG {
return MSG{"data": nil, "retcode": code, "status": "failed"} m := ""
w := ""
if len(msg) > 0 {
m = msg[0]
}
if len(msg) > 1 {
w = msg[1]
}
return MSG{"data": nil, "retcode": code, "msg": m, "wording": w, "status": "failed"}
} }
func convertGroupMemberInfo(groupId int64, m *client.GroupMemberInfo) MSG { func convertGroupMemberInfo(groupId int64, m *client.GroupMemberInfo) MSG {

View File

@ -3,10 +3,10 @@ package coolq
import ( import (
"bytes" "bytes"
"encoding/gob" "encoding/gob"
"encoding/json"
"fmt" "fmt"
"hash/crc32" "hash/crc32"
"path" "path"
"runtime/debug"
"sync" "sync"
"time" "time"
@ -17,10 +17,12 @@ import (
"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"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type CQBot struct { type CQBot struct {
Client *client.QQClient Client *client.QQClient
@ -220,7 +222,13 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
ret := bot.Client.SendGroupMessage(groupId, m, ForceFragmented) ret := bot.Client.SendGroupMessage(groupId, m, ForceFragmented)
if ret == nil || ret.Id == -1 { if ret == nil || ret.Id == -1 {
log.Warnf("群消息发送失败: 账号可能被风控.") log.Warnf("群消息发送失败: 账号可能被风控.")
return -1 if !ForceFragmented {
log.Warnf("将尝试分片发送...")
ret = bot.Client.SendGroupMessage(groupId, m, true)
}
if ret == nil || ret.Id == -1 {
return -1
}
} }
return bot.InsertGroupMessage(ret) return bot.InsertGroupMessage(ret)
} }
@ -390,22 +398,24 @@ func (bot *CQBot) Release() {
} }
func (bot *CQBot) dispatchEventMessage(m MSG) { func (bot *CQBot) dispatchEventMessage(m MSG) {
payload := gjson.Parse(m.ToJson()) if global.EventFilter != nil && global.EventFilter.Eval(global.MSG(m)) == false {
filter := global.EventFilter
if filter != nil && (*filter).Eval(payload) == false {
log.Debug("Event filtered!") log.Debug("Event filtered!")
return return
} }
for _, f := range bot.events { for _, f := range bot.events {
fn := f go func(fn func(MSG)) {
go func() { defer func() {
if pan := recover(); pan != nil {
log.Warnf("处理事件 %v 时出现错误: %v \n%s", m, pan, debug.Stack())
}
}()
start := time.Now() start := time.Now()
fn(m) fn(m)
end := time.Now() end := time.Now()
if end.Sub(start) > time.Second*5 { if end.Sub(start) > time.Second*5 {
log.Debugf("警告: 事件处理耗时超过 5 秒 (%v), 请检查应用是否有堵塞.", end.Sub(start)) log.Debugf("警告: 事件处理耗时超过 5 秒 (%v), 请检查应用是否有堵塞.", end.Sub(start))
} }
}() }(f)
} }
} }

View File

@ -9,9 +9,9 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"math"
"net/url" "net/url"
"path" "path"
"regexp"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
@ -23,9 +23,11 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
/*
var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`) var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`)
var typeReg = regexp.MustCompile(`\[CQ:(\w+)`) var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`) var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
*/
var IgnoreInvalidCQCode = false var IgnoreInvalidCQCode = false
@ -183,13 +185,37 @@ 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.GroupImageElement:
if ur {
m = MSG{
"type": "image",
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image"},
}
} else {
m = MSG{
"type": "image",
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": CQCodeEscapeText(o.Url)},
}
}
case *message.FriendImageElement:
if ur {
m = MSG{
"type": "image",
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image"},
}
} else {
m = MSG{
"type": "image",
"data": map[string]string{"file": hex.EncodeToString(o.Md5) + ".image", "url": CQCodeEscapeText(o.Url)},
}
}
case *message.GroupFlashImgElement: case *message.GroupFlashImgElement:
return []MSG{MSG{ return []MSG{{
"type": "image", "type": "image",
"data": map[string]string{"file": o.Filename, "type": "flash"}, "data": map[string]string{"file": o.Filename, "type": "flash"},
}} }}
case *message.FriendFlashImgElement: case *message.FriendFlashImgElement:
return []MSG{MSG{ return []MSG{{
"type": "image", "type": "image",
"data": map[string]string{"file": o.Filename, "type": "flash"}, "data": map[string]string{"file": o.Filename, "type": "flash"},
}} }}
@ -262,9 +288,17 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
r += fmt.Sprintf(`[CQ:image,file=%s,url=%s]`, o.Filename, CQCodeEscapeValue(o.Url)) r += fmt.Sprintf(`[CQ:image,file=%s,url=%s]`, o.Filename, CQCodeEscapeValue(o.Url))
} }
case *message.GroupImageElement: case *message.GroupImageElement:
r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image") 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))
}
case *message.FriendImageElement: case *message.FriendImageElement:
r += fmt.Sprintf("[CQ:image,file=%s]", hex.EncodeToString(o.Md5)+".image") 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))
}
case *message.GroupFlashImgElement: case *message.GroupFlashImgElement:
return fmt.Sprintf("[CQ:image,type=flash,file=%s]", o.Filename) return fmt.Sprintf("[CQ:image,type=flash,file=%s]", o.Filename)
case *message.FriendFlashImgElement: case *message.FriendFlashImgElement:
@ -283,30 +317,68 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
return return
} }
func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessageElement) { func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMessageElement) {
i := matchReg.FindAllStringSubmatchIndex(m, -1) index := 0
si := 0 stat := 0
for _, idx := range i { rMsg := []rune(msg)
if idx[0] > si { var tempText, cqCode []rune
text := m[si:idx[0]] hasNext := func() bool {
r = append(r, message.NewText(CQCodeUnescapeText(text))) return index < len(rMsg)
}
next := func() rune {
r := rMsg[index]
index++
return r
}
move := func(steps int) {
index += steps
}
peekN := func(count int) string {
lastIdx := int(math.Min(float64(index+count), float64(len(rMsg))))
return string(rMsg[index:lastIdx])
}
isCQCodeBegin := func(r rune) bool {
return r == '[' && peekN(3) == "CQ:"
}
saveTempText := func() {
if len(tempText) != 0 {
r = append(r, message.NewText(CQCodeUnescapeValue(string(tempText))))
} }
code := m[idx[0]:idx[1]] tempText = []rune{}
si = idx[1] cqCode = []rune{}
t := typeReg.FindAllStringSubmatch(code, -1)[0][1] }
ps := paramReg.FindAllStringSubmatch(code, -1) saveCQCode := func() {
d := make(map[string]string) defer func() {
for _, p := range ps { cqCode = []rune{}
d[p[1]] = CQCodeUnescapeValue(p[2]) tempText = []rune{}
}()
s := strings.SplitN(string(cqCode), ",", -1)
if len(s) == 0 {
return
} }
if t == "reply" { t := s[0]
params := make(map[string]string)
for i := 1; i < len(s); i++ {
p := s[i]
p = strings.TrimSpace(p)
if p == "" {
continue
}
data := strings.SplitN(p, "=", 2)
if len(data) == 2 {
params[data[0]] = CQCodeUnescapeValue(data[1])
} else {
params[p] = ""
}
}
if t == "reply" { // reply 特殊处理
if len(r) > 0 { if len(r) > 0 {
if _, ok := r[0].(*message.ReplyElement); ok { if _, ok := r[0].(*message.ReplyElement); ok {
log.Warnf("警告: 一条信息只能包含一个 Reply 元素.") log.Warnf("警告: 一条信息只能包含一个 Reply 元素.")
continue return
} }
} }
mid, err := strconv.Atoi(d["id"]) mid, err := strconv.Atoi(params["id"])
if err == nil { if err == nil {
org := bot.GetMessage(int32(mid)) org := bot.GetMessage(int32(mid))
if org != nil { if org != nil {
@ -318,19 +390,20 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
Elements: bot.ConvertStringMessage(org["message"].(string), group), Elements: bot.ConvertStringMessage(org["message"].(string), group),
}, },
}, r...) }, r...)
continue return
} }
} }
} }
elem, err := bot.ToElement(t, d, group) elem, err := bot.ToElement(t, params, group)
if err != nil { if err != nil {
org := "[" + string(cqCode) + "]"
if !IgnoreInvalidCQCode { if !IgnoreInvalidCQCode {
log.Warnf("转换CQ码 %v 到MiraiGo Element时出现错误: %v 将原样发送.", code, err) log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err)
r = append(r, message.NewText(code)) r = append(r, message.NewText(org))
} else { } else {
log.Warnf("转换CQ码 %v 到MiraiGo Element时出现错误: %v 将忽略.", code, err) log.Warnf("转换CQ码 %v 时出现错误: %v 将忽略.", org, err)
} }
continue return
} }
switch i := elem.(type) { switch i := elem.(type) {
case message.IMessageElement: case message.IMessageElement:
@ -339,9 +412,32 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
r = append(r, i...) r = append(r, i...)
} }
} }
if si != len(m) { for hasNext() {
r = append(r, message.NewText(CQCodeUnescapeText(m[si:]))) ch := next()
switch stat {
case 0:
if isCQCodeBegin(ch) {
saveTempText()
tempText = append(tempText, []rune("[CQ:")...)
move(3)
stat = 1
} else {
tempText = append(tempText, ch)
}
case 1:
if isCQCodeBegin(ch) {
move(-1)
stat = 0
} else if ch == ']' {
saveCQCode()
stat = 0
} else {
cqCode = append(cqCode, ch)
tempText = append(tempText, ch)
}
}
} }
saveTempText()
return return
} }
@ -598,14 +694,12 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
case "xml": case "xml":
resId := d["resid"] resId := d["resid"]
template := CQCodeEscapeValue(d["data"]) template := CQCodeEscapeValue(d["data"])
//println(template)
i, _ := strconv.ParseInt(resId, 10, 64) i, _ := strconv.ParseInt(resId, 10, 64)
msg := message.NewRichXml(template, i) msg := message.NewRichXml(template, i)
return msg, nil return msg, nil
case "json": case "json":
resId := d["resid"] resId := d["resid"]
i, _ := strconv.ParseInt(resId, 10, 64) i, _ := strconv.ParseInt(resId, 10, 64)
log.Warnf("json msg=%s", d["data"])
if i == 0 { if i == 0 {
//默认情况下走小程序通道 //默认情况下走小程序通道
msg := message.NewLightApp(CQCodeUnescapeValue(d["data"])) msg := message.NewLightApp(CQCodeUnescapeValue(d["data"]))

View File

@ -1,12 +1,22 @@
# 事件过滤器 # 事件过滤器
在go-cqhttp同级目录下新建`filter.json`文件即可开启事件过滤器,启动时会读取该文件中定义的过滤规则(使用 JSON 编写),若文件不存在,或过滤规则语法错误,则会暂停所有上报 在go-cqhttp同级目录下新建`filter.json`文件即可开启事件过滤器,启动时会读取该文件中定义的过滤规则(使用 JSON 编写),若文件不存在,或过滤规则语法错误,则不会启用事件过滤器
事件过滤器会处理所有事件(包括心跳事件在内的元事件),请谨慎使用!! 事件过滤器会处理所有事件(包括心跳事件在内的元事件),请谨慎使用!!
注意: 与客户端建立连接的握手事件**不会**经过事件过滤器
## 示例 ## 示例
这节首先给出一些示例,演示过滤器的基本用法,下一节将给出具体语法说明。 这节首先给出一些示例,演示过滤器的基本用法,下一节将给出具体语法说明。
### 过滤所有事件
```json
{
".not": {}
}
```
### 只上报以「!!」开头的消息 ### 只上报以「!!」开头的消息
```json ```json
@ -128,5 +138,5 @@
这里有几点需要注意: 这里有几点需要注意:
- `message` 字段在运行过滤器时是消息段数组的形式(见 [消息格式]( https://github.com/howmanybots/onebot/blob/master/v11/specs/message/array.md ) - `message` 字段在运行过滤器时和上报信息类型相同(见 [消息格式]( https://github.com/howmanybots/onebot/blob/master/v11/specs/message/array.md )
- `raw_message` 字段为未经**CQ码**处理的原始消息字符串,这意味着其中可能会出现形如 `[CQ:face,id=123]` 的 CQ 码 - `raw_message` 字段为未经**CQ码**处理的原始消息字符串,这意味着其中可能会出现形如 `[CQ:face,id=123]` 的 CQ 码

View File

@ -8,7 +8,7 @@
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------------ | ------ | --------------------------- | | ------------ | ------ | --------------------------- |
| access_token | string | 校验口令config.json中配置 | | access_token | string | 校验口令config.hjson中配置 |
@ -209,7 +209,7 @@ method: `POST` formdata
### admin/do_config_json ### admin/do_config_json
> 直接修改 config.json配置 > 直接修改 config.hjson配置
method: `POST` formdata method: `POST` formdata
@ -217,7 +217,7 @@ method: `POST` formdata
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------------------------------- | | ------ | ------ | ----------------------------------- |
| json | string | 完整的config.json的配合json字符串 | | json | string | 完整的config.hjson的配合json字符串 |
返回: 返回:
@ -228,7 +228,7 @@ method: `POST` formdata
### admin/get_config_json ### admin/get_config_json
> 获取当前 config.json配置 > 获取当前 config.hjson配置
method: `GET` method: `GET`
@ -247,5 +247,5 @@ 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导入配置

View File

@ -2,10 +2,64 @@
由于部分 api 原版 CQHTTP 并未实现go-cqhttp 修改并增加了一些拓展 api . 由于部分 api 原版 CQHTTP 并未实现go-cqhttp 修改并增加了一些拓展 api .
<details>
<summary>目录</summary>
<p>
##### CQCode
- [图片](#图片)
- [回复](#回复)
- [红包](#红包)
- [戳一戳](#戳一戳)
- [礼物](#礼物)
- [合并转发](#合并转发)
- [合并转发消息节点](#合并转发消息节点)
- [XML 消息](#xml-消息)
- [JSON 消息](#json-消息)
- [cardimage](#cardimage)
- [文本转语音](#文本转语音)
- [图片](#图片)
##### API
- [设置群名](#设置群名)
- [设置群头像](#设置群头像)
- [获取图片信息](#获取图片信息)
- [获取消息](#获取消息)
- [获取合并转发内容](#获取合并转发内容)
- [发送合并转发(群)](#发送合并转发(群))
- [获取中文分词](#获取中文分词)
- [图片OCR](#图片OCR)
- [获取中文分词](#获取中文分词)
- [获取群系统消息](#获取群文件系统信息)
- [获取群文件系统信息](#获取群文件系统信息)
- [获取群根目录文件列表](#获取群根目录文件列表)
- [获取群子目录文件列表](#获取群子目录文件列表)
- [获取群文件资源链接](#获取群文件资源链接)
- [获取状态](#获取状态)
- [获取群子目录文件列表](#设置群名)
##### 事件
- [群消息撤回](#群消息撤回)
- [好友消息撤回](#好友消息撤回)
- [群内戳一戳](#群内戳一戳)
- [群红包运气王提示](#群红包运气王提示)
- [群成员荣誉变更提示](#群成员荣誉变更提示)
- [群成员名片更新](#群成员名片更新)
- [接收到离线文件](#接收到离线文件)
</p>
</details>
## CQCode ## CQCode
### 图片 ### 图片
Type : `image`
范围: **发送/接收**
参数:
| 参数名 | 可能的值 | 说明 | | 参数名 | 可能的值 | 说明 |
| ------- | --------------- | --------------------------------------------------------------- | | ------- | --------------- | --------------------------------------------------------------- |
| `file` | - | 图片文件名 | | `file` | - | 图片文件名 |
@ -25,6 +79,8 @@
| 40004 | 爱你 | | 40004 | 爱你 |
| 40005 | 征友 | | 40005 | 征友 |
示例: `[CQ:image,file=http://baidu.com/1.jpg,type=show,id=40004]`
### 回复 ### 回复
@ -36,7 +92,7 @@ Type : `reply`
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ---- | ------------------------------------- | | ------ | ---- | ------------------------------------- |
| id | int | 回复时所引用的消息id, 必须为本群消息. | | `id` | int | 回复时所引用的消息id, 必须为本群消息. |
示例: `[CQ:reply,id=123456]` 示例: `[CQ:reply,id=123456]`
@ -48,9 +104,9 @@ Type: `redbag`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------- | | ------- | ------ | ----------- |
| title | string | 祝福语/口令 | | `title` | string | 祝福语/口令 |
示例: `[CQ:redbag,title=恭喜发财]` 示例: `[CQ:redbag,title=恭喜发财]`
@ -66,7 +122,7 @@ Type: `poke`
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ----- | ------------ | | ------ | ----- | ------------ |
| qq | int64 | 需要戳的成员 | | `qq` | int64 | 需要戳的成员 |
示例: `[CQ:poke,qq=123456]` 示例: `[CQ:poke,qq=123456]`
@ -82,8 +138,8 @@ Type: `gift`
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ----- | -------------- | | ------ | ----- | -------------- |
| qq | int64 | 接收礼物的成员 | | `qq` | int64 | 接收礼物的成员 |
| id | int | 礼物的类型 | | `id` | int | 礼物的类型 |
目前支持的礼物ID: 目前支持的礼物ID:
@ -116,9 +172,9 @@ Type: `forward`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ------------------------------------------------------------- | | ------ | ------ | ------------------------------------------------------------ |
| id | string | 合并转发ID, 需要通过 `/get_forward_msg` API获取转发的具体内容 | | `id` | string | 合并转发ID, 需要通过 `/get_forward_msg` API获取转发的具体内容 |
示例: `[CQ:forward,id=xxxx]` 示例: `[CQ:forward,id=xxxx]`
@ -130,12 +186,12 @@ Type: `node`
参数: 参数:
| 参数名 | 类型 | 说明 | 特殊说明 | | 参数名 | 类型 | 说明 | 特殊说明 |
| ------- | ------- | -------------- | -------------------------------------------------------------------------------------- | | --------- | ------- | -------------- | ------------------------------------------------------------ |
| id | int32 | 转发消息id | 直接引用他人的消息合并转发, 实际查看顺序为原消息发送顺序 **与下面的自定义消息二选一** | | `id` | int32 | 转发消息id | 直接引用他人的消息合并转发, 实际查看顺序为原消息发送顺序 **与下面的自定义消息二选一** |
| name | string | 发送者显示名字 | 用于自定义消息 (自定义消息并合并转发,实际查看顺序为自定义消息段顺序) | | `name` | string | 发送者显示名字 | 用于自定义消息 (自定义消息并合并转发,实际查看顺序为自定义消息段顺序) |
| uin | int64 | 发送者QQ号 | 用于自定义消息 | | `uin` | int64 | 发送者QQ号 | 用于自定义消息 |
| content | message | 具体消息 | 用于自定义消息 **不支持转发套娃,不支持引用回复** | | `content` | message | 具体消息 | 用于自定义消息 **不支持转发套娃,不支持引用回复** |
特殊说明: **需要使用单独的API `/send_group_forward_msg` 发送并且由于消息段较为复杂仅支持Array形式入参。 如果引用消息和自定义消息同时出现,实际查看顺序将取消息段顺序. 另外按 [CQHTTP](https://cqhttp.cc/docs/4.15/#/Message?id=格式) 文档说明, `data` 应全为字符串, 但由于需要接收`message` 类型的消息, 所以 *仅限此Type的content字段* 支持Array套娃** 特殊说明: **需要使用单独的API `/send_group_forward_msg` 发送并且由于消息段较为复杂仅支持Array形式入参。 如果引用消息和自定义消息同时出现,实际查看顺序将取消息段顺序. 另外按 [CQHTTP](https://cqhttp.cc/docs/4.15/#/Message?id=格式) 文档说明, `data` 应全为字符串, 但由于需要接收`message` 类型的消息, 所以 *仅限此Type的content字段* 支持Array套娃**
@ -209,7 +265,7 @@ Type: `node`
] ]
```` ````
### xml支持 ### XML 消息
Type: `xml` Type: `xml`
@ -217,10 +273,10 @@ Type: `xml`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------------------------------------- | | ------- | ------ | ----------------------------------------- |
| data | string | xml内容xml中的value部分记得实体化处理 | | `data` | string | xml内容xml中的value部分记得实体化处理 |
| resid | int32 | 可以不填 | | `resid` | int32 | 可以不填 |
示例: `[CQ:xml,data=xxxx]` 示例: `[CQ:xml,data=xxxx]`
@ -258,7 +314,7 @@ Type: `xml`
</msg> </msg>
``` ```
### json消息支持 ### JSON 消息
Type: `json` Type: `json`
@ -266,20 +322,20 @@ Type: `json`
参数: 参数:
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ----------------------------------------------- | | ------- | ------ | ----------------------------------------------- |
| data | string | json内容json的所有字符串记得实体化处理 | | `data` | string | json内容json的所有字符串记得实体化处理 |
| resid | int32 | 默认不填为0走小程序通道填了走富文本通道发送 | | `resid` | int32 | 默认不填为0走小程序通道填了走富文本通道发送 |
json中的字符串需要进行转义 json中的字符串需要进行转义
>","=>`&#44;` >","=> `&#44;`
>"&"=> `&amp;` >"&"=> `&amp;`
>"["=>`&#91;` >"["=> `&#91;`
>"]"=>`&#93;` >"]"=> `&#93;`
否则无法正确得到解析 否则无法正确得到解析
@ -289,7 +345,8 @@ json中的字符串需要进行转义
``` ```
### cardimage 一种xml的图片消息装逼大图 ### cardimage
一种xml的图片消息装逼大图
ps: xml 接口的消息都存在风控风险,请自行兼容发送失败后的处理(可以失败后走普通图片模式) ps: xml 接口的消息都存在风控风险,请自行兼容发送失败后的处理(可以失败后走普通图片模式)
@ -299,15 +356,15 @@ 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 |
| maxwidth | int64 | 默认不填为500最大width | | `maxwidth` | int64 | 默认不填为500最大width |
| maxheight | int64 | 默认不填为1000最大height | | `maxheight` | int64 | 默认不填为1000最大height |
| source | string | 分享来源的名称,可以留空 | | `source` | string | 分享来源的名称,可以留空 |
| icon | string | 分享来源的icon图标url可以留空 | | `icon` | string | 分享来源的icon图标url可以留空 |
示例cardimage 的cq码 示例cardimage 的cq码
@ -327,7 +384,7 @@ Type: `tts`
| 参数名 | 类型 | 说明 | | 参数名 | 类型 | 说明 |
| ------ | ------ | ---- | | ------ | ------ | ---- |
| text | string | 内容 | | `text` | string | 内容 |
示例: `[CQ:tts,text=这是一条测试消息]` 示例: `[CQ:tts,text=这是一条测试消息]`
@ -339,10 +396,10 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ------ | ---- | | ------------ | ------ | ---- |
| group_id | int64 | 群号 | | `group_id` | int64 | 群号 |
| group_name | string | 新名 | | `group_name` | string | 新名 |
### 设置群头像 ### 设置群头像
@ -350,11 +407,11 @@ Type: `tts`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| -------- | ------ | ------------------------ | | ---------- | ------ | ------------------------ |
| group_id | int64 | 群号 | | `group_id` | int64 | 群号 |
| file | string | 图片文件名 | | `file` | string | 图片文件名 |
| cache | int | 表示是否使用已缓存的文件 | | `cache` | int | 表示是否使用已缓存的文件 |
[1]`file` 参数支持以下几种格式: [1]`file` 参数支持以下几种格式:
@ -485,26 +542,26 @@ Type: `tts`
终结点: `/.ocr_image` 终结点: `/.ocr_image`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------- | ------ | ------ | | ------- | ------ | ------ |
| `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 | 坐标 |
### 获取群系统消息 ### 获取群系统消息
@ -512,56 +569,56 @@ Type: `tts`
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------------ | ---------------- | ------------ | | ------------------ | ---------------- | ------------ |
| `invited_requests` | InvitedRequest[] | 邀请消息列表 | | `invited_requests` | InvitedRequest[] | 邀请消息列表 |
| `join_requests` | JoinRequest[] | 进群消息列表 | | `join_requests` | JoinRequest[] | 进群消息列表 |
> 注意: 如果列表不存在任何消息, 将返回 `null` > 注意: 如果列表不存在任何消息, 将返回 `null`
**InvitedRequest** **InvitedRequest**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| -------------- | ------ | ----------------- | | -------------- | ------ | ----------------- |
| `request_id` | int64 | 请求ID | | `request_id` | int64 | 请求ID |
| `invitor_uin` | int64 | 邀请者 | | `invitor_uin` | int64 | 邀请者 |
| `invitor_nick` | string | 邀请者昵称 | | `invitor_nick` | string | 邀请者昵称 |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
| `group_name` | string | 群名 | | `group_name` | string | 群名 |
| `checked` | bool | 是否已被处理 | | `checked` | bool | 是否已被处理 |
| `actor` | int64 | 处理者, 未处理为0 | | `actor` | int64 | 处理者, 未处理为0 |
**JoinRequest** **JoinRequest**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------------- | ------ | ----------------- | | ---------------- | ------ | ----------------- |
| `request_id` | int64 | 请求ID | | `request_id` | int64 | 请求ID |
| `requester_uin` | int64 | 请求者ID | | `requester_uin` | int64 | 请求者ID |
| `requester_nick` | string | 请求者昵称 | | `requester_nick` | string | 请求者昵称 |
| `message` | string | 验证消息 | | `message` | string | 验证消息 |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
| `group_name` | string | 群名 | | `group_name` | string | 群名 |
| `checked` | bool | 是否已被处理 | | `checked` | bool | 是否已被处理 |
| `actor` | int64 | 处理者, 未处理为0 | | `actor` | int64 | 处理者, 未处理为0 |
### 获取群文件系统信息 ### 获取群文件系统信息
终结点: `/get_group_file_system_info` 终结点: `/get_group_file_system_info`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----- | ---- | | ---------- | ----- | ---- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------- | ----- | ---------- | | ------------- | ----- | ---------- |
| `file_count` | int32 | 文件总数 | | `file_count` | int32 | 文件总数 |
| `limit_count` | int32 | 文件上限 | | `limit_count` | int32 | 文件上限 |
| `used_space` | int64 | 已使用空间 | | `used_space` | int64 | 已使用空间 |
| `total_space` | int64 | 空间上限 | | `total_space` | int64 | 空间上限 |
### 获取群根目录文件列表 ### 获取群根目录文件列表
@ -570,18 +627,18 @@ Type: `tts`
终结点: `/get_group_root_files` 终结点: `/get_group_root_files`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ----- | ---- | | ---------- | ----- | ---- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| --------- | -------- | ---------- | | --------- | -------- | ---------- |
| `files` | File[] | 文件列表 | | `files` | File[] | 文件列表 |
| `folders` | Folder[] | 文件夹列表 | | `folders` | Folder[] | 文件夹列表 |
### 获取群子目录文件列表 ### 获取群子目录文件列表
> `File` 和 `Folder` 对象信息请参考最下方 > `File` 和 `Folder` 对象信息请参考最下方
@ -589,19 +646,19 @@ Type: `tts`
终结点: `/get_group_files_by_folder` 终结点: `/get_group_files_by_folder`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ----------- | ------ | --------------------------- | | ----------- | ------ | --------------------------- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
| `folder_id` | string | 文件夹ID 参考 `Folder` 对象 | | `folder_id` | string | 文件夹ID 参考 `Folder` 对象 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| --------- | -------- | ---------- | | --------- | -------- | ---------- |
| `files` | File[] | 文件列表 | | `files` | File[] | 文件列表 |
| `folders` | Folder[] | 文件夹列表 | | `folders` | Folder[] | 文件夹列表 |
### 获取群文件资源链接 ### 获取群文件资源链接
> `File` 和 `Folder` 对象信息请参考最下方 > `File` 和 `Folder` 对象信息请参考最下方
@ -609,48 +666,79 @@ Type: `tts`
终结点: `/get_group_file_url` 终结点: `/get_group_file_url`
**参数** **参数**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------- | ------ | ------------------------- | | ---------- | ------ | ------------------------- |
| `group_id` | int64 | 群号 | | `group_id` | int64 | 群号 |
| `file_id` | string | 文件ID 参考 `File` 对象 | | `file_id` | string | 文件ID 参考 `File` 对象 |
| `busid` | int32 | 文件类型 参考 `File` 对象 | | `busid` | int32 | 文件类型 参考 `File` 对象 |
**响应数据** **响应数据**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ----- | ------ | ------------ | | ----- | ------ | ------------ |
| `url` | string | 文件下载链接 | | `url` | string | 文件下载链接 |
**File** **File**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ---------------- | ------ | ---------------------- | | ---------------- | ------ | ---------------------- |
| `file_id` | string | 文件ID | | `file_id` | string | 文件ID |
| `file_name` | string | 文件名 | | `file_name` | string | 文件名 |
| `busid` | int32 | 文件类型 | | `busid` | int32 | 文件类型 |
| `file_size` | int64 | 文件大小 | | `file_size` | int64 | 文件大小 |
| `upload_time` | int64 | 上传时间 | | `upload_time` | int64 | 上传时间 |
| `dead_time` | int64 | 过期时间,永久文件恒为0 | | `dead_time` | int64 | 过期时间,永久文件恒为0 |
| `modify_time` | int64 | 最后修改时间 | | `modify_time` | int64 | 最后修改时间 |
| `download_times` | int32 | 下载次数 | | `download_times` | int32 | 下载次数 |
| `uploader` | int64 | 上传者ID | | `uploader` | int64 | 上传者ID |
| `uploader_name` | string | 上传者名字 | | `uploader_name` | string | 上传者名字 |
**Folder** **Folder**
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| ------------------ | ------ | ---------- | | ------------------ | ------ | ---------- |
| `folder_id` | string | 文件夹ID | | `folder_id` | string | 文件夹ID |
| `folder_name` | string | 文件名 | | `folder_name` | string | 文件名 |
| `create_time` | int64 | 创建时间 | | `create_time` | int64 | 创建时间 |
| `creator` | int64 | 创建者 | | `creator` | int64 | 创建者 |
| `creator_name` | string | 创建者名字 | | `creator_name` | string | 创建者名字 |
| `total_file_count` | int32 | 子文件数量 | | `total_file_count` | int32 | 子文件数量 |
### 获取状态
终结点: `/get_status`
**响应数据**
| 字段 | 类型 | 说明 |
| ----------------- | ---------- | ------------------------------- |
| `app_initialized` | bool | 原 `CQHTTP` 字段, 恒定为 `true` |
| `app_enabled` | bool | 原 `CQHTTP` 字段, 恒定为 `true` |
| `plugins_good` | bool | 原 `CQHTTP` 字段, 恒定为 `true` |
| `app_good` | bool | 原 `CQHTTP` 字段, 恒定为 `true` |
| `online` | bool | 表示BOT是否在线 |
| `goold` | bool | 同 `online` |
| `stat` | Statistics | 运行统计 |
**Statistics**
| 字段 | 类型 | 说明 |
| ------------------ | ------ | ---------------- |
| `packet_received` | uint64 | 收到的数据包总数 |
| `packet_sent` | uint64 | 发送的数据包总数 |
| `packet_lost` | uint32 | 数据包丢失总数 |
| `message_received` | uint64 | 接受信息总数 |
| `message_sent` | uint64 | 发送信息总数 |
| `disconnect_times` | uint32 | TCP链接断开次数 |
| `lost_times` | uint32 | 账号掉线次数 |
> 注意: 所有统计信息都将在重启后重制
## 事件 ## 事件
#### 群消息撤回 ### 群消息撤回
**上报数据** **上报数据**
@ -663,7 +751,7 @@ Type: `tts`
| `operator_id` | int64 | | 操作者id | | `operator_id` | int64 | | 操作者id |
| `message_id` | int64 | | 被撤回的消息id | | `message_id` | int64 | | 被撤回的消息id |
#### 好友消息撤回 ### 好友消息撤回
**上报数据** **上报数据**
@ -674,7 +762,7 @@ Type: `tts`
| `user_id` | int64 | | 好友id | | `user_id` | int64 | | 好友id |
| `message_id` | int64 | | 被撤回的消息id | | `message_id` | int64 | | 被撤回的消息id |
#### 群内戳一戳 ### 群内戳一戳
> 注意:此事件无法在平板和手表协议上触发 > 注意:此事件无法在平板和手表协议上触发
@ -689,7 +777,7 @@ Type: `tts`
| `user_id` | int64 | | 发送者id | | `user_id` | int64 | | 发送者id |
| `target_id` | int64 | | 被戳者id | | `target_id` | int64 | | 被戳者id |
#### 群红包运气王提示 ### 群红包运气王提示
> 注意:此事件无法在平板和手表协议上触发 > 注意:此事件无法在平板和手表协议上触发
@ -704,7 +792,7 @@ Type: `tts`
| `user_id` | int64 | | 红包发送者id | | `user_id` | int64 | | 红包发送者id |
| `target_id` | int64 | | 运气王id | | `target_id` | int64 | | 运气王id |
#### 群成员荣誉变更提示 ### 群成员荣誉变更提示
> 注意:此事件无法在平板和手表协议上触发 > 注意:此事件无法在平板和手表协议上触发
@ -719,7 +807,7 @@ Type: `tts`
| `user_id` | int64 | | 成员id | | `user_id` | int64 | | 成员id |
| `honor_type` | string | `talkative:龙王` `performer:群聊之火` `emotion:快乐源泉` | 荣誉类型 | | `honor_type` | string | `talkative:龙王` `performer:群聊之火` `emotion:快乐源泉` | 荣誉类型 |
#### 群成员名片更新 ### 群成员名片更新
> 注意: 此事件不保证时效性,仅在收到消息时校验卡片 > 注意: 此事件不保证时效性,仅在收到消息时校验卡片
@ -736,7 +824,7 @@ Type: `tts`
> PS: 当名片为空时 `card_xx` 字段为空字符串, 并不是昵称 > PS: 当名片为空时 `card_xx` 字段为空字符串, 并不是昵称
#### 接收到离线文件 ### 接收到离线文件
**上报数据** **上报数据**
@ -753,4 +841,4 @@ Type: `tts`
| ------ | ------ | -------- | -------- | | ------ | ------ | -------- | -------- |
| `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,13 +119,11 @@ enable ws?(Y/n)
*注:可以使用*`go env -w GOPROXY=https://goproxy.cn,direct`*来加速国内依赖安装速度* *注:可以使用*`go env -w GOPROXY=https://goproxy.cn,direct`*来加速国内依赖安装速度*
*注:此时构建后的文件名为*`go-cqhttp`(Linux)或`go-cqhttp.exe`(Windows)
## 更新 ## 更新
### 方法一 ### 方法一
从[release] (https://github.com/Mrs4s/go-cqhttp/releases)界面下载最新版本的go-cqhttp 从[release](https://github.com/Mrs4s/go-cqhttp/releases)界面下载最新版本的go-cqhttp
并替换之前的版本 并替换之前的版本
### 方法二 ### 方法二
@ -144,4 +144,4 @@ enable ws?(Y/n)
- `https://github.rc1844.workers.dev` - `https://github.rc1844.workers.dev`
#### linux #### linux
方法与windows基本一致`go-cqhttp.exe` 替换为 `./go-cqhttp`即可 方法与windows基本一致`go-cqhttp.exe` 替换为 `./go-cqhttp`即可

View File

@ -1,14 +1,139 @@
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"`
@ -28,6 +153,7 @@ type JsonConfig struct {
} `json:"_rate_limit"` } `json:"_rate_limit"`
IgnoreInvalidCQCode bool `json:"ignore_invalid_cqcode"` IgnoreInvalidCQCode bool `json:"ignore_invalid_cqcode"`
ForceFragmented bool `json:"force_fragmented"` ForceFragmented bool `json:"force_fragmented"`
ProxyRewrite string `json:"proxy_rewrite"`
HeartbeatInterval time.Duration `json:"heartbeat_interval"` HeartbeatInterval time.Duration `json:"heartbeat_interval"`
HttpConfig *GoCQHttpConfig `json:"http_config"` HttpConfig *GoCQHttpConfig `json:"http_config"`
WSConfig *GoCQWebsocketConfig `json:"ws_config"` WSConfig *GoCQWebsocketConfig `json:"ws_config"`
@ -144,22 +270,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,6 +1,7 @@
package global package global
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"regexp" "regexp"
"strings" "strings"
@ -9,17 +10,37 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
type Filter interface { type MSG map[string]interface{}
Eval(payload gjson.Result) bool
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 MSG{}
} }
type OperationNode struct { func (m MSG) String() string {
if str,ok:=m["__str__"];ok {
return fmt.Sprint(str)
}
str, _ := json.MarshalToString(m)
return str
}
type Filter interface {
Eval(payload MSG) bool
}
type operationNode struct {
key string key string
filter Filter filter Filter
} }
type NotOperator struct { type NotOperator struct {
operand_ Filter operand Filter
} }
func notOperatorConstruct(argument gjson.Result) *NotOperator { func notOperatorConstruct(argument gjson.Result) *NotOperator {
@ -27,16 +48,16 @@ func notOperatorConstruct(argument gjson.Result) *NotOperator {
panic("the argument of 'not' operator must be an object") panic("the argument of 'not' operator must be an object")
} }
op := new(NotOperator) op := new(NotOperator)
op.operand_ = Generate("and", argument) op.operand = Generate("and", argument)
return op return op
} }
func (notOperator NotOperator) Eval(payload gjson.Result) bool { func (op *NotOperator) Eval(payload MSG) bool {
return !(notOperator.operand_).Eval(payload) return !op.operand.Eval(payload)
} }
type AndOperator struct { type AndOperator struct {
operands []OperationNode operands []operationNode
} }
func andOperatorConstruct(argument gjson.Result) *AndOperator { func andOperatorConstruct(argument gjson.Result) *AndOperator {
@ -51,26 +72,26 @@ func andOperatorConstruct(argument gjson.Result) *AndOperator {
// "bar": "baz" // "bar": "baz"
// } // }
opKey := key.Str[1:] opKey := key.Str[1:]
op.operands = append(op.operands, OperationNode{"", Generate(opKey, value)}) op.operands = append(op.operands, operationNode{"", Generate(opKey, value)})
} else if value.IsObject() { } else if value.IsObject() {
// is an normal key with an object as the value // is an normal key with an object as the value
// "foo": { // "foo": {
// ".bar": "baz" // ".bar": "baz"
// } // }
opKey := key.String() opKey := key.String()
op.operands = append(op.operands, OperationNode{opKey, Generate("and", value)}) op.operands = append(op.operands, operationNode{opKey, Generate("and", value)})
} else { } else {
// is an normal key with a non-object as the value // is an normal key with a non-object as the value
// "foo": "bar" // "foo": "bar"
opKey := key.String() opKey := key.String()
op.operands = append(op.operands, OperationNode{opKey, Generate("eq", value)}) op.operands = append(op.operands, operationNode{opKey, Generate("eq", value)})
} }
return true return true
}) })
return op return op
} }
func (andOperator *AndOperator) Eval(payload gjson.Result) bool { func (andOperator *AndOperator) Eval(payload MSG) bool {
res := true res := true
for _, operand := range andOperator.operands { for _, operand := range andOperator.operands {
@ -106,11 +127,10 @@ func orOperatorConstruct(argument gjson.Result) *OrOperator {
return op return op
} }
func (orOperator OrOperator) Eval(payload gjson.Result) bool { func (op *OrOperator) Eval(payload MSG) bool {
res := false res := false
for _, operand := range orOperator.operands { for _, operand := range op.operands {
res = res || operand.Eval(payload) res = res || operand.Eval(payload)
if res == true { if res == true {
break break
} }
@ -119,35 +139,36 @@ func (orOperator OrOperator) Eval(payload gjson.Result) bool {
} }
type EqualOperator struct { type EqualOperator struct {
value gjson.Result operand string
} }
func equalOperatorConstruct(argument gjson.Result) *EqualOperator { func equalOperatorConstruct(argument gjson.Result) *EqualOperator {
op := new(EqualOperator) op := new(EqualOperator)
op.value = argument op.operand = argument.String()
return op return op
} }
func (equalOperator EqualOperator) Eval(payload gjson.Result) bool { func (op *EqualOperator) Eval(payload MSG) bool {
return payload.String() == equalOperator.value.String() return payload.String() == op.operand
} }
type NotEqualOperator struct { type NotEqualOperator struct {
value gjson.Result operand string
} }
func notEqualOperatorConstruct(argument gjson.Result) *NotEqualOperator { func notEqualOperatorConstruct(argument gjson.Result) *NotEqualOperator {
op := new(NotEqualOperator) op := new(NotEqualOperator)
op.value = argument op.operand = argument.String()
return op return op
} }
func (notEqualOperator NotEqualOperator) Eval(payload gjson.Result) bool { func (op *NotEqualOperator) Eval(payload MSG) bool {
return !(payload.String() == notEqualOperator.value.String()) return !(payload.String() == op.operand)
} }
type InOperator struct { type InOperator struct {
operand gjson.Result operandString string
operandArray []string
} }
func inOperatorConstruct(argument gjson.Result) *InOperator { func inOperatorConstruct(argument gjson.Result) *InOperator {
@ -155,20 +176,29 @@ func inOperatorConstruct(argument gjson.Result) *InOperator {
panic("the argument of 'in' operator must be an array or a string") panic("the argument of 'in' operator must be an array or a string")
} }
op := new(InOperator) op := new(InOperator)
op.operand = argument if argument.IsArray() {
op.operandArray = []string{}
argument.ForEach(func(_, value gjson.Result) bool {
op.operandArray = append(op.operandArray, value.String())
return true
})
} else {
op.operandString = argument.String()
}
return op return op
} }
func (inOperator InOperator) Eval(payload gjson.Result) bool { func (op *InOperator) Eval(payload MSG) bool {
if inOperator.operand.IsArray() { payloadStr := payload.String()
res := false if op.operandArray != nil {
inOperator.operand.ForEach(func(key, value gjson.Result) bool { for _, value := range op.operandArray {
res = res || value.String() == payload.String() if value == payloadStr {
return true return true
}) }
return res }
return false
} }
return strings.Contains(inOperator.operand.String(), payload.String()) return strings.Contains(op.operandString, payloadStr)
} }
type ContainsOperator struct { type ContainsOperator struct {
@ -184,15 +214,12 @@ func containsOperatorConstruct(argument gjson.Result) *ContainsOperator {
return op return op
} }
func (containsOperator ContainsOperator) Eval(payload gjson.Result) bool { func (op *ContainsOperator) Eval(payload MSG) bool {
if payload.IsObject() || payload.IsArray() { return strings.Contains(payload.String(), op.operand)
return false
}
return strings.Contains(payload.String(), containsOperator.operand)
} }
type RegexOperator struct { type RegexOperator struct {
regex string regex *regexp.Regexp
} }
func regexOperatorConstruct(argument gjson.Result) *RegexOperator { func regexOperatorConstruct(argument gjson.Result) *RegexOperator {
@ -200,12 +227,12 @@ func regexOperatorConstruct(argument gjson.Result) *RegexOperator {
panic("the argument of 'regex' operator must be a string") panic("the argument of 'regex' operator must be a string")
} }
op := new(RegexOperator) op := new(RegexOperator)
op.regex = argument.String() op.regex = regexp.MustCompile(argument.String())
return op return op
} }
func (containsOperator RegexOperator) Eval(payload gjson.Result) bool { func (op *RegexOperator) Eval(payload MSG) bool {
matched, _ := regexp.MatchString(containsOperator.regex, payload.String()) matched := op.regex.MatchString(payload.String())
return matched return matched
} }
@ -232,7 +259,7 @@ func Generate(opName string, argument gjson.Result) Filter {
} }
} }
var EventFilter = new(Filter) var EventFilter Filter = nil
func BootFilter() { func BootFilter() {
defer func() { defer func() {
@ -247,6 +274,6 @@ func BootFilter() {
if err != nil { if err != nil {
panic(err) panic(err)
} else { } else {
*EventFilter = Generate("and", gjson.ParseBytes(f)) EventFilter = Generate("and", gjson.ParseBytes(f))
} }
} }

View File

@ -43,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) {

View File

@ -5,7 +5,9 @@ import (
"compress/gzip" "compress/gzip"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net"
"net/http" "net/http"
"net/url"
"strings" "strings"
"time" "time"
@ -14,8 +16,28 @@ import (
var client = &http.Client{ var client = &http.Client{
Timeout: time.Second * 15, Timeout: time.Second * 15,
Transport: &http.Transport{
Proxy: func(request *http.Request) (u *url.URL, e error) {
if Proxy == "" {
return http.ProxyFromEnvironment(request)
}
return url.Parse(Proxy)
},
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
} }
var Proxy string
func GetBytes(url string) ([]byte, error) { func GetBytes(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
if err != nil { if err != nil {

10
go.mod
View File

@ -1,26 +1,28 @@
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-20201117154121-989187125900 github.com/Mrs4s/MiraiGo v0.0.0-20201209180326-c07a8a9c8a83
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-contrib/pprof v1.3.0
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
github.com/lestrrat-go/strftime v1.0.3 // indirect github.com/lestrrat-go/strftime v1.0.3 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.7.0 github.com/sirupsen/logrus v1.7.0
github.com/syndtr/goleveldb v1.0.0 github.com/syndtr/goleveldb v1.0.0
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
github.com/tidwall/gjson v1.6.3 github.com/tidwall/gjson v1.6.3
github.com/wdvxdr1123/go-silk v0.0.0-20201007123416-b982fd3d91d6 github.com/wdvxdr1123/go-silk v0.0.0-20201203155442-67728040c843
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e
) )

18
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-20201117154121-989187125900 h1:xnx3dH7hgZ/Z4k33EhKzBmQhwASJ5bvsorqPhO0DWbc= github.com/Mrs4s/MiraiGo v0.0.0-20201209180326-c07a8a9c8a83 h1:9mCmMOTDlQ5reudlum8JAjmrsqSdG0692/BgOIuPIhs=
github.com/Mrs4s/MiraiGo v0.0.0-20201117154121-989187125900/go.mod h1:pAsWtMIwqkBXr5DkUpTIHoWQJNduVnX9WSBPmPvkuCs= github.com/Mrs4s/MiraiGo v0.0.0-20201209180326-c07a8a9c8a83/go.mod h1:J1zaJWyeX7hQIPpOobqb8opxTNPbguotudPPrHJMoDM=
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=
@ -25,9 +25,12 @@ github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55 h1:XYzSdCbkzOC0F
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55/go.mod h1:6mmzY2kW1TOOrVy+r41Za2MxXM+hhqTtY3oBKd2AgFA= github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55/go.mod h1:6mmzY2kW1TOOrVy+r41Za2MxXM+hhqTtY3oBKd2AgFA=
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f h1:wrYrQttPS8FHIRSlsrcuKazukx/xqO/PpLZzZXsF+EA= github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f h1:wrYrQttPS8FHIRSlsrcuKazukx/xqO/PpLZzZXsF+EA=
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f/go.mod h1:D5ao98qkA6pxftxoqzibIBBrLSUli+kYnJqrgBf9cIA= github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f/go.mod h1:D5ao98qkA6pxftxoqzibIBBrLSUli+kYnJqrgBf9cIA=
github.com/gin-contrib/pprof v1.3.0 h1:G9eK6HnbkSqDZBYbzG4wrjCsA4e+cvYAHUZw6W+W9K0=
github.com/gin-contrib/pprof v1.3.0/go.mod h1:waMjT1H9b179t3CxuG1cV3DHpga6ybizwfBaM5OXaB0=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do= github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
github.com/gin-gonic/gin v1.6.2/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
@ -67,9 +70,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 +93,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=
@ -114,7 +123,6 @@ github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFd
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ= 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 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/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816/go.mod h1:tzym/CEb5jnFI+Q0k4Qq3+LvRF4gO3E2pxS8fHP8jcA=
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
github.com/tidwall/gjson v1.6.3 h1:aHoiiem0dr7GHkW001T1SMTJ7X5PvyekH5WX0whWGnI= github.com/tidwall/gjson v1.6.3 h1:aHoiiem0dr7GHkW001T1SMTJ7X5PvyekH5WX0whWGnI=
github.com/tidwall/gjson v1.6.3/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0= github.com/tidwall/gjson v1.6.3/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc= github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
@ -125,8 +133,8 @@ github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/wdvxdr1123/go-silk v0.0.0-20201007123416-b982fd3d91d6 h1:lX18MCdNzT2zIi7K02x4C5cPkDXpL+wCb1YTAMXjLWQ= github.com/wdvxdr1123/go-silk v0.0.0-20201203155442-67728040c843 h1:PRhoPwoTPcB9IDtAj7bEqeGS3SCxZ4xs7/IH35P24jQ=
github.com/wdvxdr1123/go-silk v0.0.0-20201007123416-b982fd3d91d6/go.mod h1:5q9LFlBr+yX/J8Jd/9wHdXwkkjFkNyQIS7kX2Lgx/Zs= github.com/wdvxdr1123/go-silk v0.0.0-20201203155442-67728040c843/go.mod h1:5q9LFlBr+yX/J8Jd/9wHdXwkkjFkNyQIS7kX2Lgx/Zs=
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 h1:4UJw9if55Fu3HOwbfcaQlJ27p3oeJU2JZqoeT3ITJQk= github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 h1:4UJw9if55Fu3HOwbfcaQlJ27p3oeJU2JZqoeT3ITJQk=
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189/go.mod h1:rIrm5geMiBhPQkdfUm8gDFi/WiHneOp1i9KjmJqc+9I= github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189/go.mod h1:rIrm5geMiBhPQkdfUm8gDFi/WiHneOp1i9KjmJqc+9I=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=

45
main.go
View File

@ -2,10 +2,8 @@ package main
import ( import (
"bufio" "bufio"
"context"
"crypto/md5" "crypto/md5"
"encoding/base64" "encoding/base64"
"encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -29,12 +27,15 @@ import (
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/getlantern/go-update" "github.com/getlantern/go-update"
jsoniter "github.com/json-iterator/go"
rotatelogs "github.com/lestrrat-go/file-rotatelogs" 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"
easy "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",
@ -66,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 {
@ -88,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")
} }
@ -122,8 +123,10 @@ func main() {
} }
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)
@ -149,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
} }
@ -209,6 +214,10 @@ func main() {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
log.Warnf("已开启Debug模式.") log.Warnf("已开启Debug模式.")
log.Debugf("开发交流群: 192548878") log.Debugf("开发交流群: 192548878")
server.Debug = true
if conf.WebUi == nil || !conf.WebUi.Enabled {
log.Warnf("警告: 在Debug模式下未启用WebUi服务, 将无法进行性能分析.")
}
} }
if !global.PathExists("device.json") { if !global.PathExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.") log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
@ -228,7 +237,7 @@ 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("加密时出现问题.")
} }
@ -236,19 +245,19 @@ func main() {
if conf.PasswordEncrypted != "" { if conf.PasswordEncrypted != "" {
if strKey == "" { if strKey == "" {
log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)") log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)")
ctx := context.Background() cancel := make(chan struct{}, 1)
go func(ctx context.Context) { go func() {
select { select {
case <-ctx.Done(): case <-cancel:
return return
case <-time.After(time.Second * 45): case <-time.After(time.Second * 45):
log.Infof("解密key输入超时") log.Infof("解密key输入超时")
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
os.Exit(0) os.Exit(0)
} }
}(ctx) }()
strKey, _ = console.ReadString('\n') strKey, _ = console.ReadString('\n')
ctx.Done() cancel <- struct{}{}
} else { } else {
log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.") log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.")
} }
@ -314,10 +323,7 @@ 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") global.Proxy = conf.ProxyRewrite
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 r := server.Restart
@ -328,7 +334,6 @@ func main() {
b.Release() b.Release()
case <-r: case <-r:
log.Info("正在重启中...") log.Info("正在重启中...")
server.HttpServer.ShutDown()
defer b.Release() defer b.Release()
restart(arg) restart(arg)
} }

View File

@ -4,8 +4,8 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"encoding/json"
"fmt" "fmt"
"github.com/gin-contrib/pprof"
"image" "image"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -19,11 +19,14 @@ import (
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
jsoniter "github.com/json-iterator/go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
asciiart "github.com/yinghau76/go-ascii-art" 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)
@ -75,7 +78,12 @@ func (s *webServer) Run(addr string, cli *client.QQClient) *coolq.CQBot {
go func() { go func() {
//开启端口监听 //开启端口监听
if s.Conf.WebUi.Enabled { if s.Conf.WebUi != nil && s.Conf.WebUi.Enabled {
if Debug {
pprof.Register(s.engine)
log.Debugf("pprof 性能分析服务已启动在 http://%v/debug/pprof, 如果有任何性能问题请下载报告并提交给开发者", addr)
time.Sleep(time.Second * 3)
}
log.Infof("Admin API 服务器已启动: %v", addr) log.Infof("Admin API 服务器已启动: %v", addr)
err := s.engine.Run(addr) err := s.engine.Run(addr)
if err != nil { if err != nil {
@ -110,6 +118,7 @@ func (s *webServer) Dologin() {
cli := s.Cli cli := s.Cli
cli.AllowSlider = true cli.AllowSlider = true
rsp, err := cli.Login() rsp, err := cli.Login()
count := 0
for { for {
global.Check(err) global.Check(err)
var text string var text string
@ -130,7 +139,7 @@ func (s *webServer) Dologin() {
_ = ioutil.WriteFile("captcha.jpg", rsp.CaptchaImage, 0644) _ = ioutil.WriteFile("captcha.jpg", rsp.CaptchaImage, 0644)
img, _, _ := image.Decode(bytes.NewReader(rsp.CaptchaImage)) img, _, _ := image.Decode(bytes.NewReader(rsp.CaptchaImage))
fmt.Println(asciiart.New("image", img).Art) fmt.Println(asciiart.New("image", img).Art)
if conf.WebUi.WebInput { if conf.WebUi != nil && conf.WebUi.WebInput {
log.Warnf("请输入验证码 (captcha.jpg) (http://%s:%d/admin/do_web_write 输入)", conf.WebUi.Host, conf.WebUi.WebUiPort) log.Warnf("请输入验证码 (captcha.jpg) (http://%s:%d/admin/do_web_write 输入)", conf.WebUi.Host, conf.WebUi.WebUiPort)
text = <-WebInput text = <-WebInput
} else { } else {
@ -176,7 +185,7 @@ func (s *webServer) Dologin() {
return return
case client.UnsafeDeviceError: case client.UnsafeDeviceError:
log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证并重启Bot.", rsp.VerifyUrl) log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证并重启Bot.", rsp.VerifyUrl)
if conf.WebUi.WebInput { if conf.WebUi != nil && conf.WebUi.WebInput {
log.Infof(" (http://%s:%d/admin/do_web_write 确认后继续)....", conf.WebUi.Host, conf.WebUi.WebUiPort) log.Infof(" (http://%s:%d/admin/do_web_write 确认后继续)....", conf.WebUi.Host, conf.WebUi.WebUiPort)
text = <-WebInput text = <-WebInput
} else { } else {
@ -191,6 +200,14 @@ func (s *webServer) Dologin() {
if strings.Contains(msg, "版本") { if strings.Contains(msg, "版本") {
msg = "密码错误或账号被冻结" msg = "密码错误或账号被冻结"
} }
if strings.Contains(msg, "上网环境") && count < 5 {
cli.Disconnect()
rsp, err = cli.Login()
count++
log.Warnf("错误: 当前上网环境异常. 将更换服务器并重试. 如果频繁遇到此问题请打开设备锁.")
time.Sleep(time.Second)
continue
}
log.Warnf("登录失败: %v", msg) log.Warnf("登录失败: %v", msg)
log.Infof("按 Enter 继续....") log.Infof("按 Enter 继续....")
readLine() readLine()
@ -283,7 +300,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
} }
@ -301,6 +318,10 @@ func AuthMiddleWare() gin.HandlerFunc {
if c.Request.Method == "OPTIONS" { if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent) c.AbortWithStatus(http.StatusNoContent)
} }
if strings.Contains(c.Request.URL.Path, "debug") {
c.Next()
return
}
// 处理请求 // 处理请求
if c.Request.Method != "GET" && c.Request.Method != "POST" { if c.Request.Method != "GET" && c.Request.Method != "POST" {
log.Warnf("已拒绝客户端 %v 的请求: 方法错误", c.Request.RemoteAddr) log.Warnf("已拒绝客户端 %v 的请求: 方法错误", c.Request.RemoteAddr)
@ -475,9 +496,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{}))
@ -500,9 +521,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{}))
@ -520,9 +541,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{}))
@ -542,9 +563,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{}))
@ -557,13 +578,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

@ -35,6 +35,7 @@ type httpClient struct {
} }
var HttpServer = &httpServer{} var HttpServer = &httpServer{}
var Debug = false
func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) { func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
@ -93,13 +94,6 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
os.Exit(1) os.Exit(1)
} }
//err := s.engine.Run(addr)
//if err != nil {
// log.Error(err)
// log.Infof("请检查端口是否被占用.")
// time.Sleep(time.Second * 5)
// os.Exit(1)
//}
}() }()
} }
@ -177,7 +171,8 @@ func GetGroupList(s *httpServer, c *gin.Context) {
func GetGroupInfo(s *httpServer, c *gin.Context) { func GetGroupInfo(s *httpServer, c *gin.Context) {
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64) gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
c.JSON(200, s.bot.CQGetGroupInfo(gid)) nc := getParamOrDefault(c, "no_cache", "false")
c.JSON(200, s.bot.CQGetGroupInfo(gid, nc == "true"))
} }
func GetGroupMemberList(s *httpServer, c *gin.Context) { func GetGroupMemberList(s *httpServer, c *gin.Context) {
@ -308,7 +303,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) {
@ -517,6 +513,7 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
"set_group_portrait": SetGroupPortrait, "set_group_portrait": SetGroupPortrait,
".handle_quick_operation": HandleQuickOperation, ".handle_quick_operation": HandleQuickOperation,
".ocr_image": OcrImage, ".ocr_image": OcrImage,
"ocr_image": OcrImage,
".get_word_slices": GetWordSlices, ".get_word_slices": GetWordSlices,
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"net/http" "net/http"
"runtime/debug"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -316,7 +317,7 @@ func (s *websocketServer) listenApi(c *websocketConn) {
func (c *websocketConn) handleRequest(bot *coolq.CQBot, payload []byte) { func (c *websocketConn) handleRequest(bot *coolq.CQBot, payload []byte) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Printf("处置WS命令时发生无法恢复的异常%v", err) log.Printf("处置WS命令时发生无法恢复的异常%v\n%s", err, debug.Stack())
c.Close() c.Close()
} }
}() }()
@ -370,7 +371,7 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
return bot.CQGetGroupList(p.Get("no_cache").Bool()) return bot.CQGetGroupList(p.Get("no_cache").Bool())
}, },
"get_group_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "get_group_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupInfo(p.Get("group_id").Int()) return bot.CQGetGroupInfo(p.Get("group_id").Int(), p.Get("no_cache").Bool())
}, },
"get_group_member_list": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "get_group_member_list": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupMemberList(p.Get("group_id").Int(), p.Get("no_cache").Bool()) return bot.CQGetGroupMemberList(p.Get("group_id").Int(), p.Get("no_cache").Bool())
@ -433,7 +434,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 {
@ -532,6 +533,9 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
".ocr_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { ".ocr_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQOcrImage(p.Get("image").Str) return bot.CQOcrImage(p.Get("image").Str)
}, },
"ocr_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQOcrImage(p.Get("image").Str)
},
".get_word_slices": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { ".get_word_slices": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetWordSlices(p.Get("content").Str) return bot.CQGetWordSlices(p.Get("content").Str)
}, },