Compare commits

...

553 Commits

Author SHA1 Message Date
github-actions[bot]
58d8815f39 🔖 Release 2.0.0-beta.4 2022-06-20 11:40:59 +00:00
Ju4tCode
b80083fed5 🔖 bump version 2.0.0-beta.4 (#1056) 2022-06-20 19:29:56 +08:00
github-actions[bot]
4ba17d900a 📝 Update changelog 2022-06-20 07:53:30 +00:00
Ju4tCode
f11970132c Fix: 修复 MessageSegment 在有额外数据时报错 (#1055) 2022-06-20 15:52:12 +08:00
github-actions[bot]
c91c9380a7 📝 Update changelog 2022-06-20 07:51:00 +00:00
Ju4tCode
06ee47edcd Feature: 添加插件元信息定义 (#1046) 2022-06-20 15:49:53 +08:00
github-actions[bot]
a82ce00a4b 📝 Update changelog 2022-06-19 01:25:55 +00:00
AquamarineCyan
e0902eeb58 🍻 publish plugin 历史上的今天 (#1048) 2022-06-19 09:24:36 +08:00
github-actions[bot]
b754ac2fbc 📝 Update changelog 2022-06-18 07:59:15 +00:00
Special-Week
1ae0a654bf 🍻 publish plugin 智能回复 (#1053) 2022-06-18 15:58:10 +08:00
github-actions[bot]
b85348f648 📝 Update changelog 2022-06-18 06:49:01 +00:00
Ju4tCode
7b06469a30 🐛 fix env var not override dotenv file (#1052) 2022-06-18 14:47:42 +08:00
github-actions[bot]
a62a49d477 📝 Update changelog 2022-06-18 03:13:55 +00:00
Special-Week
e2f96a0b5c 🍻 publish plugin nonebot_plugin_setu4 (#1050) 2022-06-18 11:12:40 +08:00
github-actions[bot]
28c22b7511 📝 Update changelog 2022-06-16 03:43:18 +00:00
nikissXI
c027e4d2ce 🍻 publish bot nya_bot (#1044) 2022-06-16 11:42:09 +08:00
github-actions[bot]
e38bb2b530 📝 Update changelog 2022-06-06 02:26:03 +00:00
18870
19a9a3c3c5 🍻 publish plugin 命令重启机器人 (#1037) 2022-06-06 10:24:55 +08:00
github-actions[bot]
4c8f5059db 📝 Update changelog 2022-06-04 11:34:00 +00:00
ZMXC01
9ab1acf1e7 🍻 publish plugin 青年大学习自动提交 (#1035) 2022-06-04 19:32:59 +08:00
github-actions[bot]
175acd38eb 📝 Update changelog 2022-06-03 13:00:11 +00:00
BlueGlassBlock
4241eb538c 🎨 Feature: 日志记录自动检测终端是否支持彩色 (#1034)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-06-03 20:59:04 +08:00
github-actions[bot]
c55b32b9f9 📝 Update changelog 2022-06-03 02:42:41 +00:00
bingqiu456
2082e5f5c2 🍻 publish plugin 疫情小助手 (#1032) 2022-06-03 10:41:18 +08:00
SEAFHMC
8485a356e7 🍻 publish plugin 谁艾特我了 (#1030) 2022-06-02 14:48:41 +08:00
dependabot[bot]
f6f70fb435 ⬆️ Bump httpx from 0.22.0 to 0.23.0 (#1029)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-02 11:21:28 +08:00
github-actions[bot]
c3ce4f76d1 📝 Update changelog 2022-06-01 16:37:04 +00:00
benx1n
db90a9ebab 🍻 publish plugin Hikari-战舰世界水表查询 (#1024) 2022-06-02 00:35:51 +08:00
github-actions[bot]
3962a98743 📝 Update changelog 2022-06-01 10:36:51 +00:00
Ju4tCode
3ce23bc593 🍻 publish adapter OneBot V12 (#1026)
Co-authored-by: yanyongyu <yanyongyu@users.noreply.github.com>
2022-06-01 18:35:40 +08:00
github-actions[bot]
3238a82042 📝 Update changelog 2022-05-31 04:36:51 +00:00
axStar
ed1f920088 🍻 publish plugin Warframe时间查询 (#1022) 2022-05-31 12:35:52 +08:00
github-actions[bot]
c34b3439fa 📝 Update changelog 2022-05-30 12:41:17 +00:00
Ju4tCode
bd2225c43c 🍻 publish plugin imagetools (#1020) (#1021)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-05-30 20:40:10 +08:00
github-actions[bot]
381234725e 📝 Update changelog 2022-05-29 02:57:28 +00:00
NumberSir
a5ee6ac401 🍻 publish plugin 明日方舟工具箱 (#1018) 2022-05-29 10:56:14 +08:00
github-actions[bot]
79fd12768d 📝 Update changelog 2022-05-27 09:29:27 +00:00
ASTWY
c0ab86f91b 🍻 publish plugin B站视频伪分享卡片 (#1013) 2022-05-27 17:28:20 +08:00
Ju4tCode
ae21bfdd0e 👷 fix python ci cache path error (#1012)
* 👷 fix python ci cache path error

* 🐛 fix path error

* ✏️ fix typo
2022-05-27 11:25:51 +08:00
github-actions[bot]
6cfa21b15c 📝 Update changelog 2022-05-26 08:36:55 +00:00
Ju4tCode
fa3ed2b58c improve plugin system (#1011) 2022-05-26 16:35:47 +08:00
github-actions[bot]
579839f2a4 📝 Update changelog 2022-05-24 11:34:00 +00:00
shoucandanghehe
daa95d02ac 🍻 publish plugin TETRIS Stats (#1008) 2022-05-24 19:32:52 +08:00
github-actions[bot]
33c261c802 📝 Update changelog 2022-05-24 04:37:58 +00:00
Jigsaw
558e073cfa 📝 Add style guides for document (#1005) 2022-05-24 12:36:59 +08:00
github-actions[bot]
c52637a3b8 📝 Update changelog 2022-05-24 02:43:21 +00:00
kexue-z
e3d1f572ed 🍻 publish plugin 签到插件 (#1006) 2022-05-24 10:42:16 +08:00
github-actions[bot]
af86b96974 📝 Update changelog 2022-05-22 17:16:30 +00:00
snowyfirefly
ddc42f7be8 🍻 publish bot LiteyukiBot-轻雪机器人 (#1002) 2022-05-23 01:15:18 +08:00
github-actions[bot]
41d50641ad 📝 Update changelog 2022-05-22 11:43:31 +00:00
Ju4tCode
6feed0610b 🐛 fix union validation error (#1001) 2022-05-22 19:42:30 +08:00
github-actions[bot]
fe43cc92a5 📝 Update changelog 2022-05-21 14:04:12 +00:00
Ju4tCode
f6fb3b3970 📝 Docs: 更新 require 样例 (#996) 2022-05-21 22:03:19 +08:00
github-actions[bot]
d8ea7f1e6f 📝 Update changelog 2022-05-21 11:42:46 +00:00
Mix
dd55650f0a 📝 Update QQ Channel icon in README.md (#997)
* 📝 Update QQ Channel icon

* 📝  Minimize QQ Channel icon SVG
2022-05-21 19:41:50 +08:00
github-actions[bot]
20f414d0de 📝 Update changelog 2022-05-21 03:18:43 +00:00
AkiraXie
5924f1e7ac 📝 Docs: 调整跨插件访问文档 (#993)
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-05-21 11:17:27 +08:00
github-actions[bot]
2fbd44eef9 📝 Update changelog 2022-05-21 03:15:19 +00:00
kexue-z
0adf4d6934 🍻 publish plugin 数据库连接插件 (#994) 2022-05-21 11:14:19 +08:00
github-actions[bot]
2c91a4c7f1 📝 Update changelog 2022-05-21 02:54:46 +00:00
NumberSir
625c72ab0d 🍻 publish plugin 百度翻译 (#991) 2022-05-21 10:53:47 +08:00
github-actions[bot]
449a2c5f96 📝 Update changelog 2022-05-21 01:15:31 +00:00
AkashiCoin
9e64f3f8ab 🍻 publish plugin MockingBird语音 2022-05-21 09:14:27 +08:00
github-actions[bot]
9b45b77894 🔖 Release 2.0.0-beta.3 2022-05-20 10:21:32 +00:00
Ju4tCode
e890453870 🔖 bump version 2.0.0-beta.3 (#990) 2022-05-20 18:13:50 +08:00
github-actions[bot]
abcea78fcc 📝 Update changelog 2022-05-20 09:35:28 +00:00
Ju4tCode
80594cffb6 🔊 add export deprecation warning (#983) 2022-05-20 17:34:15 +08:00
github-actions[bot]
6d4c5cbc2d 📝 Update changelog 2022-05-20 00:45:25 +00:00
Ju4tCode
d295e9ef6b 🍻 publish plugin imageutils (#985)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-05-20 08:44:16 +08:00
Ju4tCode
2ad46bf97a 🍻 publish bot 屑岛风Bot (#987)
Co-authored-by: kexue-z <kexue-z@users.noreply.github.com>
2022-05-20 08:43:36 +08:00
Ju4tCode
70ddc634f6 Feat: 添加 devcontainer 支持 (#981) 2022-05-19 11:55:56 +08:00
github-actions[bot]
540629aa7c 📝 Update changelog 2022-05-18 23:38:35 +00:00
黯星座
4f4369c712 ✏️ Fix typo in scheduler document (#982) 2022-05-19 07:37:23 +08:00
github-actions[bot]
c6633bc9af 📝 Update changelog 2022-05-18 08:54:30 +00:00
Ju4tCode
1c099b4d13 🍻 publish plugin 摸鱼日历 (#980)
Co-authored-by: A-kirami <A-kirami@users.noreply.github.com>
2022-05-18 16:53:13 +08:00
github-actions[bot]
abe1e29fd9 📝 Update changelog 2022-05-15 05:51:01 +00:00
Ju4tCode
e8b9963ef3 🐛 Fix: 商店搜索失效 (#978) 2022-05-15 13:49:56 +08:00
github-actions[bot]
90f7c153cb 📝 Update changelog 2022-05-15 03:23:24 +00:00
Ju4tCode
983a5930c6 🍻 publish plugin 走迷宫 (#977)
Co-authored-by: EtherLeaF <EtherLeaF@users.noreply.github.com>
2022-05-15 11:22:16 +08:00
github-actions[bot]
ff65f10da9 📝 Update changelog 2022-05-15 02:36:29 +00:00
Ju4tCode
1710d009bb 🍻 publish plugin 语录娱乐 (#973)
Co-authored-by: bingqiu456 <bingqiu456@users.noreply.github.com>
2022-05-15 10:35:20 +08:00
github-actions[bot]
049d988574 📝 Update changelog 2022-05-14 15:16:43 +00:00
Ju4tCode
97fa0b4fe9 🍻 publish plugin 国内新冠疫情数据查询 (#975)
Co-authored-by: nicklly <nicklly@users.noreply.github.com>
2022-05-14 23:15:27 +08:00
github-actions[bot]
cd42385a43 📝 Update changelog 2022-05-14 13:08:07 +00:00
Ju4tCode
56f99b7f0b Feat: 支持 WebSocket 连接同时获取 str 或 bytes (#962) 2022-05-14 21:06:57 +08:00
github-actions[bot]
91c5056c97 📝 Update changelog 2022-05-14 08:55:45 +00:00
Ju4tCode
5e970a291f 🐛 fix di default param eq override (#971) 2022-05-14 16:54:41 +08:00
github-actions[bot]
42a49a20aa 📝 Update changelog 2022-05-13 15:05:36 +00:00
Ju4tCode
a4a329cf87 🍻 publish plugin nonebot_plugin_eventdone (#966)
Co-authored-by: PadorFelice <PadorFelice@users.noreply.github.com>
2022-05-13 23:04:19 +08:00
github-actions[bot]
dc074f35d5 📝 Update changelog 2022-05-13 07:36:59 +00:00
Ju4tCode
591107870e 🍻 publish plugin 幻影坦克图片合成 (#968)
Co-authored-by: RafuiiChan <RafuiiChan@users.noreply.github.com>
2022-05-13 15:35:53 +08:00
github-actions[bot]
94b19b4833 📝 Update changelog 2022-05-13 02:34:52 +00:00
Ju4tCode
1a91371410 🍻 publish plugin 合成字符画(GIF) (#964)
Co-authored-by: RafuiiChan <RafuiiChan@users.noreply.github.com>
2022-05-13 10:33:48 +08:00
github-actions[bot]
a77664297d 📝 Update changelog 2022-05-07 05:17:59 +00:00
StarHeart
b889d2352e 📝 Docs: 添加 QQ 频道链接 (#961)
* 📝 add qq channel badge

* 📝 update qq channel link

* Update README.md

Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-05-07 13:16:43 +08:00
github-actions[bot]
17e09267e0 📝 Update changelog 2022-05-05 02:20:00 +00:00
Ju4tCode
bbf734b2d1 🍻 publish bot ShigureBot (#959)
Co-authored-by: lgc2333 <lgc2333@users.noreply.github.com>
2022-05-05 10:18:41 +08:00
github-actions[bot]
7ab9e85dc0 📝 Update changelog 2022-05-02 11:51:05 +00:00
Ju4tCode
71bfb42fe0 🍻 publish plugin 国际象棋 (#957)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-05-02 19:49:50 +08:00
github-actions[bot]
aeaea54ac1 📝 Update changelog 2022-05-02 05:12:14 +00:00
Ju4tCode
49437daf10 🍻 publish bot Inkar Suki (#955)
Co-authored-by: HornCopper <HornCopper@users.noreply.github.com>
2022-05-02 13:10:56 +08:00
github-actions[bot]
a93401e3b4 📝 Update changelog 2022-05-02 03:01:43 +00:00
MeetWq
e87861983b 🍻 rename nonebot-plugin-chess (#953)
Plugin: nonebot-plugin-chess 改名为 nonebot-plugin-boardgame
2022-05-02 11:00:27 +08:00
github-actions[bot]
2d81d54d93 📝 Update changelog 2022-05-01 02:30:47 +00:00
Ju4tCode
e145d99335 🍻 publish plugin NoneBot2 文档搜索 (#952)
Co-authored-by: MingxuanGame <MingxuanGame@users.noreply.github.com>
2022-05-01 10:29:40 +08:00
github-actions[bot]
7e3a58a0e8 📝 Update changelog 2022-04-30 08:05:57 +00:00
MingxuanGame
11b6e1ba98 📝 Docs: 添加 nonebug 单元测试文档 (#929)
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: StarHeart <starheart233@gmail.com>
2022-04-30 16:04:41 +08:00
github-actions[bot]
34186830ab 📝 Update changelog 2022-04-30 06:45:08 +00:00
Ju4tCode
b98be416e4 🍻 publish plugin 中国象棋 (#949)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-04-30 14:44:04 +08:00
github-actions[bot]
aaae928026 📝 Update changelog 2022-04-30 06:41:36 +00:00
@刘作鱼
1e43b4df10 📝 Add deployment document using PM2 (#853)
* Update deployment.md

重新提交 PM2 部署文档

* ♻️ 📝 Refactor PM2 deplotyment document

* ✏️ Fix typo in PM2 deployment document

* Update deployment.md

fix 表述歧义

* 🚚 copy docs to next version

Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>
Co-authored-by: yanyongyu <42488585+yanyongyu@users.noreply.github.com>
2022-04-30 14:40:25 +08:00
github-actions[bot]
505b4d46d0 📝 Update changelog 2022-04-30 02:00:37 +00:00
Mix
95331bbb22 🐛 Fix MessageTemplate improper behavior when no format spec (#947)
* 🧪 Add a test to figure out bug in #938

* ♻️ 🐛 Refactor rich message template formatting, fix #938
2022-04-30 09:59:23 +08:00
github-actions[bot]
f028575f2f 📝 Update changelog 2022-04-28 10:16:51 +00:00
Ju4tCode
252e3de459 🍻 publish plugin B站视频封面提取 (#946)
Co-authored-by: A-kirami <A-kirami@users.noreply.github.com>
2022-04-28 18:15:34 +08:00
github-actions[bot]
6449b1e9fd 📝 Update changelog 2022-04-28 09:59:12 +00:00
Ju4tCode
5334f11902 🍻 publish plugin 一言 (#944)
Co-authored-by: A-kirami <A-kirami@users.noreply.github.com>
2022-04-28 17:57:50 +08:00
github-actions[bot]
76ffcf14e8 📝 Update changelog 2022-04-28 09:49:41 +00:00
Ju4tCode
c8f25db6f6 🍻 publish plugin 答案之书 (#942)
Co-authored-by: A-kirami <A-kirami@users.noreply.github.com>
2022-04-28 17:48:22 +08:00
github-actions[bot]
4845ca10a4 📝 Update changelog 2022-04-28 09:43:10 +00:00
Ju4tCode
eec27a267a 🍻 publish plugin 支付宝到账语音 (#940)
Co-authored-by: A-kirami <A-kirami@users.noreply.github.com>
2022-04-28 17:41:13 +08:00
github-actions[bot]
3870f0084d 📝 Update changelog 2022-04-24 10:08:06 +00:00
kexue
06b36ec278 📝 Docs: 更新 GitHub Action 部署文档 (#937)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-04-24 18:06:57 +08:00
github-actions[bot]
dcfa25c486 📝 Update changelog 2022-04-20 09:03:15 +00:00
Ju4tCode
14953f5161 🍻 publish plugin nonebot-plugin-dida (#934)
Co-authored-by: TDK1969 <TDK1969@users.noreply.github.com>
2022-04-20 17:02:06 +08:00
github-actions[bot]
16f69b045b 📝 Update changelog 2022-04-20 06:44:40 +00:00
MeetWq
533e99418c Feat: 添加 CommandStart 依赖注入参数 (#915)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: yanyongyu <42488585+yanyongyu@users.noreply.github.com>
2022-04-20 14:43:29 +08:00
github-actions[bot]
f989710cd6 📝 Update changelog 2022-04-18 10:24:27 +00:00
Ju4tCode
e1534f2205 🍻 publish plugin 随机唐可可 (#931)
Co-authored-by: KafCoppelia <KafCoppelia@users.noreply.github.com>
2022-04-18 18:23:13 +08:00
github-actions[bot]
532aee5e71 📝 Update changelog 2022-04-16 15:47:46 +00:00
Nacho
fb047a4987 🍻 change ncm info (#924) 2022-04-16 23:46:37 +08:00
github-actions[bot]
af799aa846 📝 Update changelog 2022-04-16 02:21:11 +00:00
Ju4tCode
91f4daa722 📝 add custom rule guide (#914)
Co-authored-by: StarHeart <starheart233@gmail.com>
2022-04-16 10:20:01 +08:00
Ju4tCode
42fa47263a 🍻 publish plugin splatoon2新闻 (#917)
Co-authored-by: DrinkOolongTea <DrinkOolongTea@users.noreply.github.com>
2022-04-16 10:18:56 +08:00
dependabot[bot]
39fd544651 ⬆️ Bump codecov/codecov-action from 2 to 3 (#911)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-06 20:18:44 +08:00
github-actions[bot]
e5bb30e2b5 📝 Update changelog 2022-04-05 14:21:41 +00:00
Ju4tCode
a6d8f18cf0 🍻 publish plugin nonebot_plugin_draw (#910)
Co-authored-by: bingganhe123 <bingganhe123@users.noreply.github.com>
2022-04-05 22:20:27 +08:00
github-actions[bot]
47d843ddca 📝 Update changelog 2022-04-05 13:54:00 +00:00
Jigsaw
74542d30e0 📝 remove outdated plugins (#902) 2022-04-05 21:52:42 +08:00
pre-commit-ci[bot]
e12445be2f ⬆️ auto update by pre-commit hooks (#908)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-04-05 11:05:37 +08:00
github-actions[bot]
d8eb7d311b 📝 Update changelog 2022-04-05 02:53:11 +00:00
Ju4tCode
7ac14bab03 🍻 publish plugin 扫雷游戏 (#907)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-04-05 10:52:04 +08:00
github-actions[bot]
e2621b4448 📝 Update changelog 2022-04-04 02:36:23 +00:00
Ju4tCode
2f3324ce0c 🐛 Fix: Bot Hook 没有捕获跳过异常 (#905) 2022-04-04 10:35:14 +08:00
github-actions[bot]
494b9c625d 📝 Update changelog 2022-04-01 08:30:51 +00:00
Akirami
f20cf785ce 🏷️ fix some matcher's redundant optional (#904)
Fix: 修复部分事件响应器参数类型中冗余的 Optional
2022-04-01 16:29:44 +08:00
github-actions[bot]
82803ff90f 📝 Update changelog 2022-03-29 02:33:41 +00:00
Ju4tCode
d38b5602a6 🍻 publish plugin 汉兜 Handle (#899)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-03-29 10:32:52 +08:00
github-actions[bot]
adb5fd8ca0 📝 Update changelog 2022-03-28 07:36:06 +00:00
Ju4tCode
977e1de077 🍻 publish plugin 多适配器帮助函数 (#897)
Co-authored-by: iyume <iyume@users.noreply.github.com>
2022-03-28 15:35:01 +08:00
github-actions[bot]
537866db95 📝 Update changelog 2022-03-25 13:19:16 +00:00
Ju4tCode
9ffd78dda3 🍻 publish plugin 语句抽象化 (#894)
Co-authored-by: CherryCherries <CherryCherries@users.noreply.github.com>
2022-03-25 21:18:28 +08:00
github-actions[bot]
599da5158e 📝 Update changelog 2022-03-25 10:25:27 +00:00
hemengyang
2b64e8266c 👷 CI: 修复发布机器人的意外错误 (#892)
* 🐛 fix permission error

* 👷 remove unnecessary push trigger
2022-03-25 18:24:35 +08:00
github-actions[bot]
8ccf10954a 📝 Update changelog 2022-03-25 03:44:05 +00:00
Ju4tCode
09b9a626e6 🍻 publish plugin 快速搜索 (#889)
Co-authored-by: KoishiStudio <KoishiStudio@users.noreply.github.com>
2022-03-25 11:43:06 +08:00
github-actions[bot]
1d221fddab 📝 Update changelog 2022-03-25 03:11:00 +00:00
Ju4tCode
524ed419c2 🍻 publish plugin wordle猜单词 (#891)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-03-25 11:10:10 +08:00
github-actions[bot]
536e75f994 📝 Update changelog 2022-03-25 03:03:58 +00:00
Ju4tCode
130c2ed5c0 🍻 publish plugin MediaWiki查询 (#886)
Co-authored-by: KoishiStudio <KoishiStudio@users.noreply.github.com>
2022-03-25 11:02:54 +08:00
github-actions[bot]
3c8e705bb0 📝 Update changelog 2022-03-24 02:47:44 +00:00
Ju4tCode
87e5e15b52 🍻 publish plugin HikariSearch (#884)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-03-24 10:46:45 +08:00
github-actions[bot]
a2abc5a714 📝 Update changelog 2022-03-23 02:43:18 +00:00
Ju4tCode
de434b3072 🍻 publish plugin 第二个leetcode查询插件 (#882)
Co-authored-by: Nranphy <Nranphy@users.noreply.github.com>
2022-03-23 10:42:15 +08:00
github-actions[bot]
614f005373 📝 Update changelog 2022-03-21 15:05:52 +00:00
MeetWq
36efa3f441 📝 remove or replace some invalid plugins (#879)
* 替代SimpleMusic插件

* 移除失效插件
2022-03-21 23:04:48 +08:00
github-actions[bot]
78a90ef7aa 📝 Update changelog 2022-03-20 11:43:57 +00:00
Ju4tCode
2e5df56d38 🍻 publish plugin 成分姬 (#878)
Co-authored-by: MeetWq <MeetWq@users.noreply.github.com>
2022-03-20 19:42:55 +08:00
github-actions[bot]
a230e98052 📝 Update changelog 2022-03-20 11:41:34 +00:00
Ju4tCode
45e2e6c280 🐛 fix event maybe converted when checking type (#876)
Fix: 修复 event 类型检查会对类型进行自动转换
2022-03-20 19:40:43 +08:00
github-actions[bot]
fcdb05a7e2 📝 Update changelog 2022-03-18 14:49:11 +00:00
Ju4tCode
8c6d5a2d1f 🍻 publish plugin Arcaea查分插件 (#875)
Co-authored-by: SEAFHMC <SEAFHMC@users.noreply.github.com>
2022-03-18 22:48:09 +08:00
github-actions[bot]
8735b61a8d 📝 Update changelog 2022-03-17 13:12:30 +00:00
Ju4tCode
02de6fd266 add rule permission reflected operation support (#872)
Feature: 添加 Rule, Permission 反向位运算支持
2022-03-17 21:11:37 +08:00
github-actions[bot]
06f8dde33c 📝 Update changelog 2022-03-17 02:57:02 +00:00
Ju4tCode
0fe3e4fb16 🍻 publish plugin QQ自动同意好友申请 (#871)
Co-authored-by: ZakiuC <ZakiuC@users.noreply.github.com>
2022-03-17 10:56:17 +08:00
github-actions[bot]
56c6f6a471 📝 Update changelog 2022-03-11 15:41:47 +00:00
Ju4tCode
58e69f7884 🍻 publish plugin 21点游戏插件 (#865)
Co-authored-by: yaowan233 <yaowan233@users.noreply.github.com>
2022-03-11 23:40:54 +08:00
github-actions[bot]
4ebbf7638c 📝 Update changelog 2022-03-11 08:43:18 +00:00
Ju4tCode
8d7507c8f2 🍻 publish plugin 色图生成 (#863)
Co-authored-by: monsterxcn <monsterxcn@users.noreply.github.com>
2022-03-11 16:42:29 +08:00
github-actions[bot]
c1c720756b 📝 Update changelog 2022-03-11 07:48:09 +00:00
Ju4tCode
a1be18f7f4 📝 fix abs link in register adapter (#861)
Docs: 修复适配器文档内商店链接
2022-03-11 15:47:22 +08:00
github-actions[bot]
e2fcfa902e 📝 Update changelog 2022-03-11 04:13:18 +00:00
StarHeart
b54f4c8d4c 📝 Docs: tips for finding adapters' document link (#860)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: yanyongyu <42488585+yanyongyu@users.noreply.github.com>
2022-03-11 12:12:25 +08:00
github-actions[bot]
4cf07ca2e0 📝 Update changelog 2022-03-10 09:21:58 +00:00
Ju4tCode
5b3dd8f020 🍻 Plugin: bilibili通知插件 (#859)
Co-authored-by: TDK1969 <TDK1969@users.noreply.github.com>
2022-03-10 17:20:46 +08:00
Ju4tCode
9bb291e95b ⬆️ upgrade fastapi to 0.75 (#857) 2022-03-09 11:59:35 +08:00
github-actions[bot]
492c0947c3 📝 Update changelog 2022-03-05 15:36:03 +00:00
Ju4tCode
547d50ad76 🍻 Plugin: 订阅推送管理 (#855)
Co-authored-by: mwbimh <mwbimh@users.noreply.github.com>
2022-03-05 23:35:14 +08:00
github-actions[bot]
f7600a8a62 📝 Update changelog 2022-03-03 09:44:57 +00:00
Ju4tCode
9bd380a3bb 🍻 Plugin: 动漫新闻 (#852)
Co-authored-by: 5656565566 <5656565566@users.noreply.github.com>
2022-03-03 17:43:53 +08:00
github-actions[bot]
8600687f7d 📝 Update changelog 2022-03-02 09:48:28 +00:00
Ju4tCode
1d98ea1961 Plugin: 游戏王卡查 (#846)
Co-authored-by: anlen123 <anlen123@users.noreply.github.com>
2022-03-02 17:47:18 +08:00
dependabot[bot]
998db949da ⬆️ Bump actions/checkout from 2 to 3 (#844)
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-02 13:46:22 +08:00
github-actions[bot]
dea1b8c6fa 📝 Update changelog 2022-03-01 04:28:59 +00:00
Ju4tCode
d348f544b1 🔀 Merge pull request #843
Plugin: 二维码识别与发送
2022-03-01 12:28:08 +08:00
kexue-z
b1559eee42 🍻 publish plugin 二维码识别与发送 2022-03-01 04:02:57 +00:00
github-actions[bot]
edc7183c22 📝 Update changelog 2022-02-28 03:56:30 +00:00
Ju4tCode
ea539345cc 🔀 Merge pull request #841
Plugin: mockingbird
2022-02-28 11:55:41 +08:00
Diaosi1111
03d60dd0be 🍻 publish plugin mockingbird 2022-02-28 02:56:03 +00:00
Ju4tCode
48003a779f ⬆️ update fastapi and tomlkit (#837)
Co-authored-by: iyume <iyumelive@gmail.com>
2022-02-27 18:10:20 +08:00
github-actions[bot]
2203b82b09 📝 Update changelog 2022-02-27 07:36:59 +00:00
Ju4tCode
9fc2f7c02e 🔀 Merge pull request #839
Plugin: QQ自动续火花
2022-02-27 15:36:09 +08:00
25252www
6ee295bfd7 🍻 publish plugin QQ自动续火花 2022-02-27 07:09:39 +00:00
mobyw
6b067f0865 🔥 Plugin: 移除 nonebot-general-rss (#836) 2022-02-25 23:18:26 +08:00
Ju4tCode
339c25638b 👷 fix ci error when no changlog performed (#835) 2022-02-25 12:58:38 +08:00
Ju4tCode
e6cd3e57f5 🔀 Merge pull request #834
Plugin: update nonebot-bison
2022-02-25 12:10:19 +08:00
felinae98
69fcda5658 update nonebot-bison
支持beta
2022-02-24 22:55:30 +08:00
github-actions[bot]
88f8614cfc 📝 Update changelog 2022-02-23 07:38:38 +00:00
Ju4tCode
273b302ef2 🔀 Merge pull request #832
Plugin: 每日一句
2022-02-23 15:37:44 +08:00
MelodyYuuka
e86bab74d3 🍻 publish plugin 每日一句 2022-02-23 06:56:46 +00:00
github-actions[bot]
b1df360900 📝 Update changelog 2022-02-22 15:11:23 +00:00
CherryGS
2c271da965 📝 Add note for fastapi_reload option on Windows @CherryGS (#830)
* 添加 `fastapi_reload` 在 win 的额外影响

* 🚨 auto fix by pre-commit hooks

* Update choose-driver.md

* 🚨 auto fix by pre-commit hooks

* 调整格式

* 🚨 auto fix by pre-commit hooks

* Update website/versioned_docs/version-2.0.0-beta.2/tutorial/choose-driver.md

Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>

* Update website/versioned_docs/version-2.0.0-beta.2/tutorial/choose-driver.md

Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>

* Update website/versioned_docs/version-2.0.0-beta.2/tutorial/choose-driver.md

Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>

* Update website/versioned_docs/version-2.0.0-beta.2/tutorial/choose-driver.md

Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>

* Update website/versioned_docs/version-2.0.0-beta.2/tutorial/choose-driver.md

Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>

* Update choose-driver.md

* Update choose-driver.md

* 📝 update reload warning

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>
Co-authored-by: yanyongyu <42488585+yanyongyu@users.noreply.github.com>
2022-02-22 23:10:18 +08:00
github-actions[bot]
5db9c1e232 📝 Update changelog 2022-02-20 19:17:42 +00:00
Ju4tCode
b05ce41b1d 🔀 Merge pull request #829
Plugin: 原神抽卡记录分析
2022-02-21 03:16:57 +08:00
monsterxcn
bda27c78b9 🍻 publish plugin 原神抽卡记录分析 2022-02-20 19:09:12 +00:00
github-actions[bot]
6f0e27ee6d 📝 Update changelog 2022-02-20 15:18:56 +00:00
Ju4tCode
2c89409667 🔀 Merge pull request #825
Plugin: YetAnotherPicSearch
2022-02-20 23:18:01 +08:00
Ju4tCode
5adc5ce1cd 🔀 Merge pull request #826
Chore(deps): bump dependencies
2022-02-20 23:16:28 +08:00
StarHeartHunt
cad2f90b8a ⬆️ bump dependencies 2022-02-20 14:58:53 +08:00
NekoAria
b3d246cfb1 🍻 publish plugin YetAnotherPicSearch 2022-02-19 15:52:45 +00:00
github-actions[bot]
a8a6eb8c93 📝 Update changelog 2022-02-19 10:45:12 +00:00
Ju4tCode
86a73011b1 🔀 Merge pull request #822
CI: 添加更新日志忽略 label 选项
2022-02-19 18:44:23 +08:00
yanyongyu
9fb089bf08 👷 exclude label for changelog 2022-02-19 16:56:41 +08:00
github-actions[bot]
72d993921f 📝 Update changelog 2022-02-19 05:33:28 +00:00
Ju4tCode
db764f7e9e 🔀 Merge pull request #820
CI: 添加 dependabot 配置文件
2022-02-19 13:32:46 +08:00
Mix
1767f7a388 🔧 Add dependabot config file to update GitHub Actions 2022-02-19 11:51:07 +08:00
github-actions[bot]
fc45c67d97 📝 Update changelog 2022-02-19 03:22:02 +00:00
Ju4tCode
87885bd878 🔀 Merge pull request #819
Docs: 修复 ci/cd action 中错误的版本号
2022-02-19 11:21:20 +08:00
Bubbleioa
d75a04b31a fix bobheadxi/deployments version
在 [github action](https://github.com/Bubbleioa/ioa-bot/runs/5250225969) 上出错 
Error: Unable to resolve action `bobheadxi/deployments@v0.6`, unable to find version `v0.6`

最新版本为 v0.6.2
2022-02-19 00:40:01 +08:00
github-actions[bot]
12313204e1 📝 Update changelog 2022-02-18 08:00:02 +00:00
Ju4tCode
4573235583 🔀 Merge pull request #816
Docs: 添加 netlify 标签
2022-02-18 15:59:21 +08:00
yanyongyu
4293bdf21f 🎨 add dark theme support 2022-02-18 15:46:59 +08:00
yanyongyu
baae3e48de 🍻 add netlify badge 2022-02-18 14:53:24 +08:00
github-actions[bot]
24df95ae4a 📝 Update changelog 2022-02-18 06:08:33 +00:00
Ju4tCode
6b50a57348 🔀 Merge pull request #815
Fix: 修复 on_fullmatch 返回类型错误
2022-02-18 14:07:41 +08:00
yanyongyu
6920ec3a11 🏷️ fix fullmatch return type error 2022-02-18 11:12:19 +08:00
github-actions[bot]
6586f28f6a 📝 Update changelog 2022-02-18 03:05:38 +00:00
Ju4tCode
192c8da09c 🔀 Merge pull request #797
Feature: 新增文本完整匹配规则
2022-02-18 11:04:49 +08:00
Mix
1fba27d9b8 Fix failed full match test 2022-02-17 23:50:00 +08:00
Mix
0f0dc0a818 improve full match performance with frozenset 2022-02-17 23:49:47 +08:00
github-actions[bot]
3c3a250180 📝 Update changelog 2022-02-17 08:45:14 +00:00
Ju4tCode
03d33f3bdc 🔀 Merge pull request #814
CI: 分离 pr 预览 action
2022-02-17 16:44:31 +08:00
yanyongyu
1147d67f1a 👷 separate website ci for pr checking 2022-02-17 16:30:01 +08:00
github-actions[bot]
98e5956d44 📝 Update changelog 2022-02-17 08:00:39 +00:00
Ju4tCode
999a6a0e10 🔀 Merge pull request #813
Docs: 减小更新日志 toc 最大显示等级
2022-02-17 15:59:43 +08:00
github-actions[bot]
ff2675b527 📝 Update changelog 2022-02-17 07:56:39 +00:00
Ju4tCode
daa026cfd7 🔀 Merge pull request #812
Fix: 修复 DataclassEncoder 嵌套 encode 的问题
2022-02-17 15:55:56 +08:00
yanyongyu
d4d3962177 🎨 reduce changelog toc level 2022-02-17 15:44:49 +08:00
yanyongyu
1d6a333b49 update dataclass encoder tests 2022-02-17 15:35:39 +08:00
pre-commit-ci[bot]
9c0e05c615 🚨 auto fix by pre-commit hooks 2022-02-17 07:12:29 +00:00
github-actions[bot]
258bdbe403 📝 Update changelog 2022-02-17 07:11:16 +00:00
AkiraXie
c48ddaf0a2 🐛 fix DataclassEncoder bug and add test case 2022-02-17 15:06:26 +08:00
github-actions[bot]
9dd989c627 📝 Update changelog 2022-02-16 15:19:06 +00:00
Ju4tCode
3d84844a58 🔀 Merge pull request #810
Plugin: 60s读世界小插件
2022-02-16 23:18:20 +08:00
bingganhe123
d63d434e0f 🍻 publish plugin 60s读世界小插件 2022-02-16 15:03:00 +00:00
github-actions[bot]
5216a5b8f2 📝 Update changelog 2022-02-16 12:29:53 +00:00
hemengyang
4107affb9b Docs: 修改议题模板中的错误链接 (#807) 2022-02-16 20:29:04 +08:00
github-actions[bot]
b898303e4d 📝 Update changelog 2022-02-16 12:25:05 +00:00
Mix
43aebd9c93 Docs: 修改消息模板文档中错误的样例 (#806)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-02-16 20:24:00 +08:00
github-actions[bot]
fcda5c37d7 📝 Update changelog 2022-02-16 11:45:11 +00:00
Lan
1412385e51 Fix: 修改错误的插件 PyPI 项目名称 (#804)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-02-16 19:44:29 +08:00
github-actions[bot]
00fab9143e 📝 Update changelog 2022-02-16 11:36:28 +00:00
Ju4tCode
5e17d4c2f9 🔀 Merge pull request #798
Docs: 更新贡献指南
2022-02-16 19:35:42 +08:00
github-actions[bot]
d7de928f22 📝 Update changelog 2022-02-16 10:00:23 +00:00
Ju4tCode
83ff7a3a6c 🔀 Merge pull request #805
CI: 减少 action 冗余运行
2022-02-16 17:59:33 +08:00
yanyongyu
6f9c9eb740 🔧 change latest changes to chinese 2022-02-16 17:51:17 +08:00
yanyongyu
6272dfd46a 🔥 remove unused condition 2022-02-16 17:04:12 +08:00
yanyongyu
ab78769822 🐛 fix concurrency missing matrix 2022-02-16 14:41:39 +08:00
yanyongyu
004a308765 👷 disable auto push 2022-02-16 14:28:44 +08:00
yanyongyu
98e0ec27ee ✏️ fix changelog typo 2022-02-16 14:19:26 +08:00
yanyongyu
a491d842db 👷 reduce ci redundant run 2022-02-16 14:17:33 +08:00
github-actions[bot]
722fc6c6e1 📝 Update changelog 2022-02-16 04:12:35 +00:00
Ju4tCode
a5fffe2a4f 🔀 Merge pull request #803
Plugin: pixiv.net p站查询图片
2022-02-16 12:12:10 +08:00
github-actions[bot]
5f1f84327d 📝 Update changelog 2022-02-16 04:05:34 +00:00
Ju4tCode
3d8ac3e789 🔀 Merge pull request #802
CI: fix ci permission error
2022-02-16 12:05:13 +08:00
anlen123
c05eea2b67 🍻 publish plugin pixiv.net p站查询图片 2022-02-16 04:03:22 +00:00
yanyongyu
a6299bec8f 💚 fix ci permission error 2022-02-16 11:49:45 +08:00
Ju4tCode
513c14ee78 🔀 Merge pull request #799
CI: 添加更新日志自动更新 action
2022-02-16 11:30:56 +08:00
yanyongyu
987e44e1d0 👷 update ci config 2022-02-16 11:10:54 +08:00
jigsaw
e7937e5a06 📝 update contributing guide 2022-02-16 10:33:21 +08:00
yanyongyu
962c71ea4e 👷 update changelog ci 2022-02-15 23:39:04 +08:00
Ju4tCode
04e9a50bc1 📝 update contributing guide
Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>
2022-02-15 23:03:56 +08:00
yanyongyu
4bd1b92e9f 📝 update contributing guide 2022-02-15 21:10:07 +08:00
pre-commit-ci[bot]
f737bb899c 🚨 auto fix by pre-commit hooks 2022-02-15 00:27:43 +00:00
Akirami
9f12404338 add full match Matcher 2022-02-15 08:20:29 +08:00
github-actions
cee96d8ab6 🔖 Release 2.0.0-beta.2 2022-02-14 16:27:11 +00:00
Ju4tCode
14703fce8d 🔀 Merge pull request #796
⬆️ bump version 2.0.0-beta.2
2022-02-15 00:17:33 +08:00
hemengyang
6d0c782fcc ⬆️ bump version 2.0.0-beta.2 2022-02-15 00:11:19 +08:00
hemengyang
0cceeaec0b 👷 fix release-drafter 2022-02-15 00:05:20 +08:00
Ju4tCode
803223f31c 🔀 Merge pull request #790
Release: 2.0.0-beta.2
2022-02-14 23:55:05 +08:00
yanyongyu
6ceaf51af7 👷 prepare for changelog automation 2022-02-14 21:54:38 +08:00
yanyongyu
8f38fc5795 👷 update ci workflow 2022-02-14 21:01:39 +08:00
yanyongyu
257c49466f ⚰️ remove beta1 docs 2022-02-14 19:53:27 +08:00
Mix
85d86dfa96 📝 Add project code of conduct (#794)
* 📝 add project code of conduct

* 🚨 auto fix by pre-commit hooks

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-02-14 17:40:36 +08:00
AkiraXie
925886534c 📝 refactor dependency-injection documents (#791)
* 📝 update dependency-injection docs

* 🚨 auto fix by pre-commit hooks

* 📝 fix some indent

* 📝 fix description

* 📝 add create callable in DI docs

* 🚨 auto fix by pre-commit hooks

* 📝 delete unused params in docs

* 📝 update di docs

* 🚨 auto fix by pre-commit hooks

* 📝 update di doc

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: yanyongyu <42488585+yanyongyu@users.noreply.github.com>
2022-02-14 17:26:55 +08:00
yanyongyu
9a53b415d9 ✏️ fix plugin structure typo 2022-02-14 10:53:56 +08:00
yanyongyu
a884869ae2 ⬆️ update test dependencies 2022-02-13 21:56:12 +08:00
Mix
04fe654d74 📝 Add document for message template (#789)
* 📝 Add document for message template

* 📝 🎨 Optimize example reading experience for message template

* 🚨 auto fix by pre-commit hooks

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-02-12 16:15:06 +08:00
yanyongyu
ff887481ee 📝 add custom api doc 2022-02-12 14:07:42 +08:00
yanyongyu
0bfe1ce433 ⬆️ upgrade dependencies 2022-02-11 17:22:46 +08:00
Ju4tCode
80bf73e0e9 🔀 Merge pull request #788
Plugin: おはよう!
2022-02-11 17:16:11 +08:00
KafCoppelia
a8694aee23 🍻 publish plugin おはよう! 2022-02-11 06:24:02 +00:00
yanyongyu
943de58826 🏷️ fix typing error 2022-02-11 11:25:31 +08:00
yanyongyu
c0af89a6ad ⬆️ upgrade dependencies 2022-02-11 11:24:34 +08:00
Ju4tCode
b076497823 🔀 Merge pull request #786
Bot: 琪露诺Bot
2022-02-11 10:49:54 +08:00
summerkirakira
a416b4315a 🍻 publish bot 琪露诺Bot 2022-02-10 19:11:57 +00:00
Ju4tCode
4f91e63759 🔀 Merge pull request #782
Bugfix: Potential message body injection vulnerability in MessageTemplate
2022-02-10 15:44:41 +08:00
Mix
dc982fe5eb Fix update cause failed test 2022-02-10 15:12:27 +08:00
Ju4tCode
1b17039fe1 🔀 Merge pull request #784
Plugin: 轻量文字转图片插件
2022-02-10 15:01:33 +08:00
mobyw
b4fc9f9539 🍻 publish plugin 轻量文字转图片插件 2022-02-10 06:11:55 +00:00
Mix
b7762b9176 🔒 🐛 Add initial value to vformat results list, fix #781 2022-02-10 13:17:11 +08:00
Mix
455c599b06 🧪 Add a fail test to reproduce #781 2022-02-10 13:15:59 +08:00
yanyongyu
e9908bcbc4 🔧 change docusaurus prism config 2022-02-08 14:59:54 +08:00
yanyongyu
fba9471fe6 📝 add deploy guide 2022-02-08 14:46:43 +08:00
Ju4tCode
58bceff175 🔀 Merge pull request #769
Docs: Fix copywriting
2022-02-08 10:50:59 +08:00
yanyongyu
c45843e32d ⬆️ upgrade dependencies 2022-02-07 19:56:39 +08:00
yanyongyu
aefe16f2c7 📝 update onebot homepage 2022-02-07 17:46:02 +08:00
yanyongyu
460efe436d 📝 add message document 2022-02-07 17:40:26 +08:00
Satoshi Jek
aacfc9b90c Plugin: 修改 nonebot-plugin-strman 错误的 module_name (#780) 2022-02-07 14:59:05 +08:00
yanyongyu
7d190213b7 📝 update readme badge 2022-02-07 14:12:08 +08:00
yanyongyu
ae37f31e38 🔀 Merge branch master 2022-02-07 11:38:52 +08:00
yanyongyu
6f90dcb12f 🚚 move call api doc 2022-02-07 11:30:24 +08:00
Ju4tCode
5ce72655e2 🔀 Merge pull request #772
Fix Message.template format spec does not support static method
2022-02-07 10:59:43 +08:00
Ju4tCode
9ed5d915d5 🔀 Merge pull request #779
Plugin: Fgo从者推理
2022-02-07 10:54:45 +08:00
suhexia
c4d82aa21b 🍻 publish plugin Fgo从者推理 2022-02-06 16:48:48 +00:00
Ju4tCode
319b3ff20e 🔀 Merge pull request #777
Plugin: 无数据库的问答插件
2022-02-06 22:53:51 +08:00
kexue-z
5e19ad672e 🍻 publish plugin 无数据库的问答插件 2022-02-06 14:26:00 +00:00
Ju4tCode
2d276a6b7a 🔀 Merge pull request #775
Plugin: random_cat_gif
2022-02-06 22:25:34 +08:00
applenana
e98e784fe7 🍻 publish plugin random_cat_gif 2022-02-06 13:59:58 +00:00
Satoshi Jek
f4120d91e0 🔀 Plugin: 风格化字符串管理 商店信息更新 (#773)
* chore(plugins): 插件仓库重定向

* chore(plugins): 补充修改作者信息
2022-02-06 21:37:27 +08:00
Jigsaw
2f51afc007 🔀 Merge branch 'dev' into docs/fix-copywriting 2022-02-06 19:50:50 +08:00
jigsaw
b9fd4b1ac8 📝 Fix copywriting 2022-02-06 19:46:14 +08:00
Mix
f4395d77d7 Add test to prove the fix is valid 2022-02-06 18:55:19 +08:00
Mix
28cfa45d95 🐛 Fix Message.template format spec does not support static method
Fixes #770
2022-02-06 18:40:30 +08:00
Ju4tCode
b90054e61b 🔀 Merge pull request #771
Feature: refactor and support bot connection hook
2022-02-06 18:16:18 +08:00
yanyongyu
1ee7f73d59 🔧 remove duplicated isort black config 2022-02-06 17:24:06 +08:00
yanyongyu
118519e15d ♻️ reorganize internal tree 2022-02-06 17:08:11 +08:00
yanyongyu
65dc9a908b 📝 update doc link 2022-02-06 15:37:36 +08:00
yanyongyu
924d9b6536 ✏️ fix changelog and typing 2022-02-06 15:24:41 +08:00
yanyongyu
fd11e2696b ♻️ reorganize class and add bot hook di 2022-02-06 14:52:50 +08:00
yanyongyu
b8456b12ad ✏️ fix matcher operation typo 2022-02-05 16:51:57 +08:00
yanyongyu
dcaf5cedcf 💡 update matcher docstrings 2022-02-05 16:49:21 +08:00
Ju4tCode
2cd2ea6ca4 🔀 Merge pull request #765
Docs: update some advanced docs
2022-02-05 12:38:48 +08:00
Ju4tCode
6e8978710a 🔀 Merge pull request #767
Plugin: 群聊反闪照
2022-02-05 12:35:55 +08:00
KafCoppelia
7e5c179641 🍻 publish plugin 群聊反闪照 2022-02-05 03:33:04 +00:00
AkiraXie
86aa3ef2e8 📝 update export-and-require and permission docs 2022-02-04 21:52:00 +08:00
AkiraXie
994b99e462 📝 fix indent 2022-02-04 15:45:21 +08:00
pre-commit-ci[bot]
b0b2b1f681 🚨 auto fix by pre-commit hooks 2022-02-04 07:15:37 +00:00
AkiraXie
4e1e0e98b4 Merge branch 'nonebot:dev' into dev 2022-02-04 15:14:06 +08:00
AkiraXie
a68a6e2659 ✏️ fix typo in fastapi 2022-02-04 15:13:31 +08:00
AkiraXie
e8bb66ca48 📝 update some advanced docs 2022-02-04 15:12:02 +08:00
yanyongyu
e720584044 change hook parse typing 2022-02-04 11:12:17 +08:00
yanyongyu
ec9e8511b7 reduce the hook typing limit 2022-02-04 11:06:38 +08:00
Ju4tCode
3a314fc7ae 🔀 Merge pull request #763
update plugin info
2022-02-03 21:27:11 +08:00
kexue
fe5e5428dd 🍻 update plugin info 2022-02-03 18:05:43 +08:00
Ju4tCode
e37e6d0714 🔀 Merge pull request #762
Plugin: random-cat
2022-02-02 17:54:26 +08:00
alphaAE
7cdcfd02ab 🍻 publish plugin random-cat 2022-02-02 08:47:52 +00:00
Ju4tCode
578f0fb619 🔀 Merge pull request #760
Plugin: nonebot-plugin-setu2
2022-02-02 16:46:54 +08:00
alphaAE
3408f27a77 🍻 publish plugin nonebot-plugin-setu2 2022-02-02 08:35:14 +00:00
Ju4tCode
0fd7c77640 🔀 Merge pull request #758
Plugin: 聊天记录插件
2022-01-31 23:14:18 +08:00
MeetWq
613fc09382 🍻 publish plugin 聊天记录插件 2022-01-31 14:59:33 +00:00
yanyongyu
4d5cc03454 📝 add handler running doc 2022-01-31 14:29:26 +08:00
yanyongyu
09b438485a ✏️ fix typo 2022-01-31 12:44:33 +08:00
yanyongyu
c7883863c7 🐛 fix asciinema ssr failed 2022-01-30 18:26:26 +08:00
yanyongyu
60ccdf8a7a 🐛 fix typing error for logger wrapper 2022-01-30 15:03:10 +08:00
yanyongyu
ea188cb948 📝 add custom log guide 2022-01-30 14:11:27 +08:00
yanyongyu
244c7266b3 📝 update changelog 2022-01-30 13:21:51 +08:00
yanyongyu
1eaacde745 ⬆️ upgrade dependencies 2022-01-30 13:18:50 +08:00
yanyongyu
c33e7eca46 ⬆️ upgrade dependencies 2022-01-30 13:13:55 +08:00
Ju4tCode
bdf2f4771b 🔀 Merge pull request #752
Fix: rewrite message typing and construct
2022-01-30 13:06:54 +08:00
yanyongyu
2cd6867bd1 add more tests 2022-01-30 11:04:02 +08:00
yanyongyu
f3cc93c699 add more tests 2022-01-30 00:05:01 +08:00
Ju4tCode
244b3c02a8 🔀 Merge pull request #756
Plugin: FG(Fifth Generation)
2022-01-29 23:56:57 +08:00
yanyongyu
2ec5917709 🐛 fix missing self instance validate 2022-01-29 23:55:14 +08:00
mgsky1
a0d9c4e1a0 🍻 publish plugin FG(Fifth Generation) 2022-01-29 15:43:24 +00:00
yanyongyu
5abf55d095 add message tests 2022-01-29 23:39:13 +08:00
Ju4tCode
34e2535390 🔀 Merge pull request #754
Plugin: 词云
2022-01-29 22:20:45 +08:00
yanyongyu
5fa7806a2f improve pydantic validate for message 2022-01-29 18:20:30 +08:00
he0119
1b674496ed 🍻 publish plugin 词云 2022-01-29 09:56:21 +00:00
yanyongyu
b43dfb983d ⚰️ remove unused import 2022-01-29 15:36:25 +08:00
yanyongyu
e887c39998 🏷️ update message typing 2022-01-29 13:56:54 +08:00
jigsaw
4c2269f789 ✏️ Fix typo 2022-01-28 20:46:27 +08:00
Ju4tCode
ac0dd63ca4 🔀 Merge pull request #749
CI: avoid duplicate CI runs
2022-01-28 16:48:06 +08:00
Ju4tCode
a8a68d89a2 🔀 Merge pull request #751
Plugin: 棋类游戏
2022-01-28 16:42:38 +08:00
MeetWq
942bb8761e 🍻 publish plugin 棋类游戏 2022-01-28 07:20:26 +00:00
yanyongyu
ad712c59b3 reuse type check code for dependent 2022-01-28 14:49:04 +08:00
yanyongyu
1271a757c9 👽 update type check due to py3.10 UnionType 2022-01-28 14:27:54 +08:00
Ju4tCode
ea8a700f86 🔀 Merge pull request #745
Docs: Add CONTRIBUTING
2022-01-28 14:05:36 +08:00
pre-commit-ci[bot]
fd8fd233b6 🚨 auto fix by pre-commit hooks 2022-01-28 06:04:57 +00:00
StarHeartHunt
d06e06eba2 👷 avoid duplicate CI runs 2022-01-28 14:03:19 +08:00
jigsaw
392def7936 📝 Update CONTRIBUTING
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-01-28 13:21:45 +08:00
Jigsaw
c4d08d13cb ✏️ Fix typo
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2022-01-28 13:21:45 +08:00
jigsaw
ffab125f02 📝 Update CONTRIBUTING
Co-authored-by: Mix <32300164+mnixry@users.noreply.github.com>
Co-authored-by: StarHeartHunt <starheart233@gmail.com>
2022-01-28 13:17:41 +08:00
yanyongyu
0b150d35f7 ✏️ fix isort line length typo 2022-01-28 12:32:19 +08:00
yanyongyu
15d68706b3 📝 add asciinema svg to install doc 2022-01-27 21:24:56 +08:00
jigsaw
2924c74333 📝 Add CONTRIBUTING 2022-01-27 18:58:10 +08:00
yanyongyu
afea004421 📝 update readme 2022-01-27 16:05:30 +08:00
Ju4tCode
1b08e0d822 🔀 Merge pull request #748
Fix: dict(config) raise error
2022-01-27 11:31:05 +08:00
yanyongyu
1da7da9fc1 🐛 fix dict(config) raise error 2022-01-27 11:15:44 +08:00
Mix
1b6b9d61fe 🔀 Merge pull request #747
Plugin: go-cqhttp 频道支持适配补丁
2022-01-26 22:53:51 +08:00
mnixry
b222863f63 🍻 publish plugin go-cqhttp 频道支持适配补丁 2022-01-26 14:52:54 +00:00
Ju4tCode
e1dffa99a0 🔀 Merge pull request #743
Fix: require load plugin error
2022-01-26 21:20:43 +08:00
yanyongyu
0885474b94 improve plugin finder 2022-01-26 20:55:23 +08:00
yanyongyu
482fba234b 📝 add nb-cli doc 2022-01-26 16:21:18 +08:00
yanyongyu
770e808f1d add require tests 2022-01-26 15:37:35 +08:00
Ju4tCode
fdf05173be 🔀 Merge pull request #741
Update plugins.json
2022-01-26 15:10:52 +08:00
yanyongyu
5c73c80c65 🐛 fix require error 2022-01-26 15:06:53 +08:00
KafCoppelia
bda2991c30 Update plugins.json
删去了自己几个已经适配b1的alpha标签;修改了自己几个插件的描述,统一风格;修改了几个原a:cqhttp标签为a:onebot
2022-01-26 14:18:59 +08:00
KafCoppelia
efbfea3d94 Update plugins.json
由于均适配beta.1,将fortune与what2eat插件“alpha”tag删除;修改几个插件“desc”字段描述,统一描述风格;
2022-01-26 14:09:09 +08:00
yanyongyu
956ee7e321 📝 add bot api doc 2022-01-26 12:30:05 +08:00
Ju4tCode
ba8dfb6d94 🔀 Merge pull request #739
Plugin: nonebot-general-rss
2022-01-26 11:02:59 +08:00
Mix
1a202e918d 🔥 remove plugins with wrong dependencies 2022-01-25 21:43:10 +08:00
mobyw
2e78de3d5d 🍻 publish plugin nonebot-general-rss 2022-01-25 11:27:15 +00:00
yanyongyu
f53e374521 ✏️ fix doc api link error 2022-01-25 16:03:49 +08:00
Ju4tCode
b773083b4e 🔀 Merge pull request #737
Fix wrong module name
2022-01-25 10:43:38 +08:00
Lan
ebd45dc5c1 🏷️ Update types 2022-01-25 10:19:37 +08:00
Lan
2f61c6a6f9 ✏️ Fix wrong module name 2022-01-25 10:09:20 +08:00
Mix
22597959cf 🔀 Merge pull request #736
Plugin: NoneBot的go-cqhttp启动器
2022-01-24 21:41:51 +08:00
mnixry
6b930cd7be 🍻 publish plugin NoneBot的go-cqhttp启动器 2022-01-24 13:41:00 +00:00
yanyongyu
c8369f599f 📝 add configuration and matcher operation 2022-01-24 20:32:46 +08:00
Ju4tCode
c09ecb4a88 🔀 Merge pull request #734
Plugin: NoneBot 数据存储
2022-01-24 16:39:11 +08:00
Ju4tCode
74c3961998 🔀 Merge pull request #732
修改自己几个插件的Tag
2022-01-24 16:38:23 +08:00
Ju4tCode
e7b2dde44a ✏️ fix trailing comma 2022-01-24 16:25:40 +08:00
风屿
77faa027bd 删掉了v:voice的tag 2022-01-24 15:37:24 +08:00
he0119
40f7c4013b 🍻 publish plugin NoneBot 数据存储 2022-01-24 07:24:19 +00:00
风屿
ba6a440bbd 修改自己几个插件的Tag 2022-01-24 14:23:38 +08:00
Ju4tCode
d0d6e0fc25 🔀 Merge pull request #730
Update plugins.json
2022-01-24 10:15:37 +08:00
KafCoppelia
26934124a1 Update plugins.json
修改nonebot_plugin_fortune "module_name" 与 nonebot_plugin_tarot 标签"alpha only" to "beta first",tarot插件已适配beta.1并已发行pypi,beta.1适配优先
2022-01-23 23:10:50 +08:00
Ju4tCode
05f4a8b363 🔀 Merge pull request #729
Plugin: 今天吃什么
2022-01-23 21:17:45 +08:00
KafCoppelia
cb92bb7007 🍻 publish plugin 今天吃什么 2022-01-23 13:13:15 +00:00
Ju4tCode
bc2abc9c51 🔀 Merge pull request #726
Plugin: emoji 合成器
2022-01-23 21:12:48 +08:00
Ju4tCode
ebd7e4df19 🔀 Merge pull request #727
Fix wrong module name
2022-01-23 21:12:01 +08:00
yanyongyu
48b507e272 📝 add config docs 2022-01-23 21:09:47 +08:00
Lancercmd
6a17ce5fda ✏️ Fix wrong module name 2022-01-23 20:59:02 +08:00
MeetWq
44ca11cceb 🍻 publish plugin emoji 合成器 2022-01-23 12:15:55 +00:00
Ju4tCode
12d28eb77d 🔀 Merge pull request #724
Plugin: Fix homepage for 2 plugins
2022-01-23 17:23:51 +08:00
Jigsaw
0513b5884d 🍺 Fix homepage of nonebot-plugin-manager & nonebot-plugin-puppet 2022-01-23 17:09:26 +08:00
yanyongyu
97563a0090 🐛 fix missing api docs include 2022-01-23 13:35:09 +08:00
Ju4tCode
596f763c46 🔀 Merge pull request #691
:construction_workerusing: nb-autodoc to generate api docs
2022-01-23 12:07:51 +08:00
yanyongyu
5f3902fe61 ✏️ fix hook typo 2022-01-23 11:48:35 +08:00
Mix
ceb7589b27 🔀 Merge pull request #723
Plugin: 塔罗牌
2022-01-23 11:09:39 +08:00
KafCoppelia
fa8a3987e7 🍻 publish plugin 塔罗牌 2022-01-23 03:01:21 +00:00
Ju4tCode
8f51aff483 🔀 Merge pull request #720
Plugin: nonebot_plugin_fortune
2022-01-22 23:47:12 +08:00
KafCoppelia
c1084cc437 🍻 publish plugin nonebot_plugin_fortune 2022-01-22 15:35:38 +00:00
yanyongyu
46757a315b ⬆️ upgrade dependencies 2022-01-22 17:09:45 +08:00
yanyongyu
4316990aab ⬆️ upgrade dependencies 2022-01-22 15:50:11 +08:00
yanyongyu
7d81e079de 🎨 improve tree style 2022-01-22 15:35:52 +08:00
yanyongyu
12d9a68351 🐛 fix typing error for mutex 2022-01-22 15:26:22 +08:00
yanyongyu
c4e204001e 💡 add docstrings 2022-01-22 15:23:07 +08:00
yanyongyu
f9674da6ea 💡 add di docstrings 2022-01-21 21:04:17 +08:00
Ju4tCode
794a640681 🔀 Merge pull request #718
Adapter: mirai2
2022-01-21 11:07:12 +08:00
ieew
1bdb27d109 🍻 publish adapter mirai2 2022-01-21 02:36:08 +00:00
yanyongyu
aef585c60c 💡 add adapter docstring 2022-01-20 14:49:46 +08:00
Ju4tCode
215cfc90f4 🔀 Merge pull request #716
👷 checkout with PAT
2022-01-20 13:42:12 +08:00
hemengyang
b671a9658b 👷checkout with PAT
CI can be triggered when github action pushes a commit.
2022-01-20 13:35:58 +08:00
Ju4tCode
017049f321 🔀 Merge pull request #715
Plugin: 天气查询
2022-01-20 12:16:12 +08:00
zjkwdy
10733e7520 🍻 publish plugin 天气查询 2022-01-20 04:05:30 +00:00
Ju4tCode
b343fb8e6f 🔀 Merge pull request #711
Fix: single_session potential bug
2022-01-20 10:59:10 +08:00
AkiraXie
f6308916ad 🐛 fix bug and improve test coverage 2022-01-20 03:16:04 +08:00
pre-commit-ci[bot]
b3d0e7c548 🚨 auto fix by pre-commit hooks 2022-01-19 18:10:30 +00:00
AkiraXie
67f5b87492 🐛 fix single_session bug 2022-01-20 02:05:57 +08:00
Ju4tCode
30a14eb99c 🔀 Merge pull request #710
Update plugins.json
2022-01-19 19:19:49 +08:00
meetwq
92714de522 Update plugins.json 2022-01-19 18:53:55 +08:00
yanyongyu
98ef09585a 💡 add docstrings 2022-01-19 16:16:56 +08:00
Ju4tCode
13e021fa1e 🔀 Merge pull request #708
商店链接指向错误
2022-01-19 15:12:45 +08:00
wzl19371
82224da9ab Fix store link 2022-01-19 14:59:22 +08:00
Ju4tCode
2877c39288 🔀 Merge pull request #707
Plugin: 移除冷却事件插件
2022-01-19 01:06:43 +08:00
Satoshi Jek
af0b0ae823 Plugin: 移除冷却事件插件
由于 OneBot v11 适配器自 v2.0.0b1 起提供了命令冷却支持,且该插件已无力继续维护,故将该插件从商店移除。
2022-01-19 00:33:10 +08:00
yanyongyu
4701537a48 💡 add docstrings 2022-01-18 23:46:10 +08:00
yanyongyu
608cf859c8 💡 add log, exception, consts docstring 2022-01-18 16:12:12 +08:00
yanyongyu
27b1ded9a1 💡 add config docstring 2022-01-18 12:31:08 +08:00
Ju4tCode
60800b1d9e 🔀 Merge pull request #706
更新插件tag
2022-01-17 22:32:03 +08:00
felinae98
c675addeef 更新插件tag 2022-01-17 21:58:29 +08:00
yanyongyu
a07919ad5c 📝 rewrite docstring 2022-01-17 15:06:53 +08:00
Ju4tCode
ce0e230887 🔀 Merge pull request #705
Feature: Advanced message slice support
2022-01-17 10:59:26 +08:00
Mix
b037be4485 add unit test for message slice 2022-01-17 00:29:09 +08:00
Mix
3b4c4d3081 Implement .count and optimize .get performance for message slice 2022-01-17 00:28:36 +08:00
Mix
1221baaa94 Implement .get and .index methods for Message 2022-01-16 17:13:26 +08:00
pre-commit-ci[bot]
39822378a7 🚨 auto fix by pre-commit hooks 2022-01-16 05:26:55 +00:00
Mix
3041650b4b add advanced message slice support 2022-01-16 13:17:05 +08:00
yanyongyu
3a9a5a9ce9 📝 add frontmatter config 2022-01-16 11:30:09 +08:00
yanyongyu
34c086a046 ⚗️ reduce prettier file 2022-01-16 10:52:12 +08:00
Ju4tCode
cf819af179 🔀 Merge pull request #704
Plugin: 彩云小梦AI续写
2022-01-16 10:40:03 +08:00
yanyongyu
9b6d8b6efa 📝 test autogen docs 2022-01-15 23:53:36 +08:00
MeetWq
478dff512f 🍻 publish plugin 彩云小梦AI续写 2022-01-15 14:19:20 +00:00
yanyongyu
cc1dc10b5d add nb-autodoc 2022-01-15 22:16:31 +08:00
yanyongyu
b7a0ba11d5 🔀 Merge branch dev 2022-01-15 22:12:50 +08:00
yanyongyu
93aec6d3f6 🏷️ add pre-commit flow 2022-01-15 21:27:43 +08:00
Ju4tCode
9c729d194b 🔀 Merge pull request #702
Docs: remove unsupported char
2022-01-15 19:46:00 +08:00
StarHeart
dcfba4e94a 🐛 remove unsupported char 2022-01-15 17:41:22 +08:00
Mix
55b1f962ac 🔀 Merge pull request #701
Plugin: 人生重开模拟器
2022-01-15 16:58:15 +08:00
MeetWq
6c0ab74956 🍻 publish plugin 人生重开模拟器 2022-01-15 08:54:07 +00:00
Mix
9cbac0b4ca 🔀 Merge pull request #699
Plugin: 新冠疫情查询😷
2022-01-15 10:16:49 +08:00
hemengyang
8d0951a816 📝 fix wrong syntax and link 2022-01-15 09:35:30 +08:00
Zeta-qixi
8a896b42a3 🍻 publish plugin 新冠疫情查询😷 2022-01-14 19:32:35 +00:00
hemengyang
d26fda7320 🐛 fix docs build fail 2022-01-14 22:05:56 +08:00
Ju4tCode
9af7079fdd 🔀 Merge pull request #697
Plugin: 疯狂星期四
2022-01-14 21:53:15 +08:00
KafCoppelia
1d49defdfa 🍻 publish plugin 疯狂星期四 2022-01-14 13:35:22 +00:00
Ju4tCode
0e31a5fbf4 🔀 Merge pull request #695
Plugin: 扔骰子
2022-01-14 21:19:01 +08:00
KafCoppelia
ad5a011b45 🍻 publish plugin 扔骰子 2022-01-14 13:11:42 +00:00
hemengyang
341ee94848 🔥remove sphinx 2022-01-14 20:04:19 +08:00
hemengyang
a47b8c68c0 👷using nb-autodoc to generate api docs 2022-01-14 19:58:22 +08:00
yanyongyu
cc343c981f 💩 add logger format todo 2022-01-14 12:32:03 +08:00
Ju4tCode
10395d6bce 🔀 Merge pull request #686
Cross platform code coverage test
2022-01-13 18:17:15 +08:00
yanyongyu
6713f4d9b0 add test flags for os, python version 2022-01-13 18:11:00 +08:00
yanyongyu
8494768a89 🔥 remove pypy test 2022-01-13 18:06:07 +08:00
yanyongyu
88bd49de45 👷 support cross platform test 2022-01-13 17:58:35 +08:00
yanyongyu
b52ccc3690 👷 reuse workflow setup step 2022-01-13 16:41:01 +08:00
Ju4tCode
a8a1b4d65d 🔀 Merge pull request #683
📝 prepare docstring for autodoc
2022-01-13 11:14:03 +08:00
hemengyang
98deadb4d6 粗略过一遍,修复一眼可见的问题 2022-01-12 19:41:42 +08:00
hemengyang
ec06010298 令标题符合 markdown 语法 2022-01-12 19:24:01 +08:00
hemengyang
cd69b22d43 令 tip 符合格式 2022-01-12 19:20:59 +08:00
hemengyang
f298930f9d 更新依赖参数的注释 2022-01-12 19:15:56 +08:00
hemengyang
0e97022d3b 调整缩进 2022-01-12 19:10:29 +08:00
hemengyang
6d21cbed55 令用法符合格式 2022-01-12 18:53:30 +08:00
hemengyang
edb20a4786 令异常符合格式 2022-01-12 18:45:35 +08:00
hemengyang
187532930b 令返回符合格式 2022-01-12 18:43:07 +08:00
hemengyang
456d333568 令参数符合标准 2022-01-12 18:31:12 +08:00
hemengyang
a5f32febbd 令参数列表符合 autodoc 格式 2022-01-12 18:25:25 +08:00
hemengyang
4ba1a09fb7 使用 markdown 格式的强调语法 2022-01-12 18:19:21 +08:00
hemengyang
0099364838 删除说明前缀 2022-01-12 18:16:05 +08:00
hemengyang
0e11959347 删除默认值 2022-01-12 18:02:08 +08:00
hemengyang
705a6f7fbf 删除类型 2022-01-12 18:00:56 +08:00
Ju4tCode
eeb54c8f8a 🔀 Merge pull request #682
Docs: format adapter name
2022-01-12 17:25:15 +08:00
StarHeart
c9056c6fd0 📝 format adapter name 2022-01-12 16:46:56 +08:00
yanyongyu
e29db806cc 📝 update changelog 2022-01-12 11:54:01 +08:00
Ju4tCode
f837e5f3fa Merge pull request #673 from A-kirami/dev
从 Fastapi 的文档中排除驱动器的 HTTP 上报地址
2022-01-11 15:12:37 +08:00
yanyongyu
d82f0c6310 ⚗️ add config option for fastapi 2022-01-11 15:03:17 +08:00
Ju4tCode
18082d0dc7 🔀 Merge pull request #681
Remove mirai-api-http related info from readme
2022-01-11 14:51:23 +08:00
yanyongyu
6ca54574ce ✏️ fix context shell command typo 2022-01-11 12:53:19 +08:00
Mix
85fc2422d1 🔥 remove mirai-api-http adapter from store 2022-01-11 00:04:36 +08:00
Mix
bb7313f12c 📝 remove mirai-api-http related info from readme, fix #470
Mirai-API-HTTP will no longer be maintained by NoneBot officialy.
2022-01-10 23:41:57 +08:00
yanyongyu
742d1f1f02 ⚗️ fix load builtin plugin 2022-01-10 22:52:10 +08:00
yanyongyu
1b035ed19b 🔥 add State() deprecation warning 2022-01-10 22:24:45 +08:00
yanyongyu
ea65ee5b4f 👷 update eci python version 2022-01-10 12:07:11 +08:00
yanyongyu
6572622e8a improve test performance 2022-01-10 11:53:02 +08:00
yanyongyu
00de3bcc54 📝 update changelog 2022-01-10 11:22:35 +08:00
yanyongyu
2ccdc218e0 improve state detect #677 2022-01-10 11:21:01 +08:00
Ju4tCode
c11c62f622 🔀 Merge pull request #678
Docs: fix di import path
2022-01-10 10:44:25 +08:00
HibiKier
59c77d312a 📝 fix di import path 2022-01-09 23:49:24 +08:00
Ju4tCode
a14cfc8d77 🔀 Merge pull request #679
Fix: plugin load fail process
2022-01-09 23:29:53 +08:00
yanyongyu
d6f5216d29 🐛 fix plugin load fail 2022-01-09 23:15:33 +08:00
Ju4tCode
d549087db2 🔀 Merge pull request #676
Fix: fix matcher receive and arg detect
2022-01-09 20:45:19 +08:00
yanyongyu
3fa8bd2cd0 🐛 fix receive and got missing detect error 2022-01-09 20:34:03 +08:00
yanyongyu
8674d18543 🐛 fix pagination display error 2022-01-09 20:27:43 +08:00
明见
096f0d72f1 从 Fastapi 的文档中排除驱动器的 HTTP 上报地址 2022-01-08 22:19:45 +08:00
Ju4tCode
f0e935d4ff 🔀 Merge pull request #672
Plugin: Add tags for j1g5awi's plugins
2022-01-08 21:51:43 +08:00
Jigsaw
490a8146bc ✏️ Fix typo 2022-01-08 21:17:31 +08:00
Jigsaw
a74c6e220b ✏️ Fix typo 2022-01-08 21:05:39 +08:00
Jigsaw
0e8ef3def2 🍻 Add tags for j1g5awi's plugins 2022-01-08 20:57:36 +08:00
Ju4tCode
ba4e90b14f 🔀 Merge pull request #671
Adapter: 开黑啦
2022-01-08 20:18:35 +08:00
Tian-que
d02d8f06b2 🍻 publish adapter 开黑啦 2022-01-08 12:11:08 +00:00
306 changed files with 22716 additions and 13873 deletions

20
.devcontainer/Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.233.0/containers/codespaces-linux/.devcontainer/base.Dockerfile
FROM mcr.microsoft.com/vscode/devcontainers/universal:linux
# ** [Optional] Uncomment this section to install additional packages. **
# USER root
#
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
USER codespace
# [Required] Poetry
RUN curl -sSL https://install.python-poetry.org | python - -y
RUN poetry config virtualenvs.in-project true
# [Required] Gitmoji CLI
# Deprecated: Maybe removed once nonemoji is done
RUN yarn global add gitmoji-cli
ENV PATH="$PATH:/home/codespace/.yarn/bin"

View File

@@ -0,0 +1,83 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.233.0/containers/codespaces-linux
{
"name": "NoneBot",
"build": {
"dockerfile": "Dockerfile",
"context": ".."
},
"settings": {
"go.toolsManagement.checkForUpdates": "local",
"go.useLanguageServer": true,
"go.gopath": "/go",
"python.defaultInterpreterPath": "/opt/python/latest/bin/python",
"python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
"python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
"python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
"python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
"python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
"python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
"python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
"python.linting.pylintPath": "/usr/local/py-utils/bin/pylint",
"python.analysis.diagnosticMode": "workspace",
"python.analysis.typeCheckingMode": "basic",
"[python]":{
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"lldb.executable": "/usr/bin/lldb",
"files.exclude": {
"**/__pycache__": true
},
"files.watcherExclude": {
"**/target/**": true,
"**/__pycache__": true
}
},
"remoteUser": "codespace",
"overrideCommand": false,
"mounts": ["source=codespaces-linux-var-lib-docker,target=/var/lib/docker,type=volume"],
"runArgs": [
"--cap-add=SYS_PTRACE",
"--security-opt",
"seccomp=unconfined",
"--privileged",
"--init"
],
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"GitHub.vscode-pull-request-github",
"ms-python.python",
"ms-python.vscode-pylance",
"ms-python.isort",
"ms-python.black-formatter",
"EditorConfig.EditorConfig",
"esbenp.prettier-vscode",
"bradlc.vscode-tailwindcss"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// "oryx build" will automatically install your dependencies and attempt to build your project
"postCreateCommand": "poetry install -E all && poetry run pre-commit install && yarn install"
}

View File

@@ -4,11 +4,11 @@ contact_links:
url: https://discussions.nonebot.dev/
about: Ask questions about nonebot
- name: Plugin Publish
url: https://v2.nonebot.dev/store.html
url: https://v2.nonebot.dev/store
about: Publish your plugin to nonebot homepage and nb-cli
- name: Adapter Publish
url: https://v2.nonebot.dev/store.html
url: https://v2.nonebot.dev/store
about: Publish your adapter to nonebot homepage and nb-cli
- name: Bot Publish
url: https://v2.nonebot.dev/store.html
url: https://v2.nonebot.dev/store
about: Publish your bot to nonebot homepage and nb-cli

View File

@@ -0,0 +1,11 @@
name: Build API Doc
description: Build API Doc
runs:
using: "composite"
steps:
- run: |
poetry run nb-autodoc nonebot
cp -r ./build/nonebot/* ./website/docs/api/
yarn prettier
shell: bash

21
.github/actions/setup-node/action.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: Setup Node
description: Setup Node
runs:
using: "composite"
steps:
- uses: actions/setup-node@v2
with:
node-version: "16"
- id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
shell: bash
- uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
- run: yarn install
shell: bash

31
.github/actions/setup-python/action.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Setup Python
description: Setup Python
inputs:
python-version:
description: Python version
required: false
default: "3.9"
runs:
using: "composite"
steps:
- id: python
uses: actions/setup-python@v2
with:
python-version: ${{ inputs.python-version }}
architecture: "x64"
- uses: Gr1N/setup-poetry@v7
- id: poetry-cache
run: echo "::set-output name=dir::$(poetry config virtualenvs.path)"
shell: bash
- uses: actions/cache@v2
with:
path: ${{ steps.poetry-cache.outputs.dir }}
key: ${{ runner.os }}-poetry-${{ steps.python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
- run: poetry install -E all
shell: bash

6
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily

View File

@@ -1,42 +1,43 @@
name-template: 'Release v$RESOLVED_VERSION 🌈'
tag-template: 'v$RESOLVED_VERSION'
template: $CHANGES
category-template: "### $TITLE"
name-template: "Release v$RESOLVED_VERSION 🌈"
tag-template: "v$RESOLVED_VERSION"
change-template: "- $TITLE [@$AUTHOR](https://github.com/$AUTHOR) ([#$NUMBER]($URL))"
change-title-escapes: '\<&'
exclude-labels:
- "dependencies"
- "skip-changelog"
categories:
- title: '💥 Breaking Changes'
- title: "💥 破坏性变更"
labels:
- 'Breaking'
- title: '🚀 Features'
- "Breaking"
- title: "🚀 新功能"
labels:
- 'feature'
- 'enhancement'
- title: '🐛 Bug Fixes'
- "feature"
- "enhancement"
- title: "🐛 Bug 修复"
labels:
- 'fix'
- 'bugfix'
- 'bug'
- title: '🍻 Plugin Publish'
label: 'Plugin'
- title: '🍻 Bot Publish'
label: 'Bot'
- title: '🍻 Adapter Publish'
label: 'Adapter'
change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks.
- "fix"
- "bugfix"
- "bug"
- title: "📝 文档"
labels:
- "documentation"
- title: "💫 杂项"
- title: "🍻 插件发布"
label: "Plugin"
- title: "🍻 机器人发布"
label: "Bot"
- title: "🍻 适配器发布"
label: "Adapter"
version-resolver:
major:
labels:
- 'major'
- "major"
minor:
labels:
- 'minor'
- "minor"
patch:
labels:
- 'patch'
- "patch"
default: patch
template: |
## Documentation
See: https://v2.nonebot.dev
## 💫 Changes
$CHANGES

View File

@@ -2,38 +2,42 @@ name: Code Coverage
on:
push:
branches:
- master
pull_request:
jobs:
test:
runs-on: ubuntu-latest
name: Run Pytest and Upload Coverage
name: Test Coverage
runs-on: ${{ matrix.os }}
concurrency:
group: test-coverage-${{ github.ref }}-${{ matrix.os }}-${{ matrix.python-version }}
cancel-in-progress: true
strategy:
matrix:
python-version: ["3.7", "3.8", "3.9", "3.10"]
os: [ubuntu-latest, windows-latest, macos-latest]
fail-fast: false
env:
OS: ${{ matrix.os }}
PYTHON_VERSION: ${{ matrix.python-version }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up Python environment
uses: actions/setup-python@v2
- name: Setup Python environment
uses: ./.github/actions/setup-python
with:
python-version: "3.9"
architecture: "x64"
- uses: Gr1N/setup-poetry@v7
- uses: actions/cache@v2
with:
path: ~/.cache/pypoetry/virtualenvs
key: ${{ runner.os }}-poetry-${{ hashFiles('**/poetry.lock') }}
- name: Install dependencies
run: poetry install -E all
python-version: ${{ matrix.python-version }}
- name: Run Pytest
run: |
cd tests/
poetry run pytest --cov-report xml
poetry run pytest -n auto --cov-report xml
- name: Upload coverage report
uses: codecov/codecov-action@v2
uses: codecov/codecov-action@v3
with:
env_vars: OS,PYTHON_VERSION
files: ./tests/coverage.xml
flags: unittests

View File

@@ -1,12 +1,9 @@
name: NoneBot2 Publish Bot
on:
push:
branches:
- master
issues:
types: [opened, reopened, edited]
pull_request:
pull_request_target:
types: [closed]
jobs:
@@ -15,10 +12,12 @@ jobs:
name: nonebot2 publish bot
steps:
- name: Checkout code
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
token: ${{ secrets.GH_TOKEN }}
- name: NoneBot2 Publish Bot
uses: nonebot/nonebot2-publish-bot@main
uses: docker://ghcr.io/nonebot/nonebot2-publish-bot:main
with:
token: ${{ secrets.GH_TOKEN }}
config: >

97
.github/workflows/release-drafter.yml vendored Normal file
View File

@@ -0,0 +1,97 @@
name: Release Drafter
on:
push:
tags:
- v*
pull_request_target:
branches:
- master
types:
- closed
jobs:
update-release-draft:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-latest
concurrency:
group: pull-request-changelog
cancel-in-progress: true
steps:
- uses: actions/checkout@v3
with:
token: ${{ secrets.GH_TOKEN }}
- name: Setup Node Environment
uses: ./.github/actions/setup-node
- uses: release-drafter/release-drafter@v5
id: release-drafter
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Update Changelog
uses: docker://ghcr.io/nonebot/auto-changelog:master
with:
changelog_file: website/src/pages/changelog.md
latest_changes_position: '# 更新日志\n\n'
latest_changes_title: '## 最近更新'
replace_regex: '(?<=## 最近更新\n)[\s\S]*?(?=\n## )'
changelog_body: ${{ steps.release-drafter.outputs.body }}
commit_and_push: false
- name: Commit and Push
run: |
yarn prettier
git config user.name github-actions[bot]
git config user.email github-actions[bot]@users.noreply.github.com
git add .
git diff-index --quiet HEAD || git commit -m ":memo: Update changelog"
git push
release:
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Python Environment
uses: ./.github/actions/setup-python
- name: Setup Node Environment
uses: ./.github/actions/setup-node
- name: Build API Doc
uses: ./.github/actions/build-api-doc
- run: |
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
- uses: release-drafter/release-drafter@v5
with:
name: Release ${{ env.TAG_NAME }} 🌈
tag: ${{ env.TAG_NAME }}
publish: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build and Publish Package
run: |
poetry build
poetry publish -u ${{secrets.PYPI_USERNAME}} -p ${{secrets.PYPI_PASSWORD}}
gh release upload --clobber ${{ env.TAG_NAME }} dist/*.tar.gz dist/*.whl
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build and Publish Doc Package
run: |
yarn build:plugin --out-dir ../packages/nonebot-plugin-docs/nonebot_plugin_docs/dist
export NONEBOT_VERSION=`poetry version -s`
cd packages/nonebot-plugin-docs/
poetry version $NONEBOT_VERSION
poetry build
poetry publish -u ${{secrets.PYPI_USERNAME}} -p ${{secrets.PYPI_PASSWORD}}
gh release upload --clobber ${{ env.TAG_NAME }} dist/*.tar.gz dist/*.whl
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,36 +0,0 @@
name: Release Drafter
on:
push:
branches:
- master
tags:
- v*
jobs:
update-release-draft:
if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: release-drafter/release-drafter@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
release:
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: |
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
- uses: release-drafter/release-drafter@v5
with:
name: Release ${{ env.TAG_NAME }} 🌈
tag: ${{ env.TAG_NAME }}
publish: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,58 +0,0 @@
name: Release Nonebot Plugin Docs
on:
push:
tags:
- v*
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: "3.9"
architecture: "x64"
- uses: Gr1N/setup-poetry@v7
- uses: actions/cache@v2
with:
path: ~/.cache/pypoetry/virtualenvs
key: ${{ runner.os }}-poetry-${{ hashFiles('**/poetry.lock') }}
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: "16"
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Cache Packages
uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
- name: Install and build
run: |
poetry install -E all
poetry run sphinx-build -M markdown ./docs_build ./build
cp -r ./build/markdown/* ./website/docs/api/
yarn install
yarn prettier
yarn build:plugin --out-dir ../packages/nonebot-plugin-docs/nonebot_plugin_docs/dist
- name: Publish Package
run: |
export NONEBOT_VERSION=`poetry version -s`
cd packages/nonebot-plugin-docs/
poetry version $NONEBOT_VERSION
poetry build
poetry publish -u ${{secrets.PYPI_USERNAME}} -p ${{secrets.PYPI_PASSWORD}}

View File

@@ -8,62 +8,40 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
ref: master
token: ${{ secrets.GH_TOKEN }}
- name: Set up Python
uses: actions/setup-python@v2
- name: Setup Python Environment
uses: ./.github/actions/setup-python
- name: Setup Node Environment
uses: ./.github/actions/setup-node
- name: Build API Doc
uses: ./.github/actions/build-api-doc
- run: echo "TAG_NAME=v$(poetry version -s)" >> $GITHUB_ENV
- name: Archive Changelog
uses: docker://ghcr.io/nonebot/auto-changelog:master
with:
python-version: "3.9"
architecture: "x64"
- uses: Gr1N/setup-poetry@v7
- uses: actions/cache@v2
with:
path: ~/.cache/pypoetry/virtualenvs
key: ${{ runner.os }}-poetry-${{ hashFiles('**/poetry.lock') }}
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: "16"
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Cache Packages
uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
- name: Set up dependencies
run: |
poetry install -E all
- name: Build Doc
run: poetry run sphinx-build -M markdown ./docs_build ./build
- name: Copy Files
run: cp -r ./build/markdown/* ./website/docs/api/
changelog_file: website/src/pages/changelog.md
archive_regex: '(?<=## )最近更新(?=\n)'
archive_title: ${{ env.TAG_NAME }}
commit_and_push: false
- name: Archive Files
run: |
yarn install
yarn prettier
yarn archive $(poetry version -s)
yarn prettier
- name: Push Tag and Release to PyPI
- name: Push Tag
run: |
git config user.name github-actions
git config user.email github-actions@github.com
git config user.name github-actions[bot]
git config user.email github-actions[bot]@users.noreply.github.com
git add .
git commit -m ":bookmark: Release $(poetry version -s)"
git tag v$(poetry version -s)
git tag ${{ env.TAG_NAME }}
git push && git push --tags
poetry build
poetry publish -u ${{secrets.PYPI_USERNAME}} -p ${{secrets.PYPI_PASSWORD}}

View File

@@ -1,83 +1,44 @@
name: Build Upload Site
name: Site Deploy
on:
push:
pull_request_target:
branches:
- master
jobs:
publish:
runs-on: ubuntu-latest
concurrency:
group: website-deploy-${{ github.ref }}
cancel-in-progress: true
steps:
- uses: actions/checkout@v2
if: github.event_name == 'push'
- uses: actions/checkout@v3
- uses: actions/checkout@v2
if: github.event_name != 'push'
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Setup Python Environment
uses: ./.github/actions/setup-python
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
architecture: "x64"
- name: Setup Node Environment
uses: ./.github/actions/setup-node
- uses: Gr1N/setup-poetry@v7
- name: Build API Doc
uses: ./.github/actions/build-api-doc
- uses: actions/cache@v2
with:
path: ~/.cache/pypoetry/virtualenvs
key: ${{ runner.os }}-poetry-${{ hashFiles('**/poetry.lock') }}
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: "16"
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Cache Packages
uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
- name: Install and build
run: |
poetry install -E all
poetry run sphinx-build -M markdown ./docs_build ./build
cp -r ./build/markdown/* ./website/docs/api/
yarn install
yarn prettier
yarn build
- name: Build Doc
run: yarn build
- name: Get Branch Name
run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/})" >> $GITHUB_ENV
- name: Get Deploy Name
if: github.event_name == 'push'
run: |
echo "DEPLOY_NAME=${{ env.BRANCH_NAME }}" >> $GITHUB_ENV
echo "PRODUCTION=${{ env.BRANCH_NAME == 'master' }}" >> $GITHUB_ENV
- name: Get Deploy Name
if: github.event_name != 'push'
run: |
echo "DEPLOY_NAME=deploy-preview-${{ github.event.number }}" >> $GITHUB_ENV
echo "PRODUCTION=false" >> $GITHUB_ENV
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@v1
with:
publish-dir: './website/build'
production-deploy: ${{ env.PRODUCTION }}
publish-dir: "./website/build"
production-deploy: true
github-token: ${{ secrets.GITHUB_TOKEN }}
deploy-message: 'Deploy ${{ env.DEPLOY_NAME }}@${{ github.sha }}'
deploy-message: "Deploy ${{ env.BRANCH_NAME }}@${{ github.sha }}"
enable-commit-comment: false
alias: ${{ env.DEPLOY_NAME }}
alias: ${{ env.BRANCH_NAME }}
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.SITE_ID }}

45
.github/workflows/website-preview.yml vendored Normal file
View File

@@ -0,0 +1,45 @@
name: Site Deploy(Preview)
on:
pull_request_target:
jobs:
preview:
runs-on: ubuntu-latest
concurrency:
group: pull-request-preview-${{ github.event.number }}
cancel-in-progress: true
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Setup Python Environment
uses: ./.github/actions/setup-python
- name: Setup Node Environment
uses: ./.github/actions/setup-node
- name: Build API Doc
uses: ./.github/actions/build-api-doc
- name: Build Doc
run: yarn build
- name: Get Deploy Name
run: |
echo "DEPLOY_NAME=deploy-preview-${{ github.event.number }}" >> $GITHUB_ENV
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@v1
with:
publish-dir: "./website/build"
production-deploy: false
github-token: ${{ secrets.GITHUB_TOKEN }}
deploy-message: "Deploy ${{ env.DEPLOY_NAME }}@${{ github.sha }}"
enable-commit-comment: false
alias: ${{ env.DEPLOY_NAME }}
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.SITE_ID }}

4
.markdownlint.yaml Normal file
View File

@@ -0,0 +1,4 @@
MD013: false
MD024: # 重复标题
siblings_only: true
MD033: false # 允许 html

22
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,22 @@
ci:
autofix_commit_msg: ":rotating_light: auto fix by pre-commit hooks"
autofix_prs: true
autoupdate_branch: master
autoupdate_schedule: monthly
autoupdate_commit_msg: ":arrow_up: auto update by pre-commit hooks"
repos:
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.6.2
hooks:
- id: prettier
types_or: [javascript, jsx, ts, tsx, markdown]

86
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,86 @@
# NoneBot2 贡献者公约
## 我们的承诺
身为项目成员、贡献者、负责人,我们保证参与此社区的每个人都不受骚扰,不论其年龄、体型、身体条件、民族、性征、性别认同与表现、经验水平、教育程度、社会地位、国籍、相貌、种族、宗教信仰及性取向如何。
我们承诺致力于建设开放、友善、多元、包容、健康的社区环境。
## 我们的准则
有助于促进本社区积极环境的行为包括但不限于:
- 与人为善、推己及人
- 尊重不同的主张、观点和经历
- 积极提出、耐心接受有益批评
- 面对过失,承担责任、认真道歉、从中学习
- 关注社区共同诉求,而非一己私利
不当行为包括但不限于:
- 发布与性有关的言论或图像,以及任何形式的献殷勤或勾引
- 挑衅行为、侮辱或贬损的言论、人身及政治攻击
- 公开或私下骚扰
- 未获明确授权擅自发布他人的资料,如地址、电子邮箱等
- 其他有理由认定为违反职业操守的不当行为
## 落实之义务
社区负责人有责任诠释什么是“妥当行为”,并据此准则,妥善公正地认定与处置不当、威胁、冒犯及有害的行为。
社区负责人有权利和义务删除、编辑、拒绝违背本公约的评论comment、提交commit、代码、维基wiki编辑、问题issue等贡献。如有必要需告知采取措施的理由。
## 适用范围
此行为标准适用于本社区全部场合,以及在其他场合代表本社区的个人。
代表本社区的情形包括但不限于:使用官方电子邮件与社交平台、作为指定代表参与在线或线下活动。
## 贯彻落实
如遇滥用、骚扰等不当行为,请通过 contact@nonebot.dev 向我们举报。我们将迅速审议并调查全部投诉。
社区全体负责人有义务保密举报者信息。
## 指导方针
社区负责人将依据下列方案判断并处置违纪行为:
### 一、督促
**社区影响**:用语不当、举止不符合道德或不受社区欢迎。
**处理意见**:由社区负责人予以非公开的书面警告,阐明违纪事由、解释举止如何不妥。或要求公开道歉。
### 二、警告
**社区影响**:一起或多起事件中的违纪行为。
**处理意见**:警告继续违纪的后果、违纪者在特定时间内禁止与当事人往来、不得擅自与社区执法者往来,禁令涵盖社区内外、社交网络在内的一切联络。如有违反,可致封禁乃至开除。
### 三、封禁
**社区影响**:严重违纪行为,包括屡教不改。
**处理意见**:违纪者在特定时间内禁止与社区的任何往来或公开联络,禁止任何与当事人公开或私下往来,不得擅自与社区管理者往来。如有违反,可导致开除。
### 四、开除
**社区影响**:典型违纪行为,例如屡教不改、骚扰某个人、敌对或贬低某个群体。
**处理意见**:无限期禁止违纪者与项目社区的一切公开往来。
## 来源
本行为标准改编自[参与者公约][homepage]2.0 版,可在此查阅:[https://www.contributor-covenant.org/zh-cn/version/2/0/code_of_conduct.html][v2.0]
指导方针借鉴自[Mozilla 纪检分级][mozilla coc]。
此行为标准常见问题请洽:[https://www.contributor-covenant.org/faq][faq]。
另有诸译本:[https://www.contributor-covenant.org/translations][translations]。
[homepage]: https://www.contributor-covenant.org
[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
[mozilla coc]: https://github.com/mozilla/diversity
[faq]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

89
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,89 @@
# NoneBot2 贡献指南
首先,感谢你愿意为 NoneBot2 贡献自己的一份力量!
本指南旨在引导你更规范地向 NoneBot2 提交贡献,请务必认真阅读。
## 提交 Issue
在提交 Issue 前,我们建议你先查看 [FAQ](https://github.com/nonebot/discussions/discussions/13) 与 [已有的 Issues](https://github.com/nonebot/nonebot2/issues),以防重复提交。
### 报告问题、故障与漏洞
NoneBot2 仍然是一个不够稳定的开发中项目,如果你在使用过程中发现问题并确信是由 NoneBot2 引起的,欢迎提交 Issue。
### 建议功能
NoneBot2 还未进入正式版,欢迎在 Issue 中提议要加入哪些新功能。
为了让开发者更好地理解你的意图,请认真描述你所需要的特性,可能的话可以提出你认为可行的解决方案。
## Pull Request
NoneBot 使用 [poetry](https://python-poetry.org/) 管理项目依赖,由于 pre-commit 也经其管理,所以在此一并说明。
下面的命令能在已安装 poetry 和 yarn 的情况下帮你快速配置开发环境。
```bash
# 安装 python 依赖
poetry install
# 安装 pre-commit git hook
pre-commit install
# 安装 gitmoji git hook
yarn global add gitmoji-cli
gitmoji -i
```
### 使用 GitHub CodespacesDev Container
使用 GitHub Codespaces 选择 `NoneBot2` 项目,然后选择 `.devcontainer/devcontainer.json` 配置即可。
### Commit 规范
请确保你的每一个 commit 都能清晰地描述其意图,一个 commit 尽量只有一个意图。
NoneBot 的 commit message 格式遵循 [gitmoji](https://gitmoji.dev/) 规范,在创建 commit 时请牢记这一点。
### 工作流概述
`master` 分支为 NoneBot 的开发分支,在任何情况下都请不要直接修改 `master` 分支,而是创建一个目标分支为 `nonebot:master` 的 Pull Request 来提交修改。Pull Request 标题请尽量更改成中文,以便自动生成更新日志。
如果你不是 NoneBot 团队的成员,可在 fork 本仓库后,向本仓库的 `master` 分支发起 Pull Request注意遵循先前提到的 commit message 规范创建 commit。我们将在 code review 通过后通过 squash merge 方式将您的贡献合并到主分支。
### 撰写文档
NoneBot2 的文档使用 [docusaurus](https://docusaurus.io/),它有一些 [Markdown 特性](https://docusaurus.io/zh-CN/docs/markdown-features) 可能会帮助到你。
如果你需要在本地预览修改后的文档,可以使用 yarn 安装文档依赖后启动 dev server如下所示
```bash
yarn install
yarn start
```
NoneBot2 文档并没有具体的行文风格规范,但我们建议你尽量写得简单易懂。
以下是比较重要的排版规范。目前 NoneBot2 文档中仍有部分文档不完全遵守此规范,如果在阅读时发现欢迎提交 PR。
1. 中文与英文、数字、半角符号之间需要有空格。例:`NoneBot2 是一个可扩展的 Python 异步机器人框架。`
2. 若非英文整句,使用全角标点符号。例:`现在你可以看到机器人回复你“Hello, World !”。`
3. 直引号`「」`和弯引号`“”`都可接受,但同一份文件里应使用同种引号。
4. **不要使用斜体**,你不需要一种与粗体不同的强调。除此之外,你也可以考虑使用 docusaurus 提供的[告示](https://docusaurus.io/zh-CN/docs/markdown-features/admonitions)功能。
这是社区创始人 richardchien 的中文排版规范,可供参考:<https://stdrc.cc/style-guides/chinese>
如果你需要编辑器提示 Markdown 规范,可以安装 VSCode 上的 markdownlint 插件。
### 参与开发
NoneBot2 的代码风格遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 与 [PEP 484](https://www.python.org/dev/peps/pep-0484/) 规范,请确保你的代码风格和项目已有的代码保持一致,变量命名清晰,有适当的注释与测试代码。
## 为社区做贡献
你可以在 NoneBot 商店上架自己的适配器、插件、机器人,具体步骤可参考 [发布插件](https://v2.nonebot.dev/docs/advanced/publish-plugin) 一节。
我们仅对插件的兼容性进行简单测试,并会在下一个版本发布前对与该版本不兼容的插件作出处理。
虽然对插件的内容没有严格限制,但我们还是建议在上架插件之前先查看商店有无功能一致的插件。如果你想要上架商店的插件功能与现有插件不完全重合,请在插件说明中补充其与现有插件的区别。
同时,如果你参考或基于他人发行的代码进行开发,请注意遵守各代码所使用的开源许可协议。

View File

@@ -23,15 +23,18 @@ _✨ 跨平台 Python 异步机器人框架 ✨_
</a>
<img src="https://img.shields.io/badge/python-3.7.3+-blue" alt="python">
<a href="https://codecov.io/gh/nonebot/nonebot2">
<img src="https://codecov.io/gh/nonebot/nonebot2/branch/master/graph/badge.svg?token=2P0G0VS7N4"/>
<img src="https://codecov.io/gh/nonebot/nonebot2/branch/master/graph/badge.svg?token=2P0G0VS7N4" alt="codecov"/>
</a>
<a href="https://github.com/nonebot/nonebot2/actions/workflows/website-deploy.yml">
<img src="https://github.com/nonebot/nonebot2/actions/workflows/website-deploy.yml/badge.svg?branch=master&event=push" alt="site"/>
</a>
<a href="https://results.pre-commit.ci/latest/github/nonebot/nonebot2/master">
<img src="https://results.pre-commit.ci/badge/github/nonebot/nonebot2/master.svg" />
</a>
<br />
<a href="https://onebot.dev/">
<img src="https://img.shields.io/badge/OneBot-v11-black?style=social&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAIVBMVEUAAAAAAAADAwMHBwceHh4UFBQNDQ0ZGRkoKCgvLy8iIiLWSdWYAAAAAXRSTlMAQObYZgAAAQVJREFUSMftlM0RgjAQhV+0ATYK6i1Xb+iMd0qgBEqgBEuwBOxU2QDKsjvojQPvkJ/ZL5sXkgWrFirK4MibYUdE3OR2nEpuKz1/q8CdNxNQgthZCXYVLjyoDQftaKuniHHWRnPh2GCUetR2/9HsMAXyUT4/3UHwtQT2AggSCGKeSAsFnxBIOuAggdh3AKTL7pDuCyABcMb0aQP7aM4AnAbc/wHwA5D2wDHTTe56gIIOUA/4YYV2e1sg713PXdZJAuncdZMAGkAukU9OAn40O849+0ornPwT93rphWF0mgAbauUrEOthlX8Zu7P5A6kZyKCJy75hhw1Mgr9RAUvX7A3csGqZegEdniCx30c3agAAAABJRU5ErkJggg==" alt="cqhttp">
</a>
<a href="http://github.com/mamoe/mirai">
<img src="https://img.shields.io/badge/mirai-HTTP-lightgrey?style=social">
</a>
<a href="https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p">
<img src="https://img.shields.io/badge/%E9%92%89%E9%92%89-Bot-lightgrey?style=social&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAnFBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4jUzeAAAAM3RSTlMAQKSRaA+/f0YyFevh29R3cyklIfrlyrGsn41tVUs48c/HqJm9uZdhX1otGwkF9IN8V1CX0Q+IAAABY0lEQVRYw+3V2W7CMBAF0JuNQAhhX9OEfYdu9///rUVWpagE27Ef2gfO+0zGozsKnv6bMGzAhkNytIe5gDdzrwtTCwrbI8x4/NF668NAxgI3Q3UtFi3TyPwNQtPLUUmDd8YfqGLNe4v22XwEYb5zoOuF5baHq2UHtsKe5ivWfGAwrWu2mC34QM0PoCAuqZdOmiwV+5BLyMRtZ7dTSEcs48rzWfzwptMLyzpApka1SJ5FtR4kfCqNIBPEVDmqoqgwUYY5plQOlf6UEjNoOPnuKB6wzDyCrks///TDza8+PnR109WQdxLo8RKWq0PPnuXG0OXKQ6wWLFnCg75uYYbhmMIVVdQ709q33aHbGIj6Duz+2k1HQFX9VwqmY8xYsEJll2ahvhWgsjYLHFRXvIi2Qb0jzMQCzC3FAoydxCma88UCzE3JCWwkjCNYyMUCzHX4DiuTMawEwwhW6hnshPhjZzzJfAH0YacpbmRd7QAAAABJRU5ErkJggg==" alt="ding">
</a>
@@ -42,11 +45,14 @@ _✨ 跨平台 Python 异步机器人框架 ✨_
<img src="https://img.shields.io/badge/%E9%A3%9E%E4%B9%A6-Bot-lightgrey?style=social&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAk1BMVEX///8zMzNJSUlSUlJcXFxtbW0zMzNLS0szMzMzMzNBQUGVlZUzMzM1NTU0NDQzMzMzMzM0NDQ0NDQ0NDQ3NzdDQ0M0NDQ2NjY4ODg9PT0zMzM0NDQ5OTk7OzszMzM0NDQ3NzczMzM0NDQ0NDQ0NDQ0NDQ3Nzc2NjY4ODg2NjY7Ozs0NDQ6Ojo6Ojo3Nzc4ODgzMzNGdMWJAAAAMHRSTlMD6h0TDgr8GNf0KQbvhLT45KKTmm4jwHVJLdLFQzbcjFTgzsq7rl58T2kyqD46Y1riMDRhAAAFr0lEQVR42uzZWXKiUACF4YMyqKAQhyjOc7STmLP/1bVlLukESIJ3sLGKbwFU/Q8HuIBKpVKpVCqVSqVSqVQqlUqlUvmNM10Mcfda/U6TPdw3e9lb8ayLO+bPniYu+amjNcPd8U7PFhML0RE5uCvnaY/5SVt0WFvckcu0vxjiYmDxbu5cl2mn9UVHRMa4B2LaP3RYKD1vL6adccRFLSLL/izxxbRz7UXHimdLlFdq2mlvnztYRznZh96cP3G/dkxQRrOnR5c/c5eiQ+S2UTbe/sHir9zD1w6+okz8aXvMItyRqE46ApSHmHYRYdLRoPCMcrAP3TkLC6fpDp5QAn/EtItqij3UG/zgQZH5aWc7ZqJjzA9jKFGf9ppXC3I6uMB/Mzh2mpQQ/Mnp4BSy1Kctx4pFx5qfhA4kqE87pCyrldfBDm6sLqat2mGnttXHDfkvYtryooHo2PCrFm5lcNw1qWr1XUeEm7BH3QYVRJNGcOmoietNmNKDWeKFnCo6b3Wc1drW/NsOLpFRqmmT4xgfPFw42Q7XhkFi2kq2DtKcR2Y8wpTacRdQ3aZYB59ggiOmrS6sFevgDNr9GW6pzRAZdsQsC3rV3x4i6uQha8+sB2h9am9c6rVBDj9ixr5k007rIs+CGV65pl3wXjRi2hrKYjFtM/rI02JaW3XaPYtGtZHHY9qL0lN7QuO2yBMzpenLTvtkZNos+AY1ZcpObtoLtWmrj6TNlCOuJqZ9M3PkaDBlIBHCmwpHyHpjSgMS2ryhcIqsmsWULmR0eTPhK7LsMdMOKHdJM+nw8E+8ZoYDOT3eRDDDuz6HNt7VeszaQtYDJch+38WRZ51TDO+0Y54hylzy0XHib2JI83c0zIoLd1hAeUus1jenQe2HQ79Dg6wB3i1d/uoNpS2JrulgHWqcRxqySjoObrFjfUlLVrVrOtiGMmdCA+ZJx8hlEa9QZ2+oXcNLOkIWEUAHe22sYxqykGdoUV//5w6eoKlkTI3Gdbx7CVmQB10lDWqzSTpemyyoAW28ubYO++oOLqBPbUUtJknHrMnCRihdyaOTdAQsLHSgtSTS2BEHLK4DvQYWFW2lOtiHZi3Fko6fXCjgNVooV0nHl7tMBP1aAaXtJDvYgwGxdMmzLzu1JUyYNSU7IAwiiZ8OJrxKlTzI38QnMORFoqSn8Fh9gikvIa/UVejgDMZMQ9mOOa8WwKCRyysslF6hn2HSwZX4+ew1KGEPCSZKhoqHMw9mLd1rO8aUMYZpexbRV/2AsYBxy7/t3NtuglAQheFR6wEPVEQtaq1WxQNqnfd/urY08QJFYHZS15D9vcHckMzOz/QWA9/3jqHrbmbr1bT10a90ncQcoiclgKY/Vq81q6P2JJqfI+NHPqdDSMRzsEtIXmYGcQcQk2fwKgHxTCIVJGMWwTu6sWGxPSFx+QpkOfz3QcYEJWQhtGsbR5aKCIrHInjXNsSDeITFZ6ELYZEMAnltY8AyawKz4KJAr21IBzkRmB6LOIRGOEhIaHYsciA0uxIshwa/DLQIzrAEy2HswBIBwck9yNOvbWT4YgHEU4zbEiyHsQsXhnmKccmxp2cbxvb8CyDbMBXwD4hsw1BQguUw9s4Mk20YOTFQtmHiDJVtGJhjZRtyEVi2ITbhnLBOMd5qOvqXwz9RFy3bkJpU0LINeTCsJdvIztHVZhsJo77SbOPG6FNltpFQqMxsE7hmS+9ymJxE7XKYUGupyzZS1Kbaso00tbWybONBTadyObyjPlaVbTycRFO28Uh9oyjbEJ/E2JImnVDXy1y6zpHvW5E2npJsI5unI9vIwVe3HKYZaMg2clkoyDby6Wl5mcv0Bp9t5DVEzzZyG4JnG/kdsLONArbQ2UYRlwZwtlHIsoGbbRSdRNtymGbf0LYcpgleQbMNwdUCbcthmrP2j++VjqdSy7Isy7Isy4LxDTcBnqEPd5jdAAAAAElFTkSuQmCC" alt="feishu">
</a>
<a href="https://bot.q.qq.com/wiki/">
<img src="https://img.shields.io/badge/QQ%E9%A2%91%E9%81%93-Bot-lightgrey?style=social&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAC+lBMVEUAAAApRHRAbvYyVI4dMlsNGjcvTH5anN0/a5xdo+Vdpvpms/dMfvdcoPZjr/hJfu5krvA9Z+8/a+M9adxQjNdYmdVAbdU4XtRRjcxFd8wyVbM+aZowUJwpRJlZneRIevU5YORWl+1fqOZVle9ZnOpEdOk/aelepus/a+NQiuVKgeQ6YeRQi905X91EdtxAbthZnNlRjdk5YdpQjuhLgehhquc7Y+c6Y8k3XctWlcs0V8tJfMMzVsM9aMJVksdHebVKgLQyVJknP5REdKD///9irv9Ccf5EdP9GfP9jsf7+/f5SkP9mtf9GeP/+/vxJfv5Ukv9Ng/9boP9Gef1ls/9Ulf9Wl//+//5KgP9Nhv9dpP9Oiv9Tk/5Abv9Lg/9Fdv9NiP7///5Qj/7+/fxfpv9Nh/xhq/9QjP9Wm/79//1co/9ir/5fqf5bov9Qi//8/f1XmP1Wl/1ksv/7/v38/vv9/vlgqv9Znf9IfPzZ5fdeqP9nt/5anv5Xmf9Uk/1anvxpuf73/P34+/tot/9hrf1anvpMhvpSjv1pt/9ZnP1aofxTkfxNivza5/dOhPf+//1Ri/z+//vz+fvw9/tIf/v6/fpdofrI2PlYmfnF3Pe0y/Pm7/jW4/e0zvRapPxXlfpTkvpGevri7ffS3vVMiP5XnvxXnPtQivn3/Ph0r/dgpPZ1qfXi6/S9z/NYmf/z+v5Yn/7L2vlfmflUk/hXi/dRgvSw0fGnu+1dqP3t9Pthq/vA1vjc6vfU4vd4sfdepPdsn/dam/fU5fawzfRjjfRhi/NJhP0/a/y80fhTjfhrrfeXvvZuk/WyyPR9rvSqz/OcwfOmv/OSuPO0yfKguPCWr/BPi+9MheRKgv1gsPzq9PpgpvpVjvrN2/jG1vdonvbA0PSrx/OtxPCkxPDp8PvN4ftnuPuCufloqPiex/a3z/WPuvWQqvR2mfRplvReivSOqvOKufKGufKCrPKBoPJzlfFjr+88Ze6ftux8nOxxq/SGr/CFr/Cvx+3R19+QAAAARHRSTlMAEP4ZEwUEvC3S/v7+/Pv08PDXvJqampqSgEtJLS3f/Pz4+O/n5+bl4tTU1Lq6ure2trGdnZ2dlI6Afl5eXldMS0lJLRAR2gcAAAewSURBVFjDlZcFfBJRHMdvdnd3d3cn1qk3h4Et7EQ965h3KKgTQUGdOgYMHII6a5vO2d3d3d3d3X4+/t974A51xvfDu7vfP348HsdxR6VAulaN6lUu8SHVgQOpPpSoXK9Rq3TUf5CmSdWcB/oFcCBn1SZp/rG9aP6c/X5LzvxF/6W9Vqq2KZKq1t8sgvKT9pQt8gf9qb9QOVLWjux+K8oVSrE9bYNU7f6BVA3SpjD93O3+kdy//Ripcw34QefOnaViwM8iV+rf9Ffo7Kdr166du87vSgQGZGcIJocq/OIQlAv1EbAHDL/0hXzOhFxBP61f7vbJdJ0PFfN1RBB0MIPAUO7Alazvz+l0WY4+Pbthw4az66QG63Do6dEsuh+W9QO+//moVRet071L8phomUzBGPcGBwe3hxdmn5FVyGS0yZP0TodpHzy/kGQBygYjonUvbtpFraDwGUjYZ2JRVNSKK26+0EXjWNnkZciH26OjPy3gOZ5nVVCq+p0BzfK8wC/4FB2MLfL5+4sU7wkER7/dhN6aYxia0zKmvT0l7DUxHE1zHMcoVLJNb6ODUbB4EYpQHddcPHpXK5OpWNHp8CxbtmzmPqnBvpnLAIeTQdPT3j16EUer+yaQpT8i8pqAVi9h4cu1kZGR69bt7y9h/7p1EFz7cmEC+iTiwkgczUKmkC8ECkIs54wiI4j2j5EXQwj9QyCBNgCRIZbIj3ZRYET+nCVkP4TwKqTJHoJTXlbFscZzlv6WXr1CkpGKXhb0PozVynoj1SiTHV3lmvYC1JZnCQzNOG9a1BY1aAlKqbBYLEm8jWYSnpGypmBQTQ0sUp9iVCqr/bl60SK1UqlchIIzYCABB/BCIRR/breqVMwp9SIlUA2u39mVCPUWBlZQHz8DiT591t5euPD2WiUR6rXfiAKhnBHvhXVkrs9AGWX2dFTLGX0AZfxCTiaTHYwChTjl1LL8HZ+YccvJa52nfCL+IHyT3Lb4kVi1pAqOBPqMjPfSYHBmZBQSI6Nm0TTDXicCFCsy9HWfiDqGDPTxIzEFqTqDMVF6BTIYHEXUKhDMrMGEKddstIr2qajQYzT6sIeIrENVCsVc1VuRQeiU0FAYU4gBEkhfY5CBT4TCDJABkZWoCx0xxGB26BSspqyiFSowwAKUSNvoWUQQA1p/NRTLC9R5El+jZ5BBR9Qzffr0VbTICrNiQSC9yskKrN9g+hkoVOljp2N5njrUBdExlhj07UI4qGVZ7ePpREw/KLJa5xxfqu9sBRjMjCXJQ5SvaI3ehg0mELlz94oVu3ei3IQJE2J3eu0rdt/AAvAZoEMwp2L7Iias0aOlAYO+hHmrV89De5KVqAndicEaUhlLremOCJuHDeZ0D+v+V4jBPFK5hjrfA+E3CAvr8RfCwvwGWJ6nLmgQYTF6Gr4cZACCELN6Z+Kbr1/eJO5cHaOBBAyNpkeYZg86kWbGgAAuUBXDw8OXh4fH6BlkoNGgY43mxumkbR6HySiIomBKcHi2JZ2+odHELIdSzR5YbevMmHBMRar2EEyMXgXxOcvD4Viza88mnuNYhmNpDMMwIr9pzy4NJMOXIwMGDHBfbaog3k+LQzNgHscNmTZkSNwut0mgaQH6OK0NtmDG8yb3rrghY8YMiZuD5jozbhoSQwpShaeNAaYt3obWYIt58TQkzKe3JYisKCoUNKegwUFI8J7257agSi8SIAtT6UqPRxjc+De2axocLzYbzObjSVtX8Dyj1TICv2Jr0nEzsHLMmPFxZvS75d2GMSDGl4bbxypyuXy8wXBLUMloe6JBvtJgGB8BjitdiUfmuO/dc885kuhaaRg/fiVUwUi00zKVcAuqoLEKRVGN5UCE4bhJRdPiFrPZJZcQESEPwOUybxFpWmU6bsCZxuiyXnKEfIQ8wjWTZxSs6WRExNwRfiCByn4IOSRPwr+kit/qikChkvjmNc/Qob2HznWd5G1WgXbc2TF36A9GkI0fqLrj4AWrjT/pmju0d++heShEhqy9EUt3CwKso9F75OHSHTuWLp3bW8LcpSj28IjXCCsoCLuv4GjWDBSm5sCBSG6/zMNJDldjh2fBggVbEwdicOXAz1sh5HHwrBbON3bTdpKoCc1kCrg00xMHzICzwanD0VrTkoESlpi06L/dZuMUMoXjSaaNKIgmQMgzFti48corj1aEk88KJwpjXDJWwhIjSysUVi0HJ4bn1ZWNG1EwT/ItTpnhhCVuO8sKCjDgjNuHSwAD9M8lsJzdvcQXKyO502ueaTQwaNDmza/dl50+g9EStsMMwMB52f168+bho4dDKFNzSkKBQX4mH37w6MT69etPHCaacBiHHj04PHnQoNGkrkDgjWb6NslMJrSRhjZPHhQYSp+WCiCoWHJu2LBhl2BIDSASGMoY9MvNdjFfKUA2RCRHpQbFfne7nrHDqA4dOozCG/Qie6mAQURG6P+VoPS4DED7wONAkT4ohUeeAtm6/QPZCqSlUqJF+U6dOnVDA23Q/ldRvsUfH/vyZuv0R7LlDaL+TOsamSdNmjTuBwEic43W1N/JkDfH1EmIqT78xznyZvjXh+9m6XNM/Ikc6Zulof6DdIUb1s1Y6n3m+/czvy+VsW7Dwik9/n8HzjZEy9x05tIAAAAASUVORK5CYII=" alt="QQ频道">
<img src="https://img.shields.io/badge/QQ%E9%A2%91%E9%81%93-Bot-lightgrey?style=social&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMTIuODIgMTMwLjg5Ij48ZyBkYXRhLW5hbWU9IuWbvuWxgiAyIj48ZyBkYXRhLW5hbWU9IuWbvuWxgiAxIj48cGF0aCBkPSJNNTUuNjMgMTMwLjhjLTcgMC0xMy45LjA4LTIwLjg2IDAtMTkuMTUtLjI1LTMxLjcxLTExLjQtMzQuMjItMzAuMy00LjA3LTMwLjY2IDE0LjkzLTU5LjIgNDQuODMtNjYuNjQgMi0uNTEgNS4yMS0uMzEgNS4yMS0xLjYzIDAtMi4xMy4xNC0yLjEzLjE0LTUuNTcgMC0uODktMS4zLTEuNDYtMi4yMi0yLjMxLTYuNzMtNi4yMy03LjY3LTEzLjQxLTEtMjAuMTggNS40LTUuNTIgMTEuODctNS40IDE3LjgtLjU5IDYuNDkgNS4yNiA2LjMxIDEzLjA4LS44NiAyMS0uNjguNzQtMS43OCAxLjYtMS43OCAyLjY3djQuMjFjMCAxLjM1IDIuMiAxLjYyIDQuNzkgMi4zNSAzMS4wOSA4LjY1IDQ4LjE3IDM0LjEzIDQ1IDY2LjM3LTEuNzYgMTguMTUtMTQuNTYgMzAuMjMtMzIuNyAzMC42My04LjAyLjE5LTE2LjA3LS4wMS0yNC4xMy0uMDF6IiBmaWxsPSIjMDI5OWZlIi8+PHBhdGggZD0iTTMxLjQ2IDExOC4zOGMtMTAuNS0uNjktMTYuOC02Ljg2LTE4LjM4LTE3LjI3LTMtMTkuNDIgMi43OC0zNS44NiAxOC40Ni00Ny44MyAxNC4xNi0xMC44IDI5Ljg3LTEyIDQ1LjM4LTMuMTkgMTcuMjUgOS44NCAyNC41OSAyNS44MSAyNCA0NS4yOS0uNDkgMTUuOS04LjQyIDIzLjE0LTI0LjM4IDIzLjUtNi41OS4xNC0xMy4xOSAwLTE5Ljc5IDAiIGZpbGw9IiNmZWZlZmUiLz48cGF0aCBkPSJNNDYuMDUgNzkuNThjLjA5IDUgLjIzIDkuODItNyA5Ljc3LTcuODItLjA2LTYuMS01LjY5LTYuMjQtMTAuMTktLjE1LTQuODItLjczLTEwIDYuNzMtOS44NHM2LjM3IDUuNTUgNi41MSAxMC4yNnoiIGZpbGw9IiMxMDlmZmUiLz48cGF0aCBkPSJNODAuMjcgNzkuMjdjLS41MyAzLjkxIDEuNzUgOS42NC01Ljg4IDEwLTcuNDcuMzctNi44MS00LjgyLTYuNjEtOS41LjItNC4zMi0xLjgzLTEwIDUuNzgtMTAuNDJzNi41OSA0Ljg5IDYuNzEgOS45MnoiIGZpbGw9IiMwODljZmUiLz48L2c+PC9nPjwvc3ZnPg==" alt="QQ频道">
</a>
<br />
<a href="https://jq.qq.com/?_wv=1027&k=5OFifDh">
<img src="https://img.shields.io/badge/qq%E7%BE%A4-768887710-orange?style=flat-square" alt="QQ Chat">
<img src="https://img.shields.io/badge/QQ%E7%BE%A4-768887710-orange?style=flat-square" alt="QQ Chat Group">
</a>
<a href="https://qun.qq.com/qqweb/qunpro/share?_wv=3&_wwv=128&appChannel=share&inviteCode=7b4a3&appChannel=share&businessType=9&from=246610&biz=ka">
<img src="https://img.shields.io/badge/QQ%E9%A2%91%E9%81%93-NoneBot-5492ff?style=flat-square" alt="QQ Channel">
</a>
<a href="https://t.me/botuniverse">
<img src="https://img.shields.io/badge/telegram-botuniverse-blue?style=flat-square" alt="Telegram Channel">
@@ -59,14 +65,18 @@ _✨ 跨平台 Python 异步机器人框架 ✨_
<p align="center">
<a href="https://v2.nonebot.dev/">文档</a>
·
<a href="https://v2.nonebot.dev/guide/installation.html">安装</a>
<a href="https://v2.nonebot.dev/docs/start/installation">安装</a>
·
<a href="https://v2.nonebot.dev/guide/getting-started.html">开始使用</a>
<a href="https://v2.nonebot.dev/docs/tutorial/create-project">开始使用</a>
·
<a href="#插件">文档打不开?</a>
</p>
<!-- TODO: asciinema for install -->
<p align="center">
<a href="https://asciinema.org/a/464654">
<img src="https://v2.nonebot.dev/img/setup.svg">
</a>
</p>
## 简介
@@ -80,7 +90,6 @@ NoneBot2 是一个现代、跨平台、可扩展的 Python 聊天机器人框架
- 社区丰富:社区用户众多,直接和间接用户超过十万人,每天都有大量的活跃用户 ([社区资源](#社区资源))
- 海纳百川:一个框架,支持多个聊天软件平台,可自定义通信协议
- [OneBot 协议](https://onebot.dev/) (QQ 等)
- [Mirai-API-HTTP 协议](https://github.com/project-mirai/mirai-api-http)
- [钉钉](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p)
- [Telegram](https://core.telegram.org/bots/api)
- [飞书](https://open.feishu.cn/document/home/index)
@@ -150,26 +159,24 @@ NoneBot2 不是 NoneBot1 的替代品。事实上,它们都在被积极的维
- [文档镜像(中国境内)](https://nb2.baka.icu)
- [文档镜像(Vercel)](https://nonebot2-vercel-mirror.vercel.app)
- 其他插件请查看 [商店](https://v2.nonebot.dev/store.html)
- 其他插件请查看 [商店](https://v2.nonebot.dev/store)
## 许可证
`NoneBot` 采用 `MIT` 许可证进行开源
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```text
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
## 贡献
如果你在使用过程中发现任何问题,可以 [提交 Issue](https://github.com/nonebot/nonebot2/issues/new) 或自行 Fork 修改后提交 Pull Request。
如果你要提交 Pull Request请确保你的代码风格和项目已有的代码保持一致遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 与 [PEP 484](https://www.python.org/dev/peps/pep-0484/),变量命名清晰,有适当的注释与测试代码,**并且请以 `dev` 分支作为 Pull Request 目标分支**。
<!--TODO: Add a CONTRIBUTING.md-->
请参考 [贡献指南](./CONTRIBUTING.md)
### 鸣谢

View File

@@ -1,20 +0,0 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@@ -1,12 +0,0 @@
\-\-\-
sidebar_position: 1
id: index
slug: /api
\-\-\-
NoneBot 模块
===============
.. automodule:: nonebot
:members:
:show-inheritance:

View File

@@ -1,43 +0,0 @@
\-\-\-
id: index
slug: /api/adapters/
\-\-\-
NoneBot.adapters 模块
=====================
.. automodule:: nonebot.adapters
:members:
:private-members:
:special-members: __init__
:show-inheritance:
.. automodule:: nonebot.adapters._adapter
:members:
:private-members:
:special-members: __init__
:show-inheritance:
.. automodule:: nonebot.adapters._bot
:members:
:private-members:
:special-members: __init__
:show-inheritance:
.. automodule:: nonebot.adapters._message
:members:
:private-members:
:special-members: __init__
:show-inheritance:
.. automodule:: nonebot.adapters._event
:members:
:private-members:
:special-members: __init__
:show-inheritance:
.. automodule:: nonebot.adapters._template
:members:
:private-members:
:special-members: __init__
:show-inheritance:

View File

@@ -1,82 +0,0 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
# -- Project information -----------------------------------------------------
project = 'nonebot'
copyright = '2020, richardchien'
author = 'richardchien'
# The short X.Y version
version = '2.0.0'
# The full version, including alpha/beta/rc tags
release = '2.0.0'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.todo',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'zh_CN'
master_doc = "README"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# html_baseurl = '/api/'
# -- Extension configuration -------------------------------------------------
# -- Options for autodoc extension ----------------------------------------------
autodoc_default_options = {'member-order': 'bysource'}
autodoc_inherit_docstrings = False
autodoc_typehints = 'none'
# -- Options for todo extension ----------------------------------------------
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

View File

@@ -1,10 +0,0 @@
\-\-\-
sidebar_position: 2
\-\-\-
NoneBot.config 模块
===================
.. automodule:: nonebot.config
:members: Env, Config
:show-inheritance:

View File

@@ -1,11 +0,0 @@
\-\-\-
sidebar_position: 8
\-\-\-
NoneBot.dependencies 模块
====================
.. automodule:: nonebot.dependencies
:members:
:private-members:
:show-inheritance:

View File

@@ -1,13 +0,0 @@
\-\-\-
id: index
slug: /api/drivers/
\-\-\-
NoneBot.drivers 模块
=====================
.. automodule:: nonebot.drivers
:members:
:private-members:
:special-members: __init__
:show-inheritance:

View File

@@ -1,9 +0,0 @@
NoneBot.drivers.aiohttp 模块
=============================
.. automodule:: nonebot.drivers.aiohttp
:members:
:private-members:
:show-inheritance:

View File

@@ -1,9 +0,0 @@
NoneBot.drivers.fastapi 模块
=============================
.. automodule:: nonebot.drivers.fastapi
:members:
:private-members:
:show-inheritance:

View File

@@ -1,9 +0,0 @@
NoneBot.drivers.httpx 模块
=============================
.. automodule:: nonebot.drivers.httpx
:members:
:private-members:
:show-inheritance:

View File

@@ -1,9 +0,0 @@
NoneBot.drivers.quart 模块
==========================
.. automodule:: nonebot.drivers.quart
:members:
:private-members:
:show-inheritance:

View File

@@ -1,9 +0,0 @@
NoneBot.drivers.websockets 模块
=============================
.. automodule:: nonebot.drivers.websockets
:members:
:private-members:
:show-inheritance:

View File

@@ -1,10 +0,0 @@
\-\-\-
sidebar_position: 12
\-\-\-
NoneBot.exception 模块
======================
.. automodule:: nonebot.exception
:members:
:show-inheritance:

View File

@@ -1,10 +0,0 @@
\-\-\-
sidebar_position: 9
\-\-\-
NoneBot.log 模块
=================
.. automodule:: nonebot.log
:members:
:show-inheritance:

View File

@@ -1,35 +0,0 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

View File

@@ -1,12 +0,0 @@
\-\-\-
sidebar_position: 5
\-\-\-
NoneBot.matcher 模块
====================
.. automodule:: nonebot.matcher
:members:
:private-members:
:special-members: __init__
:show-inheritance:

View File

@@ -1,10 +0,0 @@
\-\-\-
sidebar_position: 4
\-\-\-
NoneBot.message 模块
======================
.. automodule:: nonebot.message
:members:
:show-inheritance:

View File

@@ -1,11 +0,0 @@
\-\-\-
sidebar_position: 7
\-\-\-
NoneBot.permission 模块
=======================
.. automodule:: nonebot.permission
:members:
:show-inheritance:
:special-members:

View File

@@ -1,31 +0,0 @@
\-\-\-
sidebar_position: 3
\-\-\-
NoneBot.plugin 模块
====================
.. automodule:: nonebot.plugin
:members:
:show-inheritance:
:special-members: __init__
.. automodule:: nonebot.plugin.plugin
:members:
:show-inheritance:
:special-members: __init__
.. automodule:: nonebot.plugin.on
:members:
:show-inheritance:
:special-members: __init__
.. automodule:: nonebot.plugin.load
:members:
:show-inheritance:
:special-members: __init__
.. automodule:: nonebot.plugin.export
:members:
:show-inheritance:
:special-members: __init__

View File

@@ -1,11 +0,0 @@
\-\-\-
sidebar_position: 6
\-\-\-
NoneBot.rule 模块
====================
.. automodule:: nonebot.rule
:members:
:special-members:
:show-inheritance:

View File

@@ -1,10 +0,0 @@
\-\-\-
sidebar_position: 11
\-\-\-
NoneBot.typing 模块
===================
.. automodule:: nonebot.typing
:members:
:show-inheritance:

View File

@@ -1,10 +0,0 @@
\-\-\-
sidebar_position: 10
\-\-\-
NoneBot.utils 模块
==================
.. automodule:: nonebot.utils
:members:
:show-inheritance:

View File

@@ -1,31 +1,40 @@
"""
快捷导入
========
"""本模块主要定义了 NoneBot 启动所需函数,供 bot 入口文件调用。
为方便使用,``nonebot`` 模块从子模块导入了部分内容
## 快捷导入
- ``on_message`` => ``nonebot.plugin.on_message``
- ``on_notice`` => ``nonebot.plugin.on_notice``
- ``on_request`` => ``nonebot.plugin.on_request``
- ``on_metaevent`` => ``nonebot.plugin.on_metaevent``
- ``on_startswith`` => ``nonebot.plugin.on_startswith``
- ``on_endswith`` => ``nonebot.plugin.on_endswith``
- ``on_keyword`` => ``nonebot.plugin.on_keyword``
- ``on_command`` => ``nonebot.plugin.on_command``
- ``on_shell_command`` => ``nonebot.plugin.on_shell_command``
- ``on_regex`` => ``nonebot.plugin.on_regex``
- ``CommandGroup`` => ``nonebot.plugin.CommandGroup``
- ``Matchergroup`` => ``nonebot.plugin.MatcherGroup``
- ``load_plugin`` => ``nonebot.plugin.load_plugin``
- ``load_plugins`` => ``nonebot.plugin.load_plugins``
- ``load_all_plugins`` => ``nonebot.plugin.load_all_plugins``
- ``load_from_json`` => ``nonebot.plugin.load_from_json``
- ``load_from_toml`` => ``nonebot.plugin.load_from_toml``
- ``load_builtin_plugins`` => ``nonebot.plugin.load_builtin_plugins``
- ``get_plugin`` => ``nonebot.plugin.get_plugin``
- ``get_loaded_plugins`` => ``nonebot.plugin.get_loaded_plugins``
- ``export`` => ``nonebot.plugin.export``
- ``require`` => ``nonebot.plugin.require``
为方便使用,本模块从子模块导入了部分内容,以下内容可以直接通过本模块导入:
- `on` => {ref}``on` <nonebot.plugin.on.on>`
- `on_metaevent` => {ref}``on_metaevent` <nonebot.plugin.on.on_metaevent>`
- `on_message` => {ref}``on_message` <nonebot.plugin.on.on_message>`
- `on_notice` => {ref}``on_notice` <nonebot.plugin.on.on_notice>`
- `on_request` => {ref}``on_request` <nonebot.plugin.on.on_request>`
- `on_startswith` => {ref}``on_startswith` <nonebot.plugin.on.on_startswith>`
- `on_endswith` => {ref}``on_endswith` <nonebot.plugin.on.on_endswith>`
- `on_fullmatch` => {ref}``on_fullmatch` <nonebot.plugin.on.on_fullmatch>`
- `on_keyword` => {ref}``on_keyword` <nonebot.plugin.on.on_keyword>`
- `on_command` => {ref}``on_command` <nonebot.plugin.on.on_command>`
- `on_shell_command` => {ref}``on_shell_command` <nonebot.plugin.on.on_shell_command>`
- `on_regex` => {ref}``on_regex` <nonebot.plugin.on.on_regex>`
- `CommandGroup` => {ref}``CommandGroup` <nonebot.plugin.on.CommandGroup>`
- `Matchergroup` => {ref}``MatcherGroup` <nonebot.plugin.on.MatcherGroup>`
- `load_plugin` => {ref}``load_plugin` <nonebot.plugin.load.load_plugin>`
- `load_plugins` => {ref}``load_plugins` <nonebot.plugin.load.load_plugins>`
- `load_all_plugins` => {ref}``load_all_plugins` <nonebot.plugin.load.load_all_plugins>`
- `load_from_json` => {ref}``load_from_json` <nonebot.plugin.load.load_from_json>`
- `load_from_toml` => {ref}``load_from_toml` <nonebot.plugin.load.load_from_toml>`
- `load_builtin_plugin` => {ref}``load_builtin_plugin` <nonebot.plugin.load.load_builtin_plugin>`
- `load_builtin_plugins` => {ref}``load_builtin_plugins` <nonebot.plugin.load.load_builtin_plugins>`
- `get_plugin` => {ref}``get_plugin` <nonebot.plugin.plugin.get_plugin>`
- `get_plugin_by_module_name` => {ref}``get_plugin_by_module_name` <nonebot.plugin.plugin.get_plugin_by_module_name>`
- `get_loaded_plugins` => {ref}``get_loaded_plugins` <nonebot.plugin.plugin.get_loaded_plugins>`
- `get_available_plugin_names` => {ref}``get_available_plugin_names` <nonebot.plugin.plugin.get_available_plugin_names>`
- `export` => {ref}``export` <nonebot.plugin.export.export>`
- `require` => {ref}``require` <nonebot.plugin.load.require>`
FrontMatter:
sidebar_position: 0
description: nonebot 模块
"""
import importlib
@@ -51,25 +60,20 @@ _driver: Optional[Driver] = None
def get_driver() -> Driver:
"""
:说明:
"""获取全局 {ref}`nonebot.drivers.Driver` 实例。
获取全局 Driver 对象。可用于在计划任务的回调中获取当前 Driver 对象
可用于在计划任务的回调等情形中获取当前 {ref}`nonebot.drivers.Driver` 实例
:返回:
返回:
全局 {ref}`nonebot.drivers.Driver` 对象
* ``Driver``: 全局 Driver 对象
:异常:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
:用法:
.. code-block:: python
异常:
ValueError: 全局 {ref}`nonebot.drivers.Driver` 对象尚未初始化 ({ref}`nonebot.init <nonebot.init>` 尚未调用)
用法:
```python
driver = nonebot.get_driver()
```
"""
if _driver is None:
raise ValueError("NoneBot has not been initialized.")
@@ -77,25 +81,19 @@ def get_driver() -> Driver:
def get_app() -> Any:
"""
:说明:
"""获取全局 {ref}`nonebot.drivers.ReverseDriver` 对应的 Server App 对象。
获取全局 Driver 对应 Server App 对象。
返回:
Server App 对象
:返回:
* ``Any``: Server App 对象
:异常:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
:用法:
.. code-block:: python
异常:
AssertionError: 全局 Driver 对象不是 {ref}`nonebot.drivers.ReverseDriver` 类型
ValueError: 全局 {ref}`nonebot.drivers.Driver` 对象尚未初始化 ({ref}`nonebot.init <nonebot.init>` 尚未调用)
用法:
```python
app = nonebot.get_app()
```
"""
driver = get_driver()
assert isinstance(
@@ -105,25 +103,19 @@ def get_app() -> Any:
def get_asgi() -> Any:
"""
:说明:
"""获取全局 {ref}`nonebot.drivers.ReverseDriver` 对应 [ASGI](https://asgi.readthedocs.io/) 对象。
获取全局 Driver 对应 Asgi 对象。
返回:
ASGI 对象
:返回:
* ``Any``: Asgi 对象
:异常:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
:用法:
.. code-block:: python
异常:
AssertionError: 全局 Driver 对象不是 {ref}`nonebot.drivers.ReverseDriver` 类型
ValueError: 全局 {ref}`nonebot.drivers.Driver` 对象尚未初始化 ({ref}`nonebot.init <nonebot.init>` 尚未调用)
用法:
```python
asgi = nonebot.get_asgi()
```
"""
driver = get_driver()
assert isinstance(
@@ -133,32 +125,28 @@ def get_asgi() -> Any:
def get_bot(self_id: Optional[str] = None) -> Bot:
"""
:说明:
"""获取一个连接到 NoneBot 的 {ref}`nonebot.adapters.Bot` 对象。
当提供 self_id 时,此函数是 get_bots()[self_id] 的简写;当不提供时,返回一个 Bot。
当提供 `self_id` 时,此函数是 `get_bots()[self_id]` 的简写;
当不提供时,返回一个 {ref}`nonebot.adapters.Bot`。
:参数:
参数:
self_id: 用来识别 {ref}`nonebot.adapters.Bot` 的 {ref}`nonebot.adapters.Bot.self_id` 属性
* ``self_id: Optional[str]``: 用来识别 Bot 的 ID
返回:
{ref}`nonebot.adapters.Bot` 对象
:返回:
异常:
KeyError: 对应 self_id 的 Bot 不存在
ValueError: 没有传入 self_id 且没有 Bot 可用
ValueError: 全局 {ref}`nonebot.drivers.Driver` 对象尚未初始化 ({ref}`nonebot.init <nonebot.init>` 尚未调用)
* ``Bot``: Bot 对象
:异常:
* ``KeyError``: 对应 ID 的 Bot 不存在
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
* ``ValueError``: 没有传入 ID 且没有 Bot 可用
:用法:
.. code-block:: python
assert nonebot.get_bot('12345') == nonebot.get_bots()['12345']
用法:
```python
assert nonebot.get_bot("12345") == nonebot.get_bots()["12345"]
another_unspecified_bot = nonebot.get_bot()
```
"""
bots = get_bots()
if self_id is not None:
@@ -171,25 +159,18 @@ def get_bot(self_id: Optional[str] = None) -> Bot:
def get_bots() -> Dict[str, Bot]:
"""
:说明:
"""获取所有连接到 NoneBot 的 {ref}`nonebot.adapters.Bot` 对象。
获取所有通过 ws 连接 NoneBot 的 Bot 对象。
返回:
一个以 {ref}`nonebot.adapters.Bot.self_id` 为键,{ref}`nonebot.adapters.Bot` 对象为值的字典
:返回:
* ``Dict[str, Bot]``: 一个以字符串 ID 为键Bot 对象为值的字典
:异常:
* ``ValueError``: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
:用法:
.. code-block:: python
异常:
ValueError: 全局 {ref}`nonebot.drivers.Driver` 对象尚未初始化 ({ref}`nonebot.init <nonebot.init>` 尚未调用)
用法:
```python
bots = nonebot.get_bots()
```
"""
driver = get_driver()
return driver.bots
@@ -226,31 +207,21 @@ def _resolve_combine_expr(obj_str: str) -> Type[Driver]:
return combine_driver(DriverClass, *mixins)
def init(*, _env_file: Optional[str] = None, **kwargs):
"""
:说明:
初始化 NoneBot 以及 全局 Driver 对象。
def init(*, _env_file: Optional[str] = None, **kwargs: Any) -> None:
"""初始化 NoneBot 以及 全局 {ref}`nonebot.drivers.Driver` 对象。
NoneBot 将会从 .env 文件中读取环境信息,并使用相应的 env 文件配置。
也可以传入自定义的 _env_file 来指定 NoneBot 从该文件读取配置。
也可以传入自定义的 `_env_file` 来指定 NoneBot 从该文件读取配置。
:参数:
* ``_env_file: Optional[str]``: 配置文件名,默认从 .env.{env_name} 中读取配置
* ``**kwargs``: 任意变量,将会存储到 Config 对象里
:返回:
- ``None``
:用法:
.. code-block:: python
参数:
_env_file: 配置文件名,默认从 `.env.{env_name}` 中读取配置
kwargs: 任意变量,将会存储到 {ref}`nonebot.drivers.Driver.config` 对象里
用法:
```python
nonebot.init(database=Database(...))
```
"""
global _driver
if not _driver:
@@ -275,32 +246,22 @@ def init(*, _env_file: Optional[str] = None, **kwargs):
def run(*args: Any, **kwargs: Any) -> None:
"""
:说明:
"""启动 NoneBot即运行全局 {ref}`nonebot.drivers.Driver` 对象。
启动 NoneBot即运行全局 Driver 对象。
:参数:
* ``*args``: 传入 Driver.run 的位置参数
* ``**kwargs``: 传入 Driver.run 的命名参数
:返回:
- ``None``
:用法:
.. code-block:: python
参数:
args: 传入 {ref}`nonebot.drivers.Driver.run` 的位置参数
kwargs: 传入 {ref}`nonebot.drivers.Driver.run` 的命名参数
用法:
```python
nonebot.run(host="127.0.0.1", port=8080)
```
"""
logger.success("Running NoneBot...")
get_driver().run(*args, **kwargs)
import nonebot.params as params
from nonebot.plugin import on as on
from nonebot.plugin import export as export
from nonebot.plugin import require as require
from nonebot.plugin import on_regex as on_regex
@@ -315,6 +276,7 @@ from nonebot.plugin import on_endswith as on_endswith
from nonebot.plugin import CommandGroup as CommandGroup
from nonebot.plugin import MatcherGroup as MatcherGroup
from nonebot.plugin import load_plugins as load_plugins
from nonebot.plugin import on_fullmatch as on_fullmatch
from nonebot.plugin import on_metaevent as on_metaevent
from nonebot.plugin import on_startswith as on_startswith
from nonebot.plugin import load_from_json as load_from_json
@@ -322,4 +284,9 @@ from nonebot.plugin import load_from_toml as load_from_toml
from nonebot.plugin import load_all_plugins as load_all_plugins
from nonebot.plugin import on_shell_command as on_shell_command
from nonebot.plugin import get_loaded_plugins as get_loaded_plugins
from nonebot.plugin import load_builtin_plugin as load_builtin_plugin
from nonebot.plugin import load_builtin_plugins as load_builtin_plugins
from nonebot.plugin import get_plugin_by_module_name as get_plugin_by_module_name
from nonebot.plugin import get_available_plugin_names as get_available_plugin_names
__autodoc__ = {"internal": False}

View File

@@ -1,8 +1,10 @@
"""
协议适配基类
============
"""本模块定义了协议适配基类,各协议请继承以下基类。
各协议请继承以下基类,并使用 ``driver.register_adapter`` 注册适配器
使用 {ref}`nonebot.drivers.Driver.register_adapter` 注册适配器
FrontMatter:
sidebar_position: 0
description: nonebot.adapters 模块
"""
from typing import Iterable
@@ -20,9 +22,18 @@ except ImportError:
except Exception:
pass
from ._bot import Bot as Bot
from ._event import Event as Event
from ._adapter import Adapter as Adapter
from ._message import Message as Message
from ._message import MessageSegment as MessageSegment
from ._template import MessageTemplate as MessageTemplate
from nonebot.internal.adapter import Bot as Bot
from nonebot.internal.adapter import Event as Event
from nonebot.internal.adapter import Adapter as Adapter
from nonebot.internal.adapter import Message as Message
from nonebot.internal.adapter import MessageSegment as MessageSegment
from nonebot.internal.adapter import MessageTemplate as MessageTemplate
__autodoc__ = {
"Bot": True,
"Event": True,
"Adapter": True,
"Message": True,
"MessageSegment": True,
"MessageTemplate": True,
}

View File

@@ -1,137 +0,0 @@
import abc
from pydantic import BaseModel
from ._message import Message
from nonebot.utils import DataclassEncoder
class Event(abc.ABC, BaseModel):
"""Event 基类。提供获取关键信息的方法,其余信息可直接获取。"""
class Config:
extra = "allow"
json_encoders = {Message: DataclassEncoder}
@abc.abstractmethod
def get_type(self) -> str:
"""
:说明:
获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。
:返回:
* ``Literal["message", "notice", "request", "meta_event"]``
* 其他自定义 ``str``
"""
raise NotImplementedError
@abc.abstractmethod
def get_event_name(self) -> str:
"""
:说明:
获取事件名称的方法。
:返回:
* ``str``
"""
raise NotImplementedError
@abc.abstractmethod
def get_event_description(self) -> str:
"""
:说明:
获取事件描述的方法,通常为事件具体内容。
:返回:
* ``str``
"""
raise NotImplementedError
def __str__(self) -> str:
return f"[{self.get_event_name()}]: {self.get_event_description()}"
def get_log_string(self) -> str:
"""
:说明:
获取事件日志信息的方法,通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 ``NoLogException`` 异常。
:返回:
* ``str``
:异常:
- ``NoLogException``
"""
return f"[{self.get_event_name()}]: {self.get_event_description()}"
@abc.abstractmethod
def get_user_id(self) -> str:
"""
:说明:
获取事件主体 id 的方法,通常是用户 id 。
:返回:
* ``str``
"""
raise NotImplementedError
@abc.abstractmethod
def get_session_id(self) -> str:
"""
:说明:
获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。
:返回:
* ``str``
"""
raise NotImplementedError
@abc.abstractmethod
def get_message(self) -> "Message":
"""
:说明:
获取事件消息内容的方法。
:返回:
* ``Message``
"""
raise NotImplementedError
def get_plaintext(self) -> str:
"""
:说明:
获取消息纯文本的方法,通常不需要修改,默认通过 ``get_message().extract_plain_text`` 获取。
:返回:
* ``str``
"""
return self.get_message().extract_plain_text()
@abc.abstractmethod
def is_tome(self) -> bool:
"""
:说明:
获取事件是否与机器人有关的方法。
:返回:
* ``bool``
"""
raise NotImplementedError

View File

@@ -1,232 +0,0 @@
import abc
from copy import deepcopy
from dataclasses import field, asdict, dataclass
from typing import (
Any,
Dict,
List,
Type,
Union,
Generic,
Mapping,
TypeVar,
Iterable,
)
from ._template import MessageTemplate
T = TypeVar("T")
TMS = TypeVar("TMS", covariant=True)
TM = TypeVar("TM", bound="Message")
@dataclass
class MessageSegment(Mapping, abc.ABC, Generic[TM]):
"""消息段基类"""
type: str
"""
- 类型: ``str``
- 说明: 消息段类型
"""
data: Dict[str, Any] = field(default_factory=lambda: {})
"""
- 类型: ``Dict[str, Union[str, list]]``
- 说明: 消息段数据
"""
@classmethod
@abc.abstractmethod
def get_message_class(cls) -> Type[TM]:
raise NotImplementedError
@abc.abstractmethod
def __str__(self) -> str:
"""该消息段所代表的 str在命令匹配部分使用"""
raise NotImplementedError
def __len__(self) -> int:
return len(str(self))
def __ne__(self: T, other: T) -> bool:
return not self == other
def __add__(self, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:
return self.get_message_class()(self) + other # type: ignore
def __radd__(self, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:
return self.get_message_class()(other) + self # type: ignore
def __getitem__(self, key: str):
return getattr(self, key)
def __setitem__(self, key: str, value: Any):
return setattr(self, key, value)
def __iter__(self):
yield from asdict(self).keys()
def __contains__(self, key: Any) -> bool:
return key in asdict(self).keys()
def get(self, key: str, default: Any = None):
return getattr(self, key, default)
def keys(self):
return asdict(self).keys()
def values(self):
return asdict(self).values()
def items(self):
return asdict(self).items()
def copy(self: T) -> T:
return deepcopy(self)
@abc.abstractmethod
def is_text(self) -> bool:
raise NotImplementedError
class Message(List[TMS], abc.ABC):
"""消息数组"""
def __init__(
self: TM,
message: Union[str, None, Mapping, Iterable[Mapping], TMS, TM, Any] = None,
*args,
**kwargs,
):
"""
:参数:
* ``message: Union[str, list, dict, MessageSegment, Message, Any]``: 消息内容
"""
super().__init__(*args, **kwargs)
if message is None:
return
elif isinstance(message, Message):
self.extend(message)
elif isinstance(message, MessageSegment):
self.append(message)
else:
self.extend(self._construct(message))
@classmethod
def template(cls: Type[TM], format_string: Union[str, TM]) -> MessageTemplate[TM]:
"""
:说明:
根据创建消息模板, 用法和 ``str.format`` 大致相同, 但是可以输出消息对象, 并且支持以 ``Message`` 对象作为消息模板
并且提供了拓展的格式化控制符, 可以用适用于该消息类型的 ``MessageSegment`` 的工厂方法创建消息
:示例:
.. code-block:: python
>>> Message.template("{} {}").format("hello", "world") # 基础演示
Message(MessageSegment(type='text', data={'text': 'hello world'}))
>>> Message.template("{} {}").format(MessageSegment.image("file///..."), "world") # 支持消息段等对象
Message(MessageSegment(type='image', data={'file': 'file///...'}), MessageSegment(type='text', data={'text': 'world'}))
>>> Message.template( # 支持以Message对象作为消息模板
... MessageSegment.text('test {event.user_id}') + MessageSegment.face(233) +
... MessageSegment.text('test {event.message}')).format(event={'user_id':123456, 'message':'hello world'})
Message(MessageSegment(type='text', data={'text': 'test 123456'}),
MessageSegment(type='face', data={'face': 233}),
MessageSegment(type='text', data={'text': 'test hello world'}))
>>> Message.template("{link:image}").format(link='https://...') # 支持拓展格式化控制符
Message(MessageSegment(type='image', data={'file': 'https://...'}))
:参数:
* ``format_string: str``: 格式化字符串
:返回:
- ``MessageFormatter[TM]``: 消息格式化器
"""
return MessageTemplate(format_string, cls)
@classmethod
@abc.abstractmethod
def get_segment_class(cls) -> Type[TMS]:
raise NotImplementedError
def __str__(self):
return "".join(str(seg) for seg in self)
@classmethod
def __get_validators__(cls):
yield cls._validate
@classmethod
def _validate(cls, value):
return cls(value)
@staticmethod
@abc.abstractmethod
def _construct(msg: Union[str, Mapping, Iterable[Mapping], Any]) -> Iterable[TMS]:
raise NotImplementedError
def __add__(self: TM, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:
result = self.copy()
result += other
return result
def __radd__(self: TM, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:
result = self.__class__(other) # type: ignore
return result + self
def __iadd__(self: TM, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:
if isinstance(other, MessageSegment):
self.append(other)
elif isinstance(other, Message):
self.extend(other)
else:
self.extend(self._construct(other))
return self
def append(self: TM, obj: Union[str, TMS]) -> TM:
"""
:说明:
添加一个消息段到消息数组末尾
:参数:
* ``obj: Union[str, MessageSegment]``: 要添加的消息段
"""
if isinstance(obj, MessageSegment):
super(Message, self).append(obj)
elif isinstance(obj, str):
self.extend(self._construct(obj))
else:
raise ValueError(f"Unexpected type: {type(obj)} {obj}")
return self
def extend(self: TM, obj: Union[TM, Iterable[TMS]]) -> TM:
"""
:说明:
拼接一个消息数组或多个消息段到消息数组末尾
:参数:
* ``obj: Union[Message, Iterable[MessageSegment]]``: 要添加的消息数组
"""
for segment in obj:
self.append(segment)
return self
def copy(self: TM) -> TM:
return deepcopy(self)
def extract_plain_text(self: "Message[MessageSegment]") -> str:
"""
:说明:
提取消息内纯文本消息
"""
return "".join(str(seg) for seg in self if seg.is_text())

View File

@@ -1,23 +1,18 @@
"""
配置
====
"""本模块定义了 NoneBot 本身运行所需的配置项。
NoneBot 使用 `pydantic`_ 以及 `python-dotenv`_ 来读取配置。
NoneBot 使用 [`pydantic`](https://pydantic-docs.helpmanual.io/) 以及 [`python-dotenv`](https://saurabh-kumar.com/python-dotenv/) 来读取配置。
配置项需符合特殊格式或 json 序列化格式。详情见 `pydantic Field Type`_ 文档。
配置项需符合特殊格式或 json 序列化格式。详情见 [`pydantic Field Type`](https://pydantic-docs.helpmanual.io/usage/types/) 文档。
.. _pydantic:
https://pydantic-docs.helpmanual.io/
.. _python-dotenv:
https://saurabh-kumar.com/python-dotenv/
.. _pydantic Field Type:
https://pydantic-docs.helpmanual.io/usage/types/
FrontMatter:
sidebar_position: 1
description: nonebot.config 模块
"""
import os
from pathlib import Path
from datetime import timedelta
from ipaddress import IPv4Address
from typing import Any, Set, Dict, Tuple, Union, Mapping, Optional
from typing import TYPE_CHECKING, Any, Set, Dict, Tuple, Union, Mapping, Optional
from pydantic import BaseSettings, IPvAnyAddress
from pydantic.env_settings import (
@@ -61,7 +56,7 @@ class CustomEnvSettings(EnvSettingsSource):
if env_path.is_file():
env_file_vars = read_env_file(
env_path,
encoding=env_file_encoding,
encoding=env_file_encoding, # type: ignore
case_sensitive=settings.__config__.case_sensitive,
)
env_vars = {**env_file_vars, **env_vars}
@@ -88,8 +83,7 @@ class CustomEnvSettings(EnvSettingsSource):
d[field.alias] = env_val
if env_file_vars:
for env_name, env_val in env_file_vars.items():
if (env_val is None or len(env_val) == 0) and env_name in env_vars:
for env_name in env_file_vars.keys():
env_val = env_vars[env_name]
try:
if env_val:
@@ -105,6 +99,7 @@ class CustomEnvSettings(EnvSettingsSource):
class BaseConfig(BaseSettings):
if TYPE_CHECKING:
# dummy getattr for pylance checking, actually not used
def __getattr__(self, name: str) -> Any: # pragma: no cover
return self.__dict__.get(name)
@@ -129,19 +124,15 @@ class BaseConfig(BaseSettings):
class Env(BaseConfig):
"""
运行环境配置。大小写不敏感。
"""运行环境配置。大小写不敏感。
将会从 ``nonebot.init 参数`` > ``环境变量`` > ``.env 环境配置文件`` 的优先级读取配置
将会从 `环境变量` > `.env 环境配置文件` 的优先级读取环境信息
"""
environment: str = "prod"
"""
- **类型**: ``str``
- **默认值**: ``"prod"``
"""当前环境名。
:说明:
当前环境名。 NoneBot 将从 ``.env.{environment}`` 文件中加载配置。
NoneBot 将从 `.env.{environment}` 文件中加载配置。
"""
class Config:
@@ -150,138 +141,85 @@ class Env(BaseConfig):
class Config(BaseConfig):
"""
NoneBot 主要配置。大小写不敏感。
"""NoneBot 主要配置。大小写不敏感。
除了 NoneBot 的配置项外,还可以自行添加配置项到 ``.env.{environment}`` 文件中。
这些配置将会在 json 反序列化后一起带入 ``Config`` 类中。
除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。
这些配置将会在 json 反序列化后一起带入 `Config` 类中。
配置方法参考: [配置](https://v2.nonebot.dev/docs/tutorial/configuration)
"""
_common_config: dict
_env_file: str
_env_file: str = ".env"
_common_config: Dict[str, Any] = {}
# nonebot configs
driver: str = "~fastapi"
"""
- **类型**: ``str``
- **默认值**: ``"~fastapi"``
"""NoneBot 运行所使用的 `Driver` 。继承自 {ref}`nonebot.drivers.Driver` 。
:说明:
配置格式为 `<module>[:<Driver>][+<module>[:<Mixin>]]*`。
NoneBot 运行所使用的 ``Driver`` 。继承自 ``nonebot.drivers.Driver``
配置格式为 ``<module>[:<Driver>][+<module>[:<Mixin>]]*``。
``~`` 为 ``nonebot.drivers.`` 的缩写。
`~` 为 `nonebot.drivers.` 的缩写
"""
host: IPvAnyAddress = IPv4Address("127.0.0.1") # type: ignore
"""
- **类型**: ``IPvAnyAddress``
- **默认值**: ``127.0.0.1``
:说明:
NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。
"""
"""NoneBot {ref}`nonebot.drivers.ReverseDriver` 服务端监听的 IP/主机名。"""
port: int = 8080
"""
- **类型**: ``int``
- **默认值**: ``8080``
:说明:
NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。
"""
"""NoneBot {ref}`nonebot.drivers.ReverseDriver` 服务端监听的端口。"""
log_level: Union[int, str] = "INFO"
"""
- **类型**: ``Union[int, str]``
- **默认值**: ``INFO``
"""NoneBot 日志输出等级,可以为 `int` 类型等级或等级名称
:说明:
参考 [`loguru 日志等级`](https://loguru.readthedocs.io/en/stable/api/logger.html#levels)。
配置 NoneBot 日志输出等级,可以为 ``int`` 类型等级或等级名称,参考 `loguru 日志等级`_。
:示例:
.. code-block:: default
:::tip 提示
日志等级名称应为大写,如 `INFO`。
:::
用法:
```conf
LOG_LEVEL=25
LOG_LEVEL=INFO
.. _loguru 日志等级:
https://loguru.readthedocs.io/en/stable/api/logger.html#levels
```
"""
# bot connection configs
api_timeout: Optional[float] = 30.0
"""
- **类型**: ``Optional[float]``
- **默认值**: ``30.``
:说明:
API 请求超时时间,单位: 秒。
"""
"""API 请求超时时间,单位: 秒。"""
# bot runtime configs
superusers: Set[str] = set()
"""
- **类型**: ``Set[str]``
- **默认值**: ``set()``
:说明:
机器人超级用户。
:示例:
.. code-block:: default
"""机器人超级用户。
用法:
```conf
SUPERUSERS=["12345789"]
```
"""
nickname: Set[str] = set()
"""
- **类型**: ``Set[str]``
- **默认值**: ``set()``
:说明:
机器人昵称。
"""
"""机器人昵称。"""
command_start: Set[str] = {"/"}
"""
- **类型**: ``Set[str]``
- **默认值**: ``{"/"}``
"""命令的起始标记,用于判断一条消息是不是命令。
:说明:
命令的起始标记,用于判断一条消息是不是命令。
用法:
```conf
COMMAND_START=["/", ""]
```
"""
command_sep: Set[str] = {"."}
"""
- **类型**: ``Set[str]``
- **默认值**: ``{"."}``
"""命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
:说明:
命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
用法:
```conf
COMMAND_SEP=["."]
```
"""
session_expire_timeout: timedelta = timedelta(minutes=2)
"""
- **类型**: ``timedelta``
- **默认值**: ``timedelta(minutes=2)``
:说明:
等待用户回复的超时时间。
:示例:
.. code-block:: default
"""等待用户回复的超时时间。
用法:
```conf
SESSION_EXPIRE_TIMEOUT=120 # 单位: 秒
SESSION_EXPIRE_TIMEOUT=[DD ][HH:MM]SS[.ffffff]
SESSION_EXPIRE_TIMEOUT=P[DD]DT[HH]H[MM]M[SS]S # ISO 8601
```
"""
# adapter configs
@@ -294,3 +232,9 @@ class Config(BaseConfig):
class Config:
extra = "allow"
env_file = ".env.prod"
__autodoc__ = {
"CustomEnvSettings": False,
"BaseConfig": False,
}

View File

@@ -1,20 +1,44 @@
"""本模块包含了 NoneBot 事件处理过程中使用到的常量。
FrontMatter:
sidebar_position: 9
description: nonebot.consts 模块
"""
from typing_extensions import Literal
# used by Matcher
RECEIVE_KEY = "_receive_{id}"
LAST_RECEIVE_KEY = "_last_receive"
ARG_KEY = "{key}"
REJECT_TARGET = "_current_target"
REJECT_CACHE_TARGET = "_next_target"
RECEIVE_KEY: Literal["_receive_{id}"] = "_receive_{id}"
"""`receive` 存储 key"""
LAST_RECEIVE_KEY: Literal["_last_receive"] = "_last_receive"
"""`last_receive` 存储 key"""
ARG_KEY: Literal["{key}"] = "{key}"
"""`arg` 存储 key"""
REJECT_TARGET: Literal["_current_target"] = "_current_target"
"""当前 `reject` 目标存储 key"""
REJECT_CACHE_TARGET: Literal["_next_target"] = "_next_target"
"""下一个 `reject` 目标存储 key"""
# used by Rule
PREFIX_KEY = "_prefix"
PREFIX_KEY: Literal["_prefix"] = "_prefix"
"""命令前缀存储 key"""
CMD_KEY = "command"
RAW_CMD_KEY = "raw_command"
CMD_ARG_KEY = "command_arg"
CMD_KEY: Literal["command"] = "command"
"""命令元组存储 key"""
RAW_CMD_KEY: Literal["raw_command"] = "raw_command"
"""命令文本存储 key"""
CMD_ARG_KEY: Literal["command_arg"] = "command_arg"
"""命令参数存储 key"""
CMD_START_KEY: Literal["command_start"] = "command_start"
"""命令开头存储 key"""
SHELL_ARGS = "_args"
SHELL_ARGV = "_argv"
SHELL_ARGS: Literal["_args"] = "_args"
"""shell 命令 parse 后参数字典存储 key"""
SHELL_ARGV: Literal["_argv"] = "_argv"
"""shell 命令原始参数列表存储 key"""
REGEX_MATCHED = "_matched"
REGEX_GROUP = "_matched_groups"
REGEX_DICT = "_matched_dict"
REGEX_MATCHED: Literal["_matched"] = "_matched"
"""正则匹配结果存储 key"""
REGEX_GROUP: Literal["_matched_groups"] = "_matched_groups"
"""正则匹配 group 元组存储 key"""
REGEX_DICT: Literal["_matched_dict"] = "_matched_dict"
"""正则匹配 group 字典存储 key"""

View File

@@ -1,8 +1,8 @@
"""
依赖注入处理模块
================
"""本模块模块实现了依赖注入的定义与处理。
该模块实现了依赖注入的定义与处理。
FrontMatter:
sidebar_position: 0
description: nonebot.dependencies 模块
"""
import abc
@@ -14,15 +14,21 @@ from pydantic.schema import get_annotation_from_field_info
from pydantic.fields import Required, FieldInfo, Undefined, ModelField
from nonebot.log import logger
from .utils import get_typed_signature
from nonebot.exception import TypeMisMatch
from nonebot.utils import run_sync, is_coroutine_callable
T = TypeVar("T", bound="Dependent")
from .utils import check_field_type, get_typed_signature
R = TypeVar("R")
T = TypeVar("T", bound="Dependent")
class Param(abc.ABC, FieldInfo):
"""依赖注入的基本单元 —— 参数。
继承自 `pydantic.fields.FieldInfo`,用于描述参数信息(不包括参数名)。
"""
@classmethod
def _check_param(
cls, dependent: "Dependent", name: str, param: inspect.Parameter
@@ -45,6 +51,16 @@ class CustomConfig(BaseConfig):
class Dependent(Generic[R]):
"""依赖注入容器
参数:
call: 依赖注入的可调用对象,可以是任何 Callable 对象
pre_checkers: 依赖注入解析前的参数检查
params: 具名参数列表
parameterless: 匿名参数列表
allow_types: 允许的参数类型
"""
def __init__(
self,
*,
@@ -178,17 +194,20 @@ class Dependent(Generic[R]):
field_info = field.field_info
assert isinstance(field_info, Param), "Params must be subclasses of Param"
value = await field_info._solve(**params)
if value == Undefined:
if value is Undefined:
value = field.get_default()
_, errs_ = field.validate(value, values, loc=(str(field_info), field.alias))
if errs_:
try:
values[field.name] = check_field_type(field, value)
except TypeMisMatch:
logger.debug(
f"{field_info} "
f"type {type(value)} not match depends {self.call} "
f"annotation {field._type_display()}, ignored"
)
raise TypeMisMatch(field, value)
else:
values[field.name] = value
raise
return values
__autodoc__ = {"CustomConfig": False}

View File

@@ -1,11 +1,22 @@
"""
FrontMatter:
sidebar_position: 1
description: nonebot.dependencies.utils 模块
"""
import inspect
from typing import Any, Dict, Callable
from typing import Any, Dict, TypeVar, Callable
from loguru import logger
from pydantic.fields import ModelField
from pydantic.typing import ForwardRef, evaluate_forwardref
from nonebot.exception import TypeMisMatch
V = TypeVar("V")
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
"""获取可调用对象签名"""
signature = inspect.signature(call)
globalns = getattr(call, "__globals__", {})
typed_params = [
@@ -22,6 +33,7 @@ def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any:
"""获取参数的类型注解"""
annotation = param.annotation
if isinstance(annotation, str):
annotation = ForwardRef(annotation)
@@ -33,3 +45,10 @@ def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) ->
)
return inspect.Parameter.empty
return annotation
def check_field_type(field: ModelField, value: V) -> V:
_, errs_ = field.validate(value, {}, loc=())
if errs_:
raise TypeMisMatch(field, value)
return value

View File

@@ -1,297 +1,38 @@
"""
后端驱动适配基类
=================
"""本模块定义了驱动适配器基类。
各驱动请继承以下基类
各驱动请继承以下基类
FrontMatter:
sidebar_position: 0
description: nonebot.drivers 模块
"""
import abc
import asyncio
from dataclasses import dataclass
from contextlib import asynccontextmanager
from typing import (
TYPE_CHECKING,
Any,
Set,
Dict,
Type,
Callable,
Awaitable,
AsyncGenerator,
)
from nonebot.internal.driver import URL as URL
from nonebot.internal.driver import Driver as Driver
from nonebot.internal.driver import Cookies as Cookies
from nonebot.internal.driver import Request as Request
from nonebot.internal.driver import Response as Response
from nonebot.internal.driver import WebSocket as WebSocket
from nonebot.internal.driver import HTTPVersion as HTTPVersion
from nonebot.internal.driver import ForwardMixin as ForwardMixin
from nonebot.internal.driver import ForwardDriver as ForwardDriver
from nonebot.internal.driver import ReverseDriver as ReverseDriver
from nonebot.internal.driver import combine_driver as combine_driver
from nonebot.internal.driver import HTTPServerSetup as HTTPServerSetup
from nonebot.internal.driver import WebSocketServerSetup as WebSocketServerSetup
from ._model import URL as URL
from nonebot.log import logger
from nonebot.utils import escape_tag
from ._model import Request as Request
from nonebot.config import Env, Config
from ._model import Response as Response
from ._model import WebSocket as WebSocket
from ._model import HTTPVersion as HTTPVersion
from nonebot.typing import T_BotConnectionHook, T_BotDisconnectionHook
if TYPE_CHECKING:
from nonebot.adapters import Bot, Adapter
class Driver(abc.ABC):
"""
Driver 基类。
"""
_adapters: Dict[str, "Adapter"] = {}
"""
:类型: ``Dict[str, Adapter]``
:说明: 已注册的适配器列表
"""
_bot_connection_hook: Set[T_BotConnectionHook] = set()
"""
:类型: ``Set[T_BotConnectionHook]``
:说明: Bot 连接建立时执行的函数
"""
_bot_disconnection_hook: Set[T_BotDisconnectionHook] = set()
"""
:类型: ``Set[T_BotDisconnectionHook]``
:说明: Bot 连接断开时执行的函数
"""
def __init__(self, env: Env, config: Config):
"""
:参数:
* ``env: Env``: 包含环境信息的 Env 对象
* ``config: Config``: 包含配置信息的 Config 对象
"""
self.env: str = env.environment
"""
:类型: ``str``
:说明: 环境名称
"""
self.config: Config = config
"""
:类型: ``Config``
:说明: 配置对象
"""
self._clients: Dict[str, "Bot"] = {}
"""
:类型: ``Dict[str, Bot]``
:说明: 已连接的 Bot
"""
@property
def bots(self) -> Dict[str, "Bot"]:
"""
:类型:
``Dict[str, Bot]``
:说明:
获取当前所有已连接的 Bot
"""
return self._clients
def register_adapter(self, adapter: Type["Adapter"], **kwargs) -> None:
"""
:说明:
注册一个协议适配器
:参数:
* ``name: str``: 适配器名称,用于在连接时进行识别
* ``adapter: Type[Bot]``: 适配器 Class
* ``**kwargs``: 其他传递给适配器的参数
"""
name = adapter.get_name()
if name in self._adapters:
logger.opt(colors=True).debug(
f'Adapter "<y>{escape_tag(name)}</y>" already exists'
)
return
self._adapters[name] = adapter(self, **kwargs)
logger.opt(colors=True).debug(
f'Succeeded to load adapter "<y>{escape_tag(name)}</y>"'
)
@property
@abc.abstractmethod
def type(self) -> str:
"""驱动类型名称"""
raise NotImplementedError
@property
@abc.abstractmethod
def logger(self):
"""驱动专属 logger 日志记录器"""
raise NotImplementedError
@abc.abstractmethod
def run(self, *args, **kwargs):
"""
:说明:
启动驱动框架
:参数:
* ``*args``
* ``**kwargs``
"""
logger.opt(colors=True).debug(
f"<g>Loaded adapters: {escape_tag(', '.join(self._adapters))}</g>"
)
@abc.abstractmethod
def on_startup(self, func: Callable) -> Callable:
"""注册一个在驱动启动时运行的函数"""
raise NotImplementedError
@abc.abstractmethod
def on_shutdown(self, func: Callable) -> Callable:
"""注册一个在驱动停止时运行的函数"""
raise NotImplementedError
def on_bot_connect(self, func: T_BotConnectionHook) -> T_BotConnectionHook:
"""
:说明:
装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行。
:函数参数:
* ``bot: Bot``: 当前连接上的 Bot 对象
"""
self._bot_connection_hook.add(func)
return func
def on_bot_disconnect(self, func: T_BotDisconnectionHook) -> T_BotDisconnectionHook:
"""
:说明:
装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行。
:函数参数:
* ``bot: Bot``: 当前连接上的 Bot 对象
"""
self._bot_disconnection_hook.add(func)
return func
def _bot_connect(self, bot: "Bot") -> None:
"""在 WebSocket 连接成功后,调用该函数来注册 bot 对象"""
if bot.self_id in self._clients:
raise RuntimeError(f"Duplicate bot connection with id {bot.self_id}")
self._clients[bot.self_id] = bot
async def _run_hook(bot: "Bot") -> None:
coros = list(map(lambda x: x(bot), self._bot_connection_hook))
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running WebSocketConnection hook. "
"Running cancelled!</bg #f8bbd0></r>"
)
asyncio.create_task(_run_hook(bot))
def _bot_disconnect(self, bot: "Bot") -> None:
"""在 WebSocket 连接断开后,调用该函数来注销 bot 对象"""
if bot.self_id in self._clients:
del self._clients[bot.self_id]
async def _run_hook(bot: "Bot") -> None:
coros = list(map(lambda x: x(bot), self._bot_disconnection_hook))
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running WebSocketDisConnection hook. "
"Running cancelled!</bg #f8bbd0></r>"
)
asyncio.create_task(_run_hook(bot))
class ForwardMixin(abc.ABC):
@property
@abc.abstractmethod
def type(self) -> str:
raise NotImplementedError
@abc.abstractmethod
async def request(self, setup: Request) -> Response:
raise NotImplementedError
@abc.abstractmethod
@asynccontextmanager
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
raise NotImplementedError
yield # used for static type checking's generator detection
class ForwardDriver(Driver, ForwardMixin):
"""
Forward Driver 基类。将客户端框架封装,以满足适配器使用。
"""
class ReverseDriver(Driver):
"""
Reverse Driver 基类。将后端框架封装,以满足适配器使用。
"""
@property
@abc.abstractmethod
def server_app(self) -> Any:
"""驱动 APP 对象"""
raise NotImplementedError
@property
@abc.abstractmethod
def asgi(self) -> Any:
"""驱动 ASGI 对象"""
raise NotImplementedError
@abc.abstractmethod
def setup_http_server(self, setup: "HTTPServerSetup") -> None:
raise NotImplementedError
@abc.abstractmethod
def setup_websocket_server(self, setup: "WebSocketServerSetup") -> None:
raise NotImplementedError
def combine_driver(driver: Type[Driver], *mixins: Type[ForwardMixin]) -> Type[Driver]:
# check first
assert issubclass(driver, Driver), "`driver` must be subclass of Driver"
assert all(
map(lambda m: issubclass(m, ForwardMixin), mixins)
), "`mixins` must be subclass of ForwardMixin"
class CombinedDriver(*mixins, driver, ForwardDriver): # type: ignore
@property
def type(self) -> str:
return (
driver.type.__get__(self)
+ "+"
+ "+".join(map(lambda x: x.type.__get__(self), mixins))
)
return CombinedDriver
@dataclass
class HTTPServerSetup:
path: URL # path should not be absolute, check it by URL.is_absolute() == False
method: str
name: str
handle_func: Callable[[Request], Awaitable[Response]]
@dataclass
class WebSocketServerSetup:
path: URL # path should not be absolute, check it by URL.is_absolute() == False
name: str
handle_func: Callable[[WebSocket], Awaitable[Any]]
__autodoc__ = {
"URL": True,
"Driver": True,
"Cookies": True,
"Request": True,
"Response": True,
"WebSocket": True,
"HTTPVersion": True,
"ForwardMixin": True,
"ForwardDriver": True,
"ReverseDriver": True,
"combine_driver": True,
"HTTPServerSetup": True,
"WebSocketServerSetup": True,
}

View File

@@ -27,7 +27,7 @@ class BlockDriver(Driver):
@property
@overrides(Driver)
def type(self) -> str:
"""驱动名称: ``block_driver``"""
"""驱动名称: `block_driver`"""
return "block_driver"
@property
@@ -39,13 +39,7 @@ class BlockDriver(Driver):
@overrides(Driver)
def on_startup(self, func: STARTUP_FUNC) -> STARTUP_FUNC:
"""
:说明:
注册一个启动时执行的函数
:参数:
* ``func: Callable[[], Awaitable[None]]``
"""
self.startup_funcs.add(func)
return func
@@ -53,13 +47,7 @@ class BlockDriver(Driver):
@overrides(Driver)
def on_shutdown(self, func: SHUTDOWN_FUNC) -> SHUTDOWN_FUNC:
"""
:说明:
注册一个停止时执行的函数
:参数:
* ``func: Callable[[], Awaitable[None]]``
"""
self.shutdown_funcs.add(func)
return func

View File

@@ -1,11 +1,21 @@
"""
AIOHTTP 驱动适配
================
"""[AIOHTTP](https://aiohttp.readthedocs.io/en/stable/) 驱动适配器。
```bash
nb driver install aiohttp
# 或者
pip install nonebot2[aiohttp]
```
:::tip 提示
本驱动仅支持客户端连接
:::
FrontMatter:
sidebar_position: 2
description: nonebot.drivers.aiohttp 模块
"""
from typing import AsyncGenerator
from typing import Type, AsyncGenerator
from contextlib import asynccontextmanager
from nonebot.typing import overrides
@@ -13,7 +23,7 @@ from nonebot.drivers import Request, Response
from nonebot.exception import WebSocketClosed
from nonebot.drivers._block_driver import BlockDriver
from nonebot.drivers import WebSocket as BaseWebSocket
from nonebot.drivers import HTTPVersion, ForwardMixin, combine_driver
from nonebot.drivers import HTTPVersion, ForwardMixin, ForwardDriver, combine_driver
try:
import aiohttp
@@ -24,6 +34,8 @@ except ImportError:
class Mixin(ForwardMixin):
"""AIOHTTP Mixin"""
@property
@overrides(ForwardMixin)
def type(self) -> str:
@@ -85,6 +97,8 @@ class Mixin(ForwardMixin):
class WebSocket(BaseWebSocket):
"""AIOHTTP Websocket Wrapper"""
def __init__(
self,
*,
@@ -118,20 +132,33 @@ class WebSocket(BaseWebSocket):
@overrides(BaseWebSocket)
async def receive(self) -> str:
msg = await self._receive()
if msg.type not in (aiohttp.WSMsgType.TEXT, aiohttp.WSMsgType.BINARY):
raise TypeError(
f"WebSocket received unexpected frame type: {msg.type}, {msg.data!r}"
)
return msg.data
@overrides(BaseWebSocket)
async def receive_text(self) -> str:
msg = await self._receive()
if msg.type != aiohttp.WSMsgType.TEXT:
raise TypeError(f"WebSocket received unexpected frame type: {msg.type}")
raise TypeError(
f"WebSocket received unexpected frame type: {msg.type}, {msg.data!r}"
)
return msg.data
@overrides(BaseWebSocket)
async def receive_bytes(self) -> bytes:
msg = await self._receive()
if msg.type != aiohttp.WSMsgType.TEXT:
raise TypeError(f"WebSocket received unexpected frame type: {msg.type}")
if msg.type != aiohttp.WSMsgType.BINARY:
raise TypeError(
f"WebSocket received unexpected frame type: {msg.type}, {msg.data!r}"
)
return msg.data
@overrides(BaseWebSocket)
async def send(self, data: str) -> None:
async def send_text(self, data: str) -> None:
await self.websocket.send_str(data)
@overrides(BaseWebSocket)
@@ -139,4 +166,5 @@ class WebSocket(BaseWebSocket):
await self.websocket.send_bytes(data)
Driver = combine_driver(BlockDriver, Mixin)
Driver: Type[ForwardDriver] = combine_driver(BlockDriver, Mixin) # type: ignore
"""AIOHTTP Driver"""

View File

@@ -1,18 +1,17 @@
"""
FastAPI 驱动适配
================
"""[FastAPI](https://fastapi.tiangolo.com/) 驱动适配
本驱动同时支持服务端以及客户端连接
:::tip 提示
本驱动仅支持服务端连接
:::
后端使用方法请参考: `FastAPI 文档`_
.. _FastAPI 文档:
https://fastapi.tiangolo.com/
FrontMatter:
sidebar_position: 1
description: nonebot.drivers.fastapi 模块
"""
import logging
from functools import wraps
from typing import Any, List, Tuple, Callable, Optional
from typing import Any, List, Tuple, Union, Callable, Optional
import uvicorn
from pydantic import BaseSettings
@@ -20,10 +19,10 @@ from fastapi.responses import Response
from fastapi import FastAPI, Request, UploadFile, status
from starlette.websockets import WebSocket, WebSocketState, WebSocketDisconnect
from ._model import FileTypes
from nonebot.config import Env
from nonebot.typing import overrides
from nonebot.exception import WebSocketClosed
from nonebot.internal.driver import FileTypes
from nonebot.config import Config as NoneBotConfig
from nonebot.drivers import Request as BaseRequest
from nonebot.drivers import WebSocket as BaseWebSocket
@@ -37,102 +36,40 @@ def catch_closed(func):
return await func(*args, **kwargs)
except WebSocketDisconnect as e:
raise WebSocketClosed(e.code)
except KeyError:
raise TypeError("WebSocket received unexpected frame type")
return decorator
class Config(BaseSettings):
"""
FastAPI 驱动框架设置,详情参考 FastAPI 文档
"""
"""FastAPI 驱动框架设置,详情参考 FastAPI 文档"""
fastapi_openapi_url: Optional[str] = None
"""
:类型:
``Optional[str]``
:说明:
``openapi.json`` 地址,默认为 ``None`` 即关闭
"""
"""`openapi.json` 地址,默认为 `None` 即关闭"""
fastapi_docs_url: Optional[str] = None
"""
:类型:
``Optional[str]``
:说明:
``swagger`` 地址,默认为 ``None`` 即关闭
"""
"""`swagger` 地址,默认为 `None` 即关闭"""
fastapi_redoc_url: Optional[str] = None
"""
:类型:
``Optional[str]``
:说明:
``redoc`` 地址,默认为 ``None`` 即关闭
"""
"""`redoc` 地址,默认为 `None` 即关闭"""
fastapi_include_adapter_schema: bool = True
"""是否包含适配器路由的 schema默认为 `True`"""
fastapi_reload: bool = False
"""
:类型:
``bool``
:说明:
开启/关闭冷重载
"""
"""开启/关闭冷重载"""
fastapi_reload_dirs: Optional[List[str]] = None
"""
:类型:
``Optional[List[str]]``
:说明:
重载监控文件夹列表,默认为 uvicorn 默认值
"""
"""重载监控文件夹列表,默认为 uvicorn 默认值"""
fastapi_reload_delay: Optional[float] = None
"""
:类型:
``Optional[float]``
:说明:
重载延迟,默认为 uvicorn 默认值
"""
"""重载延迟,默认为 uvicorn 默认值"""
fastapi_reload_includes: Optional[List[str]] = None
"""
:类型:
``Optional[List[str]]``
:说明:
要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
"""
"""要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值"""
fastapi_reload_excludes: Optional[List[str]] = None
"""
:类型:
``Optional[List[str]]``
:说明:
不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
"""
"""不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值"""
class Config:
extra = "ignore"
class Driver(ReverseDriver):
"""FastAPI 驱动框架。包含反向 Server 功能。"""
"""FastAPI 驱动框架。"""
def __init__(self, env: Env, config: NoneBotConfig):
super(Driver, self).__init__(env, config)
@@ -148,19 +85,19 @@ class Driver(ReverseDriver):
@property
@overrides(ReverseDriver)
def type(self) -> str:
"""驱动名称: ``fastapi``"""
"""驱动名称: `fastapi`"""
return "fastapi"
@property
@overrides(ReverseDriver)
def server_app(self) -> FastAPI:
"""``FastAPI APP`` 对象"""
"""`FastAPI APP` 对象"""
return self._server_app
@property
@overrides(ReverseDriver)
def asgi(self) -> FastAPI:
"""``FastAPI APP`` 对象"""
"""`FastAPI APP` 对象"""
return self._server_app
@property
@@ -179,6 +116,7 @@ class Driver(ReverseDriver):
_handle,
name=setup.name,
methods=[setup.method],
include_in_schema=self.fastapi_config.fastapi_include_adapter_schema,
)
@overrides(ReverseDriver)
@@ -199,7 +137,7 @@ class Driver(ReverseDriver):
@overrides(ReverseDriver)
def on_shutdown(self, func: Callable) -> Callable:
"""参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#startup-event>`_"""
"""参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#shutdown-event>`_"""
return self.server_app.on_event("shutdown")(func)
@overrides(ReverseDriver)
@@ -211,7 +149,7 @@ class Driver(ReverseDriver):
app: Optional[str] = None,
**kwargs,
):
"""使用 ``uvicorn`` 启动 FastAPI"""
"""使用 `uvicorn` 启动 FastAPI"""
super().run(host, port, app, **kwargs)
LOGGING_CONFIG = {
"version": 1,
@@ -300,6 +238,8 @@ class Driver(ReverseDriver):
class FastAPIWebSocket(BaseWebSocket):
"""FastAPI WebSocket Wrapper"""
@overrides(BaseWebSocket)
def __init__(self, *, request: BaseRequest, websocket: WebSocket):
super().__init__(request=request)
@@ -323,9 +263,17 @@ class FastAPIWebSocket(BaseWebSocket):
) -> None:
await self.websocket.close(code)
@overrides(BaseWebSocket)
async def receive(self) -> Union[str, bytes]:
# assert self.websocket.application_state == WebSocketState.CONNECTED
msg = await self.websocket.receive()
if msg["type"] == "websocket.disconnect":
raise WebSocketClosed(msg["code"])
return msg["text"] if "text" in msg else msg["bytes"]
@overrides(BaseWebSocket)
@catch_closed
async def receive(self) -> str:
async def receive_text(self) -> str:
return await self.websocket.receive_text()
@overrides(BaseWebSocket)
@@ -334,9 +282,12 @@ class FastAPIWebSocket(BaseWebSocket):
return await self.websocket.receive_bytes()
@overrides(BaseWebSocket)
async def send(self, data: str) -> None:
async def send_text(self, data: str) -> None:
await self.websocket.send({"type": "websocket.send", "text": data})
@overrides(BaseWebSocket)
async def send_bytes(self, data: bytes) -> None:
await self.websocket.send({"type": "websocket.send", "bytes": data})
__autodoc__ = {"catch_closed": False}

View File

@@ -1,4 +1,20 @@
from typing import AsyncGenerator
"""[HTTPX](https://www.python-httpx.org/) 驱动适配
```bash
nb driver install httpx
# 或者
pip install nonebot2[httpx]
```
:::tip 提示
本驱动仅支持客户端 HTTP 连接
:::
FrontMatter:
sidebar_position: 3
description: nonebot.drivers.httpx 模块
"""
from typing import Type, AsyncGenerator
from contextlib import asynccontextmanager
from nonebot.typing import overrides
@@ -9,6 +25,7 @@ from nonebot.drivers import (
WebSocket,
HTTPVersion,
ForwardMixin,
ForwardDriver,
combine_driver,
)
@@ -21,6 +38,8 @@ except ImportError:
class Mixin(ForwardMixin):
"""HTTPX Mixin"""
@property
@overrides(ForwardMixin)
def type(self) -> str:
@@ -30,22 +49,22 @@ class Mixin(ForwardMixin):
async def request(self, setup: Request) -> Response:
async with httpx.AsyncClient(
http2=setup.version == HTTPVersion.H2,
proxies=setup.proxy,
proxies=setup.proxy, # type: ignore
follow_redirects=True,
) as client:
response = await client.request(
setup.method,
str(setup.url),
content=setup.content,
data=setup.data,
content=setup.content, # type: ignore
data=setup.data, # type: ignore
json=setup.json,
files=setup.files,
files=setup.files, # type: ignore
headers=tuple(setup.headers.items()),
timeout=setup.timeout,
)
return Response(
response.status_code,
headers=response.headers,
headers=response.headers.multi_items(),
content=response.content,
request=setup,
)
@@ -57,4 +76,5 @@ class Mixin(ForwardMixin):
yield ws
Driver = combine_driver(BlockDriver, Mixin)
Driver: Type[ForwardDriver] = combine_driver(BlockDriver, Mixin) # type: ignore
"""HTTPX Driver"""

View File

@@ -1,24 +1,31 @@
"""
Quart 驱动适配
================
"""[Quart](https://pgjones.gitlab.io/quart/index.html) 驱动适配
后端使用方法请参考: `Quart 文档`_
```bash
nb driver install quart
# 或者
pip install nonebot2[quart]
```
.. _Quart 文档:
https://pgjones.gitlab.io/quart/index.html
:::tip 提示
本驱动仅支持服务端连接
:::
FrontMatter:
sidebar_position: 5
description: nonebot.drivers.quart 模块
"""
import asyncio
from functools import wraps
from typing import List, Tuple, TypeVar, Callable, Optional, Coroutine
from typing import List, Tuple, Union, TypeVar, Callable, Optional, Coroutine
import uvicorn
from pydantic import BaseSettings
from ._model import FileTypes
from nonebot.config import Env
from nonebot.typing import overrides
from nonebot.exception import WebSocketClosed
from nonebot.internal.driver import FileTypes
from nonebot.config import Config as NoneBotConfig
from nonebot.drivers import Request as BaseRequest
from nonebot.drivers import WebSocket as BaseWebSocket
@@ -31,7 +38,7 @@ try:
from quart.datastructures import FileStorage
from quart import Websocket as QuartWebSocket
except ImportError:
raise ValueError(
raise ImportError(
"Please install Quart by using `pip install nonebot2[quart]`"
) from None
@@ -50,69 +57,25 @@ def catch_closed(func):
class Config(BaseSettings):
"""
Quart 驱动框架设置
"""
"""Quart 驱动框架设置"""
quart_reload: bool = False
"""
:类型:
``bool``
:说明:
开启/关闭冷重载
"""
"""开启/关闭冷重载"""
quart_reload_dirs: Optional[List[str]] = None
"""
:类型:
``Optional[List[str]]``
:说明:
重载监控文件夹列表,默认为 uvicorn 默认值
"""
"""重载监控文件夹列表,默认为 uvicorn 默认值"""
quart_reload_delay: Optional[float] = None
"""
:类型:
``Optional[float]``
:说明:
重载延迟,默认为 uvicorn 默认值
"""
"""重载延迟,默认为 uvicorn 默认值"""
quart_reload_includes: Optional[List[str]] = None
"""
:类型:
``Optional[List[str]]``
:说明:
要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
"""
"""要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值"""
quart_reload_excludes: Optional[List[str]] = None
"""
:类型:
``Optional[List[str]]``
:说明:
不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
"""
"""不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值"""
class Config:
extra = "ignore"
class Driver(ReverseDriver):
"""
Quart 驱动框架
"""
"""Quart 驱动框架"""
def __init__(self, env: Env, config: NoneBotConfig):
super().__init__(env, config)
@@ -124,19 +87,19 @@ class Driver(ReverseDriver):
@property
@overrides(ReverseDriver)
def type(self) -> str:
"""驱动名称: ``quart``"""
"""驱动名称: `quart`"""
return "quart"
@property
@overrides(ReverseDriver)
def server_app(self) -> Quart:
"""``Quart`` 对象"""
"""`Quart` 对象"""
return self._server_app
@property
@overrides(ReverseDriver)
def asgi(self):
"""``Quart`` 对象"""
"""`Quart` 对象"""
return self._server_app
@property
@@ -170,16 +133,12 @@ class Driver(ReverseDriver):
@overrides(ReverseDriver)
def on_startup(self, func: _AsyncCallable) -> _AsyncCallable:
"""参考文档: `Startup and Shutdown`_
.. _Startup and Shutdown:
https://pgjones.gitlab.io/quart/how_to_guides/startup_shutdown.html
"""
"""参考文档: [`Startup and Shutdown`](https://pgjones.gitlab.io/quart/how_to_guides/startup_shutdown.html)"""
return self.server_app.before_serving(func) # type: ignore
@overrides(ReverseDriver)
def on_shutdown(self, func: _AsyncCallable) -> _AsyncCallable:
"""参考文档: `Startup and Shutdown`_"""
"""参考文档: [`Startup and Shutdown`](https://pgjones.gitlab.io/quart/how_to_guides/startup_shutdown.html)"""
return self.server_app.after_serving(func) # type: ignore
@overrides(ReverseDriver)
@@ -191,7 +150,7 @@ class Driver(ReverseDriver):
app: Optional[str] = None,
**kwargs,
):
"""使用 ``uvicorn`` 启动 Quart"""
"""使用 `uvicorn` 启动 Quart"""
super().run(host, port, app, **kwargs)
LOGGING_CONFIG = {
"version": 1,
@@ -240,7 +199,7 @@ class Driver(ReverseDriver):
http_request = BaseRequest(
request.method,
request.url,
headers=request.headers.items(),
headers=list(request.headers.items()),
cookies=list(request.cookies.items()),
content=await request.get_data(
cache=False, as_text=False, parse_form_data=False
@@ -265,7 +224,7 @@ class Driver(ReverseDriver):
http_request = BaseRequest(
websocket.method,
websocket.url,
headers=websocket.headers.items(),
headers=list(websocket.headers.items()),
cookies=list(websocket.cookies.items()),
version=websocket.http_version,
)
@@ -276,6 +235,8 @@ class Driver(ReverseDriver):
class WebSocket(BaseWebSocket):
"""Quart WebSocket Wrapper"""
def __init__(self, *, request: BaseRequest, websocket: QuartWebSocket):
super().__init__(request=request)
self.websocket = websocket
@@ -296,7 +257,12 @@ class WebSocket(BaseWebSocket):
@overrides(BaseWebSocket)
@catch_closed
async def receive(self) -> str:
async def receive(self) -> Union[str, bytes]:
return await self.websocket.receive()
@overrides(BaseWebSocket)
@catch_closed
async def receive_text(self) -> str:
msg = await self.websocket.receive()
if isinstance(msg, bytes):
raise TypeError("WebSocket received unexpected frame type: bytes")
@@ -311,9 +277,12 @@ class WebSocket(BaseWebSocket):
return msg
@overrides(BaseWebSocket)
async def send(self, data: str):
async def send_text(self, data: str):
await self.websocket.send(data)
@overrides(BaseWebSocket)
async def send_bytes(self, data: bytes):
await self.websocket.send(data)
__autodoc__ = {"catch_closed": False}

View File

@@ -1,7 +1,23 @@
"""[websockets](https://websockets.readthedocs.io/) 驱动适配
```bash
nb driver install websockets
# 或者
pip install nonebot2[websockets]
```
:::tip 提示
本驱动仅支持客户端 WebSocket 连接
:::
FrontMatter:
sidebar_position: 4
description: nonebot.drivers.websockets 模块
"""
import logging
from functools import wraps
from typing import AsyncGenerator
from contextlib import asynccontextmanager
from typing import Type, Union, AsyncGenerator
from nonebot.typing import overrides
from nonebot.log import LoguruHandler
@@ -9,7 +25,7 @@ from nonebot.drivers import Request, Response
from nonebot.exception import WebSocketClosed
from nonebot.drivers._block_driver import BlockDriver
from nonebot.drivers import WebSocket as BaseWebSocket
from nonebot.drivers import ForwardMixin, combine_driver
from nonebot.drivers import ForwardMixin, ForwardDriver, combine_driver
try:
from websockets.exceptions import ConnectionClosed
@@ -30,14 +46,16 @@ def catch_closed(func):
return await func(*args, **kwargs)
except ConnectionClosed as e:
if e.rcvd_then_sent:
raise WebSocketClosed(e.rcvd.code, e.rcvd.reason)
raise WebSocketClosed(e.rcvd.code, e.rcvd.reason) # type: ignore
else:
raise WebSocketClosed(e.sent.code, e.sent.reason)
raise WebSocketClosed(e.sent.code, e.sent.reason) # type: ignore
return decorator
class Mixin(ForwardMixin):
"""Websockets Mixin"""
@property
@overrides(ForwardMixin)
def type(self) -> str:
@@ -60,6 +78,8 @@ class Mixin(ForwardMixin):
class WebSocket(BaseWebSocket):
"""Websockets WebSocket Wrapper"""
@overrides(BaseWebSocket)
def __init__(self, *, request: Request, websocket: WebSocketClientProtocol):
super().__init__(request=request)
@@ -80,7 +100,13 @@ class WebSocket(BaseWebSocket):
@overrides(BaseWebSocket)
@catch_closed
async def receive(self) -> str:
async def receive(self) -> Union[str, bytes]:
msg = await self.websocket.recv()
return msg
@overrides(BaseWebSocket)
@catch_closed
async def receive_text(self) -> str:
msg = await self.websocket.recv()
if isinstance(msg, bytes):
raise TypeError("WebSocket received unexpected frame type: bytes")
@@ -95,7 +121,7 @@ class WebSocket(BaseWebSocket):
return msg
@overrides(BaseWebSocket)
async def send(self, data: str) -> None:
async def send_text(self, data: str) -> None:
await self.websocket.send(data)
@overrides(BaseWebSocket)
@@ -103,4 +129,5 @@ class WebSocket(BaseWebSocket):
await self.websocket.send(data)
Driver = combine_driver(BlockDriver, Mixin)
Driver: Type[ForwardDriver] = combine_driver(BlockDriver, Mixin) # type: ignore
"""Websockets Driver"""

View File

@@ -1,9 +1,32 @@
"""
异常
====
"""本模块包含了所有 NoneBot 运行时可能会抛出的异常。
下列文档中的异常是所有 NoneBot 运行时可能会抛出的。
这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。
```bash
NoneBotException
├── ParserExit
├── ProcessException
| ├── IgnoredException
| ├── SkippedException
| | └── TypeMisMatch
| ├── MockApiException
| └── StopPropagation
├── MatcherException
| ├── PausedException
| ├── RejectedException
| └── FinishedException
├── AdapterException
| ├── NoLogException
| ├── ApiNotAvailable
| ├── NetworkError
| └── ActionFailed
└── DriverException
└── WebSocketClosed
```
FrontMatter:
sidebar_position: 10
description: nonebot.exception 模块
"""
from typing import Any, Optional
@@ -12,25 +35,12 @@ from pydantic.fields import ModelField
class NoneBotException(Exception):
"""
:说明:
所有 NoneBot 发生的异常基类。
"""
"""所有 NoneBot 发生的异常基类。"""
# Rule Exception
class ParserExit(NoneBotException):
"""
:说明:
``shell command`` 处理消息失败时返回的异常
:参数:
* ``status``
* ``message``
"""
"""{ref}`nonebot.rule.shell_command` 处理消息失败时返回的异常"""
def __init__(self, status: int = 0, message: Optional[str] = None):
self.status = status
@@ -45,26 +55,18 @@ class ParserExit(NoneBotException):
# Processor Exception
class ProcessException(NoneBotException):
"""
:说明:
事件处理过程中发生的异常基类。
"""
"""事件处理过程中发生的异常基类。"""
class IgnoredException(ProcessException):
"""
:说明:
"""指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。
指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。
:参数:
* ``reason``: 忽略事件的原因
参数:
reason: 忽略事件的原因
"""
def __init__(self, reason):
self.reason = reason
def __init__(self, reason: Any):
self.reason: Any = reason
def __repr__(self):
return f"<IgnoredException, reason={self.reason}>"
@@ -73,15 +75,42 @@ class IgnoredException(ProcessException):
return self.__repr__()
class MockApiException(ProcessException):
class SkippedException(ProcessException):
"""指示 NoneBot 立即结束当前 `Dependent` 的运行。
例如,可以在 `Handler` 中通过 {ref}`nonebot.matcher.Matcher.skip` 抛出。
用法:
```python
def always_skip():
Matcher.skip()
@matcher.handle()
async def handler(dependency = Depends(always_skip)):
# never run
```
"""
:说明:
指示 NoneBot 阻止本次 API 调用或修改本次调用返回值,并返回自定义内容。可由 api hook 抛出。
:参数:
class TypeMisMatch(SkippedException):
"""当前 `Handler` 的参数类型不匹配。"""
* ``result``: 返回的内容
def __init__(self, param: ModelField, value: Any):
self.param: ModelField = param
self.value: Any = value
def __repr__(self):
return f"<TypeMisMatch, param={self.param}, value={self.value}>"
def __str__(self):
self.__repr__()
class MockApiException(ProcessException):
"""指示 NoneBot 阻止本次 API 调用或修改本次调用返回值,并返回自定义内容。可由 api hook 抛出。
参数:
result: 返回的内容
"""
def __init__(self, result: Any):
@@ -95,166 +124,107 @@ class MockApiException(ProcessException):
class StopPropagation(ProcessException):
"""
:说明:
"""指示 NoneBot 终止事件向下层传播。
指示 NoneBot 终止事件向下层传播。
{ref}`nonebot.matcher.Matcher.block` 为 `True`
或使用 {ref}`nonebot.matcher.Matcher.stop_propagation` 方法时抛出。
:用法:
在 ``Matcher.block == True`` 时抛出。
用法:
```python
matcher = on_notice(block=True)
# 或者
@matcher.handle()
async def handler(matcher: Matcher):
matcher.stop_propagation()
```
"""
# Matcher Exceptions
class MatcherException(NoneBotException):
"""
:说明:
所有 Matcher 发生的异常基类。
"""
class SkippedException(MatcherException):
"""
:说明:
指示 NoneBot 立即结束当前 ``Handler`` 的处理,继续处理下一个 ``Handler``。
:用法:
可以在 ``Handler`` 中通过 ``Matcher.skip()`` 抛出。
"""
class TypeMisMatch(SkippedException):
"""
:说明:
当前 ``Handler`` 的参数类型不匹配。
"""
def __init__(self, param: ModelField, value: Any):
self.param: ModelField = param
self.value: Any = value
def __repr__(self):
return f"<TypeMisMatch, param={self.param}, value={self.value}>"
def __str__(self):
self.__repr__()
"""所有 Matcher 发生的异常基类。"""
class PausedException(MatcherException):
"""
:说明:
"""指示 NoneBot 结束当前 `Handler` 并等待下一条消息后继续下一个 `Handler`。可用于用户输入新信息。
指示 NoneBot 结束当前 ``Handler`` 并等待下一条消息后继续下一个 ``Handler``
可用于用户输入新信息。
可以在 `Handler` 中通过 {ref}`nonebot.matcher.Matcher.pause` 抛出
:用法:
可以在 ``Handler`` 中通过 ``Matcher.pause()`` 抛出。
用法:
```python
@matcher.handle()
async def handler():
await matcher.pause("some message")
```
"""
class RejectedException(MatcherException):
"""
:说明:
"""指示 NoneBot 结束当前 `Handler` 并等待下一条消息后重新运行当前 `Handler`。可用于用户重新输入。
指示 NoneBot 结束当前 ``Handler`` 并等待下一条消息后重新运行当前 ``Handler``
可用于用户重新输入。
可以在 `Handler` 中通过 {ref}`nonebot.matcher.Matcher.reject` 抛出
:用法:
可以在 ``Handler`` 中通过 ``Matcher.reject()`` 抛出。
用法:
```python
@matcher.handle()
async def handler():
await matcher.reject("some message")
```
"""
class FinishedException(MatcherException):
"""
:说明:
"""指示 NoneBot 结束当前 `Handler` 且后续 `Handler` 不再被运行。可用于结束用户会话。
指示 NoneBot 结束当前 ``Handler`` 且后续 ``Handler`` 不再被运行
可用于结束用户会话。
可以在 `Handler` 中通过 {ref}`nonebot.matcher.Matcher.finish` 抛出
:用法:
可以在 ``Handler`` 中通过 ``Matcher.finish()`` 抛出。
用法:
```python
@matcher.handle()
async def handler():
await matcher.finish("some message")
```
"""
# Adapter Exceptions
class AdapterException(NoneBotException):
"""
:说明:
"""代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception`
代表 ``Adapter`` 抛出的异常,所有的 ``Adapter`` 都要在内部继承自这个 ``Exception``
:参数:
* ``adapter_name: str``: 标识 adapter
参数:
adapter_name: 标识 adapter
"""
def __init__(self, adapter_name: str) -> None:
self.adapter_name = adapter_name
self.adapter_name: str = adapter_name
class NoLogException(AdapterException):
"""
:说明:
"""指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息。
指示 NoneBot 对当前 ``Event`` 进行处理但不显示 Log 信息,可在 ``get_log_string`` 时抛出
可在 {ref}`nonebot.adapters.Event.get_log_string` 时抛出
"""
pass
class ApiNotAvailable(AdapterException):
"""
:说明:
在 API 连接不可用时抛出。
"""
pass
"""在 API 连接不可用时抛出。"""
class NetworkError(AdapterException):
"""
:说明:
在网络出现问题时抛出,如: API 请求地址不正确, API 请求无返回或返回状态非正常等。
"""
pass
"""在网络出现问题时抛出,如: API 请求地址不正确, API 请求无返回或返回状态非正常等。"""
class ActionFailed(AdapterException):
"""
:说明:
API 请求成功返回数据,但 API 操作失败。
"""
pass
"""API 请求成功返回数据,但 API 操作失败。"""
# Driver Exceptions
class DriverException(NoneBotException):
"""
:说明:
``Driver`` 抛出的异常基类
"""
"""`Driver` 抛出的异常基类"""
class WebSocketClosed(DriverException):
"""
:说明:
WebSocket 连接已关闭
"""
"""WebSocket 连接已关闭"""
def __init__(self, code: int, reason: Optional[str] = None):
self.code = code

View File

@@ -0,0 +1,6 @@
from .bot import Bot as Bot
from .event import Event as Event
from .adapter import Adapter as Adapter
from .message import Message as Message
from .message import MessageSegment as MessageSegment
from .template import MessageTemplate as MessageTemplate

View File

@@ -2,9 +2,8 @@ import abc
from contextlib import asynccontextmanager
from typing import Any, Dict, AsyncGenerator
from ._bot import Bot
from nonebot.config import Config
from nonebot.drivers import (
from nonebot.internal.driver import (
Driver,
Request,
Response,
@@ -15,61 +14,93 @@ from nonebot.drivers import (
WebSocketServerSetup,
)
from .bot import Bot
class Adapter(abc.ABC):
"""协议适配器基类。
通常 Adapter 中编写协议通信相关代码: 建立通信连接处理接收与发送 data
参数:
driver: {ref}`nonebot.drivers.Driver` 实例
kwargs: 其他由 {ref}`nonebot.drivers.Driver.register_adapter` 传入的额外参数
"""
def __init__(self, driver: Driver, **kwargs: Any):
self.driver: Driver = driver
"""{ref}`nonebot.drivers.Driver` 实例"""
self.bots: Dict[str, Bot] = {}
"""本协议适配器已建立连接的 {ref}`nonebot.adapters.Bot` 实例"""
@classmethod
@abc.abstractmethod
def get_name(cls) -> str:
"""当前协议适配器的名称"""
raise NotImplementedError
@property
def config(self) -> Config:
"""全局 NoneBot 配置"""
return self.driver.config
def bot_connect(self, bot: Bot) -> None:
"""告知 NoneBot 建立了一个新的 {ref}`nonebot.adapters.Bot` 连接。
当有新的 {ref}`nonebot.adapters.Bot` 实例连接建立成功时调用
参数:
bot: {ref}`nonebot.adapters.Bot` 实例
"""
self.driver._bot_connect(bot)
self.bots[bot.self_id] = bot
def bot_disconnect(self, bot: Bot) -> None:
"""告知 NoneBot {ref}`nonebot.adapters.Bot` 连接已断开。
当有 {ref}`nonebot.adapters.Bot` 实例连接断开时调用
参数:
bot: {ref}`nonebot.adapters.Bot` 实例
"""
self.driver._bot_disconnect(bot)
self.bots.pop(bot.self_id, None)
def setup_http_server(self, setup: HTTPServerSetup):
"""设置一个 HTTP 服务器路由配置"""
if not isinstance(self.driver, ReverseDriver):
raise TypeError("Current driver does not support http server")
self.driver.setup_http_server(setup)
def setup_websocket_server(self, setup: WebSocketServerSetup):
"""设置一个 WebSocket 服务器路由配置"""
if not isinstance(self.driver, ReverseDriver):
raise TypeError("Current driver does not support websocket server")
self.driver.setup_websocket_server(setup)
async def request(self, setup: Request) -> Response:
"""进行一个 HTTP 客户端请求"""
if not isinstance(self.driver, ForwardDriver):
raise TypeError("Current driver does not support http client")
return await self.driver.request(setup)
@asynccontextmanager
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
"""建立一个 WebSocket 客户端连接请求"""
if not isinstance(self.driver, ForwardDriver):
raise TypeError("Current driver does not support websocket client")
async with self.driver.websocket(setup) as ws:
yield ws
@abc.abstractmethod
async def _call_api(self, bot: Bot, api: str, **data) -> Any:
"""
:说明:
async def _call_api(self, bot: Bot, api: str, **data: Any) -> Any:
"""`Adapter` 实际调用 api 的逻辑实现函数,实现该方法以调用 api。
``adapter`` 实际调用 api 的逻辑实现函数实现该方法以调用 api
:参数:
* ``api: str``: API 名称
* ``**data``: API 数据
参数:
api: API 名称
data: API 数据
"""
raise NotImplementedError
__autodoc__ = {"Adapter._call_api": True}

View File

@@ -10,9 +10,9 @@ from nonebot.exception import MockApiException
from nonebot.typing import T_CalledAPIHook, T_CallingAPIHook
if TYPE_CHECKING:
from ._event import Event
from ._adapter import Adapter
from ._message import Message, MessageSegment
from .event import Event
from .adapter import Adapter
from .message import Message, MessageSegment
class _ApiCall(Protocol):
@@ -21,29 +21,23 @@ class _ApiCall(Protocol):
class Bot(abc.ABC):
"""
Bot 基类用于处理上报消息并提供 API 调用接口
"""Bot 基类。
用于处理上报消息并提供 API 调用接口
参数:
adapter: 协议适配器实例
self_id: 机器人 ID
"""
_calling_api_hook: Set[T_CallingAPIHook] = set()
"""
:类型: ``Set[T_CallingAPIHook]``
:说明: call_api 时执行的函数
"""
"""call_api 时执行的函数"""
_called_api_hook: Set[T_CalledAPIHook] = set()
"""
:类型: ``Set[T_CalledAPIHook]``
:说明: call_api 后执行的函数
"""
"""call_api 后执行的函数"""
def __init__(self, adapter: "Adapter", self_id: str):
"""
:参数:
* ``self_id: str``: 机器人 ID
* ``request: HTTPConnection``: request 连接对象
"""
self.adapter: "Adapter" = adapter
"""协议适配器实例"""
self.self_id: str = self_id
"""机器人 ID"""
@@ -52,29 +46,26 @@ class Bot(abc.ABC):
@property
def type(self) -> str:
"""协议适配器名称"""
return self.adapter.get_name()
@property
def config(self) -> Config:
"""全局 NoneBot 配置"""
return self.adapter.config
async def call_api(self, api: str, **data: Any) -> Any:
"""
:说明:
"""调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
调用机器人 API 接口可以通过该函数或直接通过 bot 属性进行调用
:参数:
* ``api: str``: API 名称
* ``**data``: API 数据
:示例:
.. code-block:: python
参数:
api: API 名称
data: API 数据
用法:
```python
await bot.call_api("send_msg", message="hello world")
await bot.send_msg(message="hello world")
```
"""
result: Any = None
@@ -128,51 +119,44 @@ class Bot(abc.ABC):
@abc.abstractmethod
async def send(
self, event: "Event", message: Union[str, "Message", "MessageSegment"], **kwargs
self,
event: "Event",
message: Union[str, "Message", "MessageSegment"],
**kwargs: Any,
) -> Any:
"""
:说明:
"""调用机器人基础发送消息接口
调用机器人基础发送消息接口
:参数:
* ``event: Event``: 上报事件
* ``message: Union[str, Message, MessageSegment]``: 要发送的消息
* ``**kwargs``
参数:
event: 上报事件
message: 要发送的消息
kwargs: 任意额外参数
"""
raise NotImplementedError
@classmethod
def on_calling_api(cls, func: T_CallingAPIHook) -> T_CallingAPIHook:
"""
:说明:
"""调用 api 预处理。
调用 api 预处理
钩子函数参数:
:参数:
* ``bot: Bot``: 当前 bot 对象
* ``api: str``: 调用的 api 名称
* ``data: Dict[str, Any]``: api 调用的参数字典
- bot: 当前 bot 对象
- api: 调用的 api 名称
- data: api 调用的参数字典
"""
cls._calling_api_hook.add(func)
return func
@classmethod
def on_called_api(cls, func: T_CalledAPIHook) -> T_CalledAPIHook:
"""
:说明:
"""调用 api 后处理。
调用 api 后处理
钩子函数参数:
:参数:
* ``bot: Bot``: 当前 bot 对象
* ``exception: Optional[Exception]``: 调用 api 时发生的错误
* ``api: str``: 调用的 api 名称
* ``data: Dict[str, Any]``: api 调用的参数字典
* ``result: Any``: api 调用的返回
- bot: 当前 bot 对象
- exception: 调用 api 时发生的错误
- api: 调用的 api 名称
- data: api 调用的参数字典
- result: api 调用的返回
"""
cls._called_api_hook.add(func)
return func

View File

@@ -0,0 +1,79 @@
import abc
from typing import Any, Type, TypeVar
from pydantic import BaseModel
from nonebot.utils import DataclassEncoder
from .message import Message
E = TypeVar("E", bound="Event")
class Event(abc.ABC, BaseModel):
"""Event 基类。提供获取关键信息的方法,其余信息可直接获取。"""
class Config:
extra = "allow"
json_encoders = {Message: DataclassEncoder}
@classmethod
def validate(cls: Type["E"], value: Any) -> "E":
if isinstance(value, Event) and not isinstance(value, cls):
raise TypeError(f"{value} is incompatible with Event type {cls}")
return super().validate(value)
@abc.abstractmethod
def get_type(self) -> str:
"""获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。"""
raise NotImplementedError
@abc.abstractmethod
def get_event_name(self) -> str:
"""获取事件名称的方法。"""
raise NotImplementedError
@abc.abstractmethod
def get_event_description(self) -> str:
"""获取事件描述的方法,通常为事件具体内容。"""
raise NotImplementedError
def __str__(self) -> str:
return f"[{self.get_event_name()}]: {self.get_event_description()}"
def get_log_string(self) -> str:
"""获取事件日志信息的方法。
通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 `NoLogException` 异常。
异常:
NoLogException
"""
return f"[{self.get_event_name()}]: {self.get_event_description()}"
@abc.abstractmethod
def get_user_id(self) -> str:
"""获取事件主体 id 的方法,通常是用户 id 。"""
raise NotImplementedError
@abc.abstractmethod
def get_session_id(self) -> str:
"""获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。"""
raise NotImplementedError
@abc.abstractmethod
def get_message(self) -> "Message":
"""获取事件消息内容的方法。"""
raise NotImplementedError
def get_plaintext(self) -> str:
"""获取消息纯文本的方法。
通常不需要修改,默认通过 `get_message().extract_plain_text` 获取。
"""
return self.get_message().extract_plain_text()
@abc.abstractmethod
def is_tome(self) -> bool:
"""获取事件是否与机器人有关的方法。"""
raise NotImplementedError

View File

@@ -0,0 +1,329 @@
import abc
from copy import deepcopy
from dataclasses import field, asdict, dataclass
from typing import (
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
Iterable,
Optional,
overload,
)
from pydantic import parse_obj_as
from .template import MessageTemplate
T = TypeVar("T")
TMS = TypeVar("TMS", bound="MessageSegment")
TM = TypeVar("TM", bound="Message")
@dataclass
class MessageSegment(abc.ABC, Generic[TM]):
"""消息段基类"""
type: str
"""消息段类型"""
data: Dict[str, Any] = field(default_factory=dict)
"""消息段数据"""
@classmethod
@abc.abstractmethod
def get_message_class(cls) -> Type[TM]:
"""获取消息数组类型"""
raise NotImplementedError
@abc.abstractmethod
def __str__(self) -> str:
"""该消息段所代表的 str在命令匹配部分使用"""
raise NotImplementedError
def __len__(self) -> int:
return len(str(self))
def __ne__(self: T, other: T) -> bool:
return not self == other
def __add__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:
return self.get_message_class()(self) + other
def __radd__(self: TMS, other: Union[str, TMS, Iterable[TMS]]) -> TM:
return self.get_message_class()(other) + self
@classmethod
def __get_validators__(cls):
yield cls._validate
@classmethod
def _validate(cls, value):
if isinstance(value, cls):
return value
if not isinstance(value, dict):
raise ValueError(f"Expected dict for MessageSegment, got {type(value)}")
if "type" not in value:
raise ValueError(
f"Expected dict with 'type' for MessageSegment, got {value}"
)
return cls(type=value["type"], data=value.get("data", {}))
def get(self, key: str, default: Any = None):
return asdict(self).get(key, default)
def keys(self):
return asdict(self).keys()
def values(self):
return asdict(self).values()
def items(self):
return asdict(self).items()
def copy(self: T) -> T:
return deepcopy(self)
@abc.abstractmethod
def is_text(self) -> bool:
"""当前消息段是否为纯文本"""
raise NotImplementedError
class Message(List[TMS], abc.ABC):
"""消息数组
参数:
message: 消息内容
"""
def __init__(
self,
message: Union[str, None, Iterable[TMS], TMS] = None,
):
super().__init__()
if message is None:
return
elif isinstance(message, str):
self.extend(self._construct(message))
elif isinstance(message, MessageSegment):
self.append(message)
elif isinstance(message, Iterable):
self.extend(message)
else:
self.extend(self._construct(message)) # pragma: no cover
@classmethod
def template(cls: Type[TM], format_string: Union[str, TM]) -> MessageTemplate[TM]:
"""创建消息模板。
用法和 `str.format` 大致相同, 但是可以输出消息对象, 并且支持以 `Message` 对象作为消息模板
并且提供了拓展的格式化控制符, 可以用适用于该消息类型的 `MessageSegment` 的工厂方法创建消息
参数:
format_string: 格式化模板
返回:
消息格式化器
"""
return MessageTemplate(format_string, cls)
@classmethod
@abc.abstractmethod
def get_segment_class(cls) -> Type[TMS]:
"""获取消息段类型"""
raise NotImplementedError
def __str__(self) -> str:
return "".join(str(seg) for seg in self)
@classmethod
def __get_validators__(cls):
yield cls._validate
@classmethod
def _validate(cls, value):
if isinstance(value, cls):
return value
elif isinstance(value, Message):
raise ValueError(f"Type {type(value)} can not be converted to {cls}")
elif isinstance(value, str):
pass
elif isinstance(value, dict):
value = parse_obj_as(cls.get_segment_class(), value)
elif isinstance(value, Iterable):
value = [parse_obj_as(cls.get_segment_class(), v) for v in value]
else:
raise ValueError(
f"Expected str, dict or iterable for Message, got {type(value)}"
)
return cls(value)
@staticmethod
@abc.abstractmethod
def _construct(msg: str) -> Iterable[TMS]:
"""构造消息数组"""
raise NotImplementedError
def __add__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:
result = self.copy()
result += other
return result
def __radd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:
result = self.__class__(other)
return result + self
def __iadd__(self: TM, other: Union[str, TMS, Iterable[TMS]]) -> TM:
if isinstance(other, str):
self.extend(self._construct(other))
elif isinstance(other, MessageSegment):
self.append(other)
elif isinstance(other, Iterable):
self.extend(other)
else:
raise ValueError(f"Unsupported type: {type(other)}") # pragma: no cover
return self
@overload
def __getitem__(self: TM, __args: str) -> TM:
"""
参数:
__args: 消息段类型
返回:
所有类型为 `__args` 的消息段
"""
@overload
def __getitem__(self, __args: Tuple[str, int]) -> TMS:
"""
参数:
__args: 消息段类型和索引
返回:
类型为 `__args[0]` 的消息段第 `__args[1]` 个
"""
@overload
def __getitem__(self: TM, __args: Tuple[str, slice]) -> TM:
"""
参数:
__args: 消息段类型和切片
返回:
类型为 `__args[0]` 的消息段切片 `__args[1]`
"""
@overload
def __getitem__(self, __args: int) -> TMS:
"""
参数:
__args: 索引
返回:
第 `__args` 个消息段
"""
@overload
def __getitem__(self: TM, __args: slice) -> TM:
"""
参数:
__args: 切片
返回:
消息切片 `__args`
"""
def __getitem__(
self: TM,
args: Union[
str,
Tuple[str, int],
Tuple[str, slice],
int,
slice,
],
) -> Union[TMS, TM]:
arg1, arg2 = args if isinstance(args, tuple) else (args, None)
if isinstance(arg1, int) and arg2 is None:
return super().__getitem__(arg1)
elif isinstance(arg1, slice) and arg2 is None:
return self.__class__(super().__getitem__(arg1))
elif isinstance(arg1, str) and arg2 is None:
return self.__class__(seg for seg in self if seg.type == arg1)
elif isinstance(arg1, str) and isinstance(arg2, int):
return [seg for seg in self if seg.type == arg1][arg2]
elif isinstance(arg1, str) and isinstance(arg2, slice):
return self.__class__([seg for seg in self if seg.type == arg1][arg2])
else:
raise ValueError("Incorrect arguments to slice") # pragma: no cover
def index(self, value: Union[TMS, str], *args) -> int:
if isinstance(value, str):
first_segment = next((seg for seg in self if seg.type == value), None)
if first_segment is None:
raise ValueError(f"Segment with type {value} is not in message")
return super().index(first_segment, *args)
return super().index(value, *args)
def get(self: TM, type_: str, count: Optional[int] = None) -> TM:
if count is None:
return self[type_]
iterator, filtered = (
seg for seg in self if seg.type == type_
), self.__class__()
for _ in range(count):
seg = next(iterator, None)
if seg is None:
break
filtered.append(seg)
return filtered
def count(self, value: Union[TMS, str]) -> int:
return len(self[value]) if isinstance(value, str) else super().count(value)
def append(self: TM, obj: Union[str, TMS]) -> TM:
"""添加一个消息段到消息数组末尾。
参数:
obj: 要添加的消息段
"""
if isinstance(obj, MessageSegment):
super().append(obj)
elif isinstance(obj, str):
self.extend(self._construct(obj))
else:
raise ValueError(f"Unexpected type: {type(obj)} {obj}") # pragma: no cover
return self
def extend(self: TM, obj: Union[TM, Iterable[TMS]]) -> TM:
"""拼接一个消息数组或多个消息段到消息数组末尾。
参数:
obj: 要添加的消息数组
"""
for segment in obj:
self.append(segment)
return self
def copy(self: TM) -> TM:
return deepcopy(self)
def extract_plain_text(self) -> str:
"""提取消息内纯文本消息"""
return "".join(str(seg) for seg in self if seg.is_text())
__autodoc__ = {
"MessageSegment.__str__": True,
"MessageSegment.__add__": True,
"Message.__getitem__": True,
"Message._construct": True,
}

View File

@@ -1,4 +1,3 @@
import inspect
import functools
from string import Formatter
from typing import (
@@ -21,7 +20,7 @@ from typing import (
)
if TYPE_CHECKING:
from . import Message, MessageSegment
from .message import Message, MessageSegment
TM = TypeVar("TM", bound="Message")
TF = TypeVar("TF", str, "Message")
@@ -31,7 +30,12 @@ FormatSpecFunc_T = TypeVar("FormatSpecFunc_T", bound=FormatSpecFunc)
class MessageTemplate(Formatter, Generic[TF]):
"""消息模板格式化实现类"""
"""消息模板格式化实现类
参数:
template: 模板
factory: 消息类型工厂默认为 `str`
"""
@overload
def __init__(
@@ -45,17 +49,9 @@ class MessageTemplate(Formatter, Generic[TF]):
) -> None:
...
def __init__(self, template, factory=str) -> None:
"""
:说明:
创建一个模板
:参数:
* ``template: Union[str, Message]``: 模板
* ``factory: Union[str, Message]``: 消息构造类型默认为 `str`
"""
def __init__( # type:ignore
self, template, factory=str
) -> None: # TODO: fix type hint here
self.template: TF = template
self.factory: Type[TF] = factory
self.format_specs: Dict[str, FormatSpecFunc] = {}
@@ -69,31 +65,46 @@ class MessageTemplate(Formatter, Generic[TF]):
self.format_specs[name] = spec
return spec
def format(self, *args: Any, **kwargs: Any) -> TF:
"""
:说明:
def format(self, *args, **kwargs):
"""根据传入参数和模板生成消息对象"""
return self._format(args, kwargs)
def format_map(self, mapping: Mapping[str, Any]) -> TF:
"""根据传入字典和模板生成消息对象, 在传入字段名不是有效标识符时有用"""
return self._format([], mapping)
def _format(self, args: Sequence[Any], kwargs: Mapping[str, Any]) -> TF:
full_message = self.factory()
used_args, arg_index = set(), 0
根据模板和参数生成消息对象
"""
msg = self.factory()
if isinstance(self.template, str):
msg += self.vformat(self.template, args, kwargs)
msg, arg_index = self._vformat(
self.template, args, kwargs, used_args, arg_index
)
full_message += msg
elif isinstance(self.template, self.factory):
template = cast("Message[MessageSegment]", self.template)
for seg in template:
msg += self.vformat(str(seg), args, kwargs) if seg.is_text() else seg
if not seg.is_text():
full_message += seg
else:
msg, arg_index = self._vformat(
str(seg), args, kwargs, used_args, arg_index
)
full_message += msg
else:
raise TypeError("template must be a string or instance of Message!")
return msg # type:ignore
self.check_unused_args(list(used_args), args, kwargs)
return cast(TF, full_message)
def vformat(
self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]
self,
format_string: str,
args: Sequence[Any],
kwargs: Mapping[str, Any],
) -> TF:
used_args = set()
result, _ = self._vformat(format_string, args, kwargs, used_args, 2)
self.check_unused_args(list(used_args), args, kwargs)
return result
raise NotImplementedError("`vformat` has merged into `_format`")
def _vformat(
self,
@@ -101,13 +112,9 @@ class MessageTemplate(Formatter, Generic[TF]):
args: Sequence[Any],
kwargs: Mapping[str, Any],
used_args: Set[Union[int, str]],
recursion_depth: int,
auto_arg_index: int = 0,
) -> Tuple[TF, int]:
if recursion_depth < 0:
raise ValueError("Max string recursion exceeded")
results: List[Any] = []
results: List[Any] = [self.factory()]
for (literal_text, field_name, format_spec, conversion) in self.parse(
format_string
@@ -146,36 +153,23 @@ class MessageTemplate(Formatter, Generic[TF]):
obj, arg_used = self.get_field(field_name, args, kwargs)
used_args.add(arg_used)
assert format_spec is not None
# do any conversion on the resulting object
obj = self.convert_field(obj, conversion) if conversion else obj
# expand the format spec, if needed
format_control, auto_arg_index = self._vformat(
format_spec,
args,
kwargs,
used_args,
recursion_depth - 1,
auto_arg_index,
)
# format the object and append to the result
formatted_text = self.format_field(obj, str(format_control))
formatted_text = (
self.format_field(obj, format_spec) if format_spec else obj
)
results.append(formatted_text)
return (
self.factory(functools.reduce(self._add, results or [""])),
auto_arg_index,
)
return functools.reduce(self._add, results), auto_arg_index
def format_field(self, value: Any, format_spec: str) -> Any:
formatter: Optional[FormatSpecFunc] = self.format_specs.get(format_spec)
if formatter is None and not issubclass(self.factory, str):
segment_class: Type["MessageSegment"] = self.factory.get_segment_class()
method = getattr(segment_class, format_spec, None)
if inspect.ismethod(method):
if callable(method) and not cast(str, method.__name__).startswith("_"):
formatter = getattr(segment_class, format_spec)
return (
super().format_field(value, format_spec)

View File

@@ -0,0 +1,25 @@
from .model import URL as URL
from .model import RawURL as RawURL
from .driver import Driver as Driver
from .model import Cookies as Cookies
from .model import Request as Request
from .model import FileType as FileType
from .model import Response as Response
from .model import DataTypes as DataTypes
from .model import FileTypes as FileTypes
from .model import WebSocket as WebSocket
from .model import FilesTypes as FilesTypes
from .model import QueryTypes as QueryTypes
from .model import CookieTypes as CookieTypes
from .model import FileContent as FileContent
from .model import HTTPVersion as HTTPVersion
from .model import HeaderTypes as HeaderTypes
from .model import SimpleQuery as SimpleQuery
from .model import ContentTypes as ContentTypes
from .driver import ForwardMixin as ForwardMixin
from .model import QueryVariable as QueryVariable
from .driver import ForwardDriver as ForwardDriver
from .driver import ReverseDriver as ReverseDriver
from .driver import combine_driver as combine_driver
from .model import HTTPServerSetup as HTTPServerSetup
from .model import WebSocketServerSetup as WebSocketServerSetup

View File

@@ -0,0 +1,245 @@
import abc
import asyncio
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any, Set, Dict, Type, Callable, AsyncGenerator
from nonebot.log import logger
from nonebot.config import Env, Config
from nonebot.dependencies import Dependent
from nonebot.exception import SkippedException
from nonebot.utils import escape_tag, run_coro_with_catch
from nonebot.typing import T_BotConnectionHook, T_BotDisconnectionHook
from nonebot.internal.params import BotParam, DependParam, DefaultParam
from .model import Request, Response, WebSocket, HTTPServerSetup, WebSocketServerSetup
if TYPE_CHECKING:
from nonebot.internal.adapter import Bot, Adapter
BOT_HOOK_PARAMS = [DependParam, BotParam, DefaultParam]
class Driver(abc.ABC):
"""Driver 基类。
参数:
env: 包含环境信息的 Env 对象
config: 包含配置信息的 Config 对象
"""
_adapters: Dict[str, "Adapter"] = {}
"""已注册的适配器列表"""
_bot_connection_hook: Set[Dependent[Any]] = set()
"""Bot 连接建立时执行的函数"""
_bot_disconnection_hook: Set[Dependent[Any]] = set()
"""Bot 连接断开时执行的函数"""
def __init__(self, env: Env, config: Config):
self.env: str = env.environment
"""环境名称"""
self.config: Config = config
"""全局配置对象"""
self._clients: Dict[str, "Bot"] = {}
@property
def bots(self) -> Dict[str, "Bot"]:
"""获取当前所有已连接的 Bot"""
return self._clients
def register_adapter(self, adapter: Type["Adapter"], **kwargs) -> None:
"""注册一个协议适配器
参数:
adapter: 适配器类
kwargs: 其他传递给适配器的参数
"""
name = adapter.get_name()
if name in self._adapters:
logger.opt(colors=True).debug(
f'Adapter "<y>{escape_tag(name)}</y>" already exists'
)
return
self._adapters[name] = adapter(self, **kwargs)
logger.opt(colors=True).debug(
f'Succeeded to load adapter "<y>{escape_tag(name)}</y>"'
)
@property
@abc.abstractmethod
def type(self) -> str:
"""驱动类型名称"""
raise NotImplementedError
@property
@abc.abstractmethod
def logger(self):
"""驱动专属 logger 日志记录器"""
raise NotImplementedError
@abc.abstractmethod
def run(self, *args, **kwargs):
"""
启动驱动框架
"""
logger.opt(colors=True).debug(
f"<g>Loaded adapters: {escape_tag(', '.join(self._adapters))}</g>"
)
@abc.abstractmethod
def on_startup(self, func: Callable) -> Callable:
"""注册一个在驱动器启动时执行的函数"""
raise NotImplementedError
@abc.abstractmethod
def on_shutdown(self, func: Callable) -> Callable:
"""注册一个在驱动器停止时执行的函数"""
raise NotImplementedError
@classmethod
def on_bot_connect(cls, func: T_BotConnectionHook) -> T_BotConnectionHook:
"""装饰一个函数使他在 bot 连接成功时执行。
钩子函数参数:
- bot: 当前连接上的 Bot 对象
"""
cls._bot_connection_hook.add(
Dependent[Any].parse(call=func, allow_types=BOT_HOOK_PARAMS)
)
return func
@classmethod
def on_bot_disconnect(cls, func: T_BotDisconnectionHook) -> T_BotDisconnectionHook:
"""装饰一个函数使他在 bot 连接断开时执行。
钩子函数参数:
- bot: 当前连接上的 Bot 对象
"""
cls._bot_disconnection_hook.add(
Dependent[Any].parse(call=func, allow_types=BOT_HOOK_PARAMS)
)
return func
def _bot_connect(self, bot: "Bot") -> None:
"""在连接成功后,调用该函数来注册 bot 对象"""
if bot.self_id in self._clients:
raise RuntimeError(f"Duplicate bot connection with id {bot.self_id}")
self._clients[bot.self_id] = bot
async def _run_hook(bot: "Bot") -> None:
coros = list(
map(
lambda x: run_coro_with_catch(x(bot=bot), (SkippedException,)),
self._bot_connection_hook,
)
)
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running WebSocketConnection hook. "
"Running cancelled!</bg #f8bbd0></r>"
)
asyncio.create_task(_run_hook(bot))
def _bot_disconnect(self, bot: "Bot") -> None:
"""在连接断开后,调用该函数来注销 bot 对象"""
if bot.self_id in self._clients:
del self._clients[bot.self_id]
async def _run_hook(bot: "Bot") -> None:
coros = list(
map(
lambda x: run_coro_with_catch(x(bot=bot), (SkippedException,)),
self._bot_disconnection_hook,
)
)
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running WebSocketDisConnection hook. "
"Running cancelled!</bg #f8bbd0></r>"
)
asyncio.create_task(_run_hook(bot))
class ForwardMixin(abc.ABC):
"""客户端混入基类。"""
@property
@abc.abstractmethod
def type(self) -> str:
"""客户端驱动类型名称"""
raise NotImplementedError
@abc.abstractmethod
async def request(self, setup: Request) -> Response:
"""发送一个 HTTP 请求"""
raise NotImplementedError
@abc.abstractmethod
@asynccontextmanager
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
"""发起一个 WebSocket 连接"""
raise NotImplementedError
yield # used for static type checking's generator detection
class ForwardDriver(Driver, ForwardMixin):
"""客户端基类。将客户端框架封装,以满足适配器使用。"""
class ReverseDriver(Driver):
"""服务端基类。将后端框架封装,以满足适配器使用。"""
@property
@abc.abstractmethod
def server_app(self) -> Any:
"""驱动 APP 对象"""
raise NotImplementedError
@property
@abc.abstractmethod
def asgi(self) -> Any:
"""驱动 ASGI 对象"""
raise NotImplementedError
@abc.abstractmethod
def setup_http_server(self, setup: "HTTPServerSetup") -> None:
"""设置一个 HTTP 服务器路由配置"""
raise NotImplementedError
@abc.abstractmethod
def setup_websocket_server(self, setup: "WebSocketServerSetup") -> None:
"""设置一个 WebSocket 服务器路由配置"""
raise NotImplementedError
def combine_driver(driver: Type[Driver], *mixins: Type[ForwardMixin]) -> Type[Driver]:
"""将一个驱动器和多个混入类合并。"""
# check first
assert issubclass(driver, Driver), "`driver` must be subclass of Driver"
assert all(
map(lambda m: issubclass(m, ForwardMixin), mixins)
), "`mixins` must be subclass of ForwardMixin"
if not mixins:
return driver
class CombinedDriver(*mixins, driver, ForwardDriver): # type: ignore
@property
def type(self) -> str:
return (
driver.type.__get__(self)
+ "+"
+ "+".join(map(lambda x: x.type.__get__(self), mixins))
)
return CombinedDriver

View File

@@ -1,5 +1,6 @@
import abc
from enum import Enum
from dataclasses import dataclass
from http.cookiejar import Cookie, CookieJar
from typing import (
IO,
@@ -9,8 +10,10 @@ from typing import (
Tuple,
Union,
Mapping,
Callable,
Iterator,
Optional,
Awaitable,
MutableMapping,
)
@@ -168,8 +171,7 @@ class WebSocket(abc.ABC):
@abc.abstractmethod
def closed(self) -> bool:
"""
:类型: ``bool``
:说明: 连接是否已经关闭
连接是否已经关闭
"""
raise NotImplementedError
@@ -184,7 +186,12 @@ class WebSocket(abc.ABC):
raise NotImplementedError
@abc.abstractmethod
async def receive(self) -> str:
async def receive(self) -> Union[str, bytes]:
"""接收一条 WebSocket text/bytes 信息"""
raise NotImplementedError
@abc.abstractmethod
async def receive_text(self) -> str:
"""接收一条 WebSocket text 信息"""
raise NotImplementedError
@@ -193,8 +200,17 @@ class WebSocket(abc.ABC):
"""接收一条 WebSocket binary 信息"""
raise NotImplementedError
async def send(self, data: Union[str, bytes]) -> None:
"""发送一条 WebSocket text/bytes 信息"""
if isinstance(data, str):
await self.send_text(data)
elif isinstance(data, bytes):
await self.send_bytes(data)
else:
raise TypeError("WebSocker send method expects str or bytes!")
@abc.abstractmethod
async def send(self, data: str) -> None:
async def send_text(self, data: str) -> None:
"""发送一条 WebSocket text 信息"""
raise NotImplementedError
@@ -246,8 +262,8 @@ class Cookies(MutableMapping):
self,
name: str,
default: Optional[str] = None,
domain: str = None,
path: str = None,
domain: Optional[str] = None,
path: Optional[str] = None,
) -> Optional[str]:
value: Optional[str] = None
for cookie in self.jar:
@@ -315,3 +331,22 @@ class Cookies(MutableMapping):
)
return f"<Cookies [{cookies_repr}]>"
@dataclass
class HTTPServerSetup:
"""HTTP 服务器路由配置。"""
path: URL # path should not be absolute, check it by URL.is_absolute() == False
method: str
name: str
handle_func: Callable[[Request], Awaitable[Response]]
@dataclass
class WebSocketServerSetup:
"""WebSocket 服务器路由配置。"""
path: URL # path should not be absolute, check it by URL.is_absolute() == False
name: str
handle_func: Callable[[WebSocket], Awaitable[Any]]

721
nonebot/internal/matcher.py Normal file
View File

@@ -0,0 +1,721 @@
from types import ModuleType
from datetime import datetime
from contextvars import ContextVar
from collections import defaultdict
from contextlib import AsyncExitStack
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Union,
TypeVar,
Callable,
NoReturn,
Optional,
)
from nonebot.log import logger
from nonebot.dependencies import Dependent
from nonebot.consts import (
ARG_KEY,
RECEIVE_KEY,
REJECT_TARGET,
LAST_RECEIVE_KEY,
REJECT_CACHE_TARGET,
)
from nonebot.typing import (
Any,
T_State,
T_Handler,
T_TypeUpdater,
T_DependencyCache,
T_PermissionUpdater,
)
from nonebot.exception import (
TypeMisMatch,
PausedException,
StopPropagation,
SkippedException,
FinishedException,
RejectedException,
)
from .rule import Rule
from .permission import USER, Permission
from .adapter import Bot, Event, Message, MessageSegment, MessageTemplate
from .params import (
Depends,
ArgParam,
BotParam,
EventParam,
StateParam,
DependParam,
DefaultParam,
MatcherParam,
)
if TYPE_CHECKING:
from nonebot.plugin import Plugin
T = TypeVar("T")
matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
"""用于存储当前所有的事件响应器"""
current_bot: ContextVar[Bot] = ContextVar("current_bot")
current_event: ContextVar[Event] = ContextVar("current_event")
current_matcher: ContextVar["Matcher"] = ContextVar("current_matcher")
current_handler: ContextVar[Dependent] = ContextVar("current_handler")
class MatcherMeta(type):
if TYPE_CHECKING:
module: Optional[str]
plugin_name: Optional[str]
module_name: Optional[str]
module_prefix: Optional[str]
type: str
rule: Rule
permission: Permission
handlers: List[T_Handler]
priority: int
block: bool
temp: bool
expire_time: Optional[datetime]
def __repr__(self) -> str:
return (
f"<Matcher from {self.module_name or 'unknown'}, "
f"type={self.type}, priority={self.priority}, "
f"temp={self.temp}>"
)
def __str__(self) -> str:
return repr(self)
class Matcher(metaclass=MatcherMeta):
"""事件响应器类"""
plugin: Optional["Plugin"] = None
"""事件响应器所在插件"""
module: Optional[ModuleType] = None
"""事件响应器所在插件模块"""
plugin_name: Optional[str] = None
"""事件响应器所在插件名"""
module_name: Optional[str] = None
"""事件响应器所在点分割插件模块路径"""
type: str = ""
"""事件响应器类型"""
rule: Rule = Rule()
"""事件响应器匹配规则"""
permission: Permission = Permission()
"""事件响应器触发权限"""
handlers: List[Dependent[Any]] = []
"""事件响应器拥有的事件处理函数列表"""
priority: int = 1
"""事件响应器优先级"""
block: bool = False
"""事件响应器是否阻止事件传播"""
temp: bool = False
"""事件响应器是否为临时"""
expire_time: Optional[datetime] = None
"""事件响应器过期时间点"""
_default_state: T_State = {}
"""事件响应器默认状态"""
_default_type_updater: Optional[Dependent[str]] = None
"""事件响应器类型更新函数"""
_default_permission_updater: Optional[Dependent[Permission]] = None
"""事件响应器权限更新函数"""
HANDLER_PARAM_TYPES = [
DependParam,
BotParam,
EventParam,
StateParam,
ArgParam,
MatcherParam,
DefaultParam,
]
def __init__(self):
self.handlers = self.handlers.copy()
self.state = self._default_state.copy()
def __repr__(self) -> str:
return (
f"<Matcher from {self.module_name or 'unknown'}, type={self.type}, "
f"priority={self.priority}, temp={self.temp}>"
)
def __str__(self) -> str:
return repr(self)
@classmethod
def new(
cls,
type_: str = "",
rule: Optional[Rule] = None,
permission: Optional[Permission] = None,
handlers: Optional[List[Union[T_Handler, Dependent[Any]]]] = None,
temp: bool = False,
priority: int = 1,
block: bool = False,
*,
plugin: Optional["Plugin"] = None,
module: Optional[ModuleType] = None,
expire_time: Optional[datetime] = None,
default_state: Optional[T_State] = None,
default_type_updater: Optional[Union[T_TypeUpdater, Dependent[str]]] = None,
default_permission_updater: Optional[
Union[T_PermissionUpdater, Dependent[Permission]]
] = None,
) -> Type["Matcher"]:
"""
创建一个新的事件响应器,并存储至 `matchers <#matchers>`_
参数:
type_: 事件响应器类型,与 `event.get_type()` 一致时触发,空字符串表示任意
rule: 匹配规则
permission: 权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器,即触发一次后删除
priority: 响应优先级
block: 是否阻止事件向更低优先级的响应器传播
plugin: 事件响应器所在插件
module: 事件响应器所在模块
default_state: 默认状态 `state`
expire_time: 事件响应器最终有效时间点,过时即被删除
返回:
Type[Matcher]: 新的事件响应器类
"""
NewMatcher = type(
"Matcher",
(Matcher,),
{
"plugin": plugin,
"module": module,
"plugin_name": plugin and plugin.name,
"module_name": module and module.__name__,
"type": type_,
"rule": rule or Rule(),
"permission": permission or Permission(),
"handlers": [
handler
if isinstance(handler, Dependent)
else Dependent[Any].parse(
call=handler, allow_types=cls.HANDLER_PARAM_TYPES
)
for handler in handlers
]
if handlers
else [],
"temp": temp,
"expire_time": expire_time,
"priority": priority,
"block": block,
"_default_state": default_state or {},
"_default_type_updater": (
default_type_updater
if isinstance(default_type_updater, Dependent)
else default_type_updater
and Dependent[str].parse(
call=default_type_updater, allow_types=cls.HANDLER_PARAM_TYPES
)
),
"_default_permission_updater": (
default_permission_updater
if isinstance(default_permission_updater, Dependent)
else default_permission_updater
and Dependent[Permission].parse(
call=default_permission_updater,
allow_types=cls.HANDLER_PARAM_TYPES,
)
),
},
)
logger.trace(f"Define new matcher {NewMatcher}")
matchers[priority].append(NewMatcher)
return NewMatcher
@classmethod
async def check_perm(
cls,
bot: Bot,
event: Event,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""检查是否满足触发权限
参数:
bot: Bot 对象
event: 上报事件
stack: 异步上下文栈
dependency_cache: 依赖缓存
返回:
是否满足权限
"""
event_type = event.get_type()
return event_type == (cls.type or event_type) and await cls.permission(
bot, event, stack, dependency_cache
)
@classmethod
async def check_rule(
cls,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""检查是否满足匹配规则
参数:
bot: Bot 对象
event: 上报事件
state: 当前状态
stack: 异步上下文栈
dependency_cache: 依赖缓存
返回:
是否满足匹配规则
"""
event_type = event.get_type()
return event_type == (cls.type or event_type) and await cls.rule(
bot, event, state, stack, dependency_cache
)
@classmethod
def type_updater(cls, func: T_TypeUpdater) -> T_TypeUpdater:
"""装饰一个函数来更改当前事件响应器的默认响应事件类型更新函数
参数:
func: 响应事件类型更新函数
"""
cls._default_type_updater = Dependent[str].parse(
call=func, allow_types=cls.HANDLER_PARAM_TYPES
)
return func
@classmethod
def permission_updater(cls, func: T_PermissionUpdater) -> T_PermissionUpdater:
"""装饰一个函数来更改当前事件响应器的默认会话权限更新函数
参数:
func: 会话权限更新函数
"""
cls._default_permission_updater = Dependent[Permission].parse(
call=func, allow_types=cls.HANDLER_PARAM_TYPES
)
return func
@classmethod
def append_handler(
cls, handler: T_Handler, parameterless: Optional[List[Any]] = None
) -> Dependent[Any]:
handler_ = Dependent[Any].parse(
call=handler,
parameterless=parameterless,
allow_types=cls.HANDLER_PARAM_TYPES,
)
cls.handlers.append(handler_)
return handler_
@classmethod
def handle(
cls, parameterless: Optional[List[Any]] = None
) -> Callable[[T_Handler], T_Handler]:
"""装饰一个函数来向事件响应器直接添加一个处理函数
参数:
parameterless: 非参数类型依赖列表
"""
def _decorator(func: T_Handler) -> T_Handler:
cls.append_handler(func, parameterless=parameterless)
return func
return _decorator
@classmethod
def receive(
cls, id: str = "", parameterless: Optional[List[Any]] = None
) -> Callable[[T_Handler], T_Handler]:
"""装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
参数:
id: 消息 ID
parameterless: 非参数类型依赖列表
"""
async def _receive(event: Event, matcher: "Matcher") -> Union[None, NoReturn]:
matcher.set_target(RECEIVE_KEY.format(id=id))
if matcher.get_target() == RECEIVE_KEY.format(id=id):
matcher.set_receive(id, event)
return
if matcher.get_receive(id, ...) is not ...:
return
await matcher.reject()
_parameterless = [Depends(_receive), *(parameterless or [])]
def _decorator(func: T_Handler) -> T_Handler:
if cls.handlers and cls.handlers[-1].call is func:
func_handler = cls.handlers[-1]
for depend in reversed(_parameterless):
func_handler.prepend_parameterless(depend)
else:
cls.append_handler(func, parameterless=_parameterless)
return func
return _decorator
@classmethod
def got(
cls,
key: str,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
parameterless: Optional[List[Any]] = None,
) -> Callable[[T_Handler], T_Handler]:
"""装饰一个函数来指示 NoneBot 获取一个参数 `key`
当要获取的 `key` 不存在时接收用户新的一条消息再运行该函数,如果 `key` 已存在则直接继续运行
参数:
key: 参数名
prompt: 在参数不存在时向用户发送的消息
parameterless: 非参数类型依赖列表
"""
async def _key_getter(event: Event, matcher: "Matcher"):
matcher.set_target(ARG_KEY.format(key=key))
if matcher.get_target() == ARG_KEY.format(key=key):
matcher.set_arg(key, event.get_message())
return
if matcher.get_arg(key, ...) is not ...:
return
await matcher.reject(prompt)
_parameterless = [
Depends(_key_getter),
*(parameterless or []),
]
def _decorator(func: T_Handler) -> T_Handler:
if cls.handlers and cls.handlers[-1].call is func:
func_handler = cls.handlers[-1]
for depend in reversed(_parameterless):
func_handler.prepend_parameterless(depend)
else:
cls.append_handler(func, parameterless=_parameterless)
return func
return _decorator
@classmethod
async def send(
cls,
message: Union[str, Message, MessageSegment, MessageTemplate],
**kwargs: Any,
) -> Any:
"""发送一条消息给当前交互用户
参数:
message: 消息内容
kwargs: {ref}`nonebot.adapters.Bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
"""
bot = current_bot.get()
event = current_event.get()
state = current_matcher.get().state
if isinstance(message, MessageTemplate):
_message = message.format(**state)
else:
_message = message
return await bot.send(event=event, message=_message, **kwargs)
@classmethod
async def finish(
cls,
message: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""发送一条消息给当前交互用户并结束当前事件响应器
参数:
message: 消息内容
kwargs: {ref}`nonebot.adapters.Bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
"""
if message is not None:
await cls.send(message, **kwargs)
raise FinishedException
@classmethod
async def pause(
cls,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
参数:
prompt: 消息内容
kwargs: {ref}`nonebot.adapters.Bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
"""
if prompt is not None:
await cls.send(prompt, **kwargs)
raise PausedException
@classmethod
async def reject(
cls,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""最近使用 `got` / `receive` 接收的消息不符合预期,
发送一条消息给当前交互用户并将当前事件处理流程中断在当前位置,在接收用户新的一个事件后从头开始执行当前处理函数
参数:
prompt: 消息内容
kwargs: {ref}`nonebot.adapters.Bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
"""
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
async def reject_arg(
cls,
key: str,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""最近使用 `got` 接收的消息不符合预期,
发送一条消息给当前交互用户并将当前事件处理流程中断在当前位置,在接收用户新的一条消息后从头开始执行当前处理函数
参数:
key: 参数名
prompt: 消息内容
kwargs: {ref}`nonebot.adapters.Bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
"""
matcher = current_matcher.get()
matcher.set_target(ARG_KEY.format(key=key))
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
async def reject_receive(
cls,
id: str = "",
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""最近使用 `receive` 接收的消息不符合预期,
发送一条消息给当前交互用户并将当前事件处理流程中断在当前位置,在接收用户新的一个事件后从头开始执行当前处理函数
参数:
id: 消息 id
prompt: 消息内容
kwargs: {ref}`nonebot.adapters.Bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
"""
matcher = current_matcher.get()
matcher.set_target(RECEIVE_KEY.format(id=id))
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
def skip(cls) -> NoReturn:
"""跳过当前事件处理函数,继续下一个处理函数
通常在事件处理函数的依赖中使用。
"""
raise SkippedException
def get_receive(self, id: str, default: T = None) -> Union[Event, T]:
"""获取一个 `receive` 事件
如果没有找到对应的事件,返回 `default` 值
"""
return self.state.get(RECEIVE_KEY.format(id=id), default)
def set_receive(self, id: str, event: Event) -> None:
"""设置一个 `receive` 事件"""
self.state[RECEIVE_KEY.format(id=id)] = event
self.state[LAST_RECEIVE_KEY] = event
def get_last_receive(self, default: T = None) -> Union[Event, T]:
"""获取最近一次 `receive` 事件
如果没有事件,返回 `default` 值
"""
return self.state.get(LAST_RECEIVE_KEY, default)
def get_arg(self, key: str, default: T = None) -> Union[Message, T]:
"""获取一个 `got` 消息
如果没有找到对应的消息,返回 `default` 值
"""
return self.state.get(ARG_KEY.format(key=key), default)
def set_arg(self, key: str, message: Message) -> None:
"""设置一个 `got` 消息"""
self.state[ARG_KEY.format(key=key)] = message
def set_target(self, target: str, cache: bool = True) -> None:
if cache:
self.state[REJECT_CACHE_TARGET] = target
else:
self.state[REJECT_TARGET] = target
def get_target(self, default: T = None) -> Union[str, T]:
return self.state.get(REJECT_TARGET, default)
def stop_propagation(self):
"""阻止事件传播"""
self.block = True
async def update_type(self, bot: Bot, event: Event) -> str:
updater = self.__class__._default_type_updater
if not updater:
return "message"
return await updater(bot=bot, event=event, state=self.state, matcher=self)
async def update_permission(self, bot: Bot, event: Event) -> Permission:
updater = self.__class__._default_permission_updater
if not updater:
return USER(event.get_session_id(), perm=self.permission)
return await updater(bot=bot, event=event, state=self.state, matcher=self)
async def resolve_reject(self):
handler = current_handler.get()
self.handlers.insert(0, handler)
if REJECT_CACHE_TARGET in self.state:
self.state[REJECT_TARGET] = self.state[REJECT_CACHE_TARGET]
async def simple_run(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
):
logger.trace(
f"Matcher {self} run with incoming args: "
f"bot={bot}, event={event}, state={state}"
)
b_t = current_bot.set(bot)
e_t = current_event.set(event)
m_t = current_matcher.set(self)
try:
# Refresh preprocess state
self.state.update(state)
while self.handlers:
handler = self.handlers.pop(0)
current_handler.set(handler)
logger.debug(f"Running handler {handler}")
try:
await handler(
matcher=self,
bot=bot,
event=event,
state=self.state,
stack=stack,
dependency_cache=dependency_cache,
)
except TypeMisMatch as e:
logger.debug(
f"Handler {handler} param {e.param.name} value {e.value} "
f"mismatch type {e.param._type_display()}, skipped"
)
except SkippedException as e:
logger.debug(f"Handler {handler} skipped")
except StopPropagation:
self.block = True
finally:
logger.info(f"Matcher {self} running complete")
current_bot.reset(b_t)
current_event.reset(e_t)
current_matcher.reset(m_t)
# 运行handlers
async def run(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
):
try:
await self.simple_run(bot, event, state, stack, dependency_cache)
except RejectedException:
await self.resolve_reject()
type_ = await self.update_type(bot, event)
permission = await self.update_permission(bot, event)
Matcher.new(
type_,
Rule(),
permission,
self.handlers,
temp=True,
priority=0,
block=True,
plugin=self.plugin,
module=self.module,
expire_time=datetime.now() + bot.config.session_expire_timeout,
default_state=self.state,
default_type_updater=self.__class__._default_type_updater,
default_permission_updater=self.__class__._default_permission_updater,
)
except PausedException:
type_ = await self.update_type(bot, event)
permission = await self.update_permission(bot, event)
Matcher.new(
type_,
Rule(),
permission,
self.handlers,
temp=True,
priority=0,
block=True,
plugin=self.plugin,
module=self.module,
expire_time=datetime.now() + bot.config.session_expire_timeout,
default_state=self.state,
default_type_updater=self.__class__._default_type_updater,
default_permission_updater=self.__class__._default_permission_updater,
)
except FinishedException:
pass
__autodoc__ = {
"MatcherMeta": False,
"Matcher.get_target": False,
"Matcher.set_target": False,
"Matcher.update_type": False,
"Matcher.update_permission": False,
"Matcher.resolve_reject": False,
"Matcher.simple_run": False,
}

378
nonebot/internal/params.py Normal file
View File

@@ -0,0 +1,378 @@
import asyncio
import inspect
import warnings
from typing_extensions import Literal
from typing import TYPE_CHECKING, Any, Callable, Optional, cast
from contextlib import AsyncExitStack, contextmanager, asynccontextmanager
from pydantic.fields import Required, Undefined, ModelField
from nonebot.log import logger
from nonebot.exception import TypeMisMatch
from nonebot.dependencies.utils import check_field_type
from nonebot.dependencies import Param, Dependent, CustomConfig
from nonebot.typing import T_State, T_Handler, T_DependencyCache
from nonebot.utils import (
get_name,
run_sync,
is_gen_callable,
run_sync_ctx_manager,
is_async_gen_callable,
is_coroutine_callable,
generic_check_issubclass,
)
if TYPE_CHECKING:
from nonebot.matcher import Matcher
from nonebot.adapters import Bot, Event
class DependsInner:
def __init__(
self,
dependency: Optional[T_Handler] = None,
*,
use_cache: bool = True,
) -> None:
self.dependency = dependency
self.use_cache = use_cache
def __repr__(self) -> str:
dep = get_name(self.dependency)
cache = "" if self.use_cache else ", use_cache=False"
return f"{self.__class__.__name__}({dep}{cache})"
def Depends(
dependency: Optional[T_Handler] = None,
*,
use_cache: bool = True,
) -> Any:
"""子依赖装饰器
参数:
dependency: 依赖函数。默认为参数的类型注释。
use_cache: 是否使用缓存。默认为 `True`。
用法:
```python
def depend_func() -> Any:
return ...
def depend_gen_func():
try:
yield ...
finally:
...
async def handler(param_name: Any = Depends(depend_func), gen: Any = Depends(depend_gen_func)):
...
```
"""
return DependsInner(dependency, use_cache=use_cache)
class DependParam(Param):
"""子依赖参数"""
@classmethod
def _check_param(
cls,
dependent: Dependent,
name: str,
param: inspect.Parameter,
) -> Optional["DependParam"]:
if isinstance(param.default, DependsInner):
dependency: T_Handler
if param.default.dependency is None:
assert param.annotation is not param.empty, "Dependency cannot be empty"
dependency = param.annotation
else:
dependency = param.default.dependency
sub_dependent = Dependent[Any].parse(
call=dependency,
allow_types=dependent.allow_types,
)
dependent.pre_checkers.extend(sub_dependent.pre_checkers)
sub_dependent.pre_checkers.clear()
return cls(
Required, use_cache=param.default.use_cache, dependent=sub_dependent
)
@classmethod
def _check_parameterless(
cls, dependent: "Dependent", value: Any
) -> Optional["Param"]:
if isinstance(value, DependsInner):
assert value.dependency, "Dependency cannot be empty"
dependent = Dependent[Any].parse(
call=value.dependency, allow_types=dependent.allow_types
)
return cls(Required, use_cache=value.use_cache, dependent=dependent)
async def _solve(
self,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
**kwargs: Any,
) -> Any:
use_cache: bool = self.extra["use_cache"]
dependency_cache = {} if dependency_cache is None else dependency_cache
sub_dependent: Dependent = self.extra["dependent"]
sub_dependent.call = cast(Callable[..., Any], sub_dependent.call)
call = sub_dependent.call
# solve sub dependency with current cache
sub_values = await sub_dependent.solve(
stack=stack,
dependency_cache=dependency_cache,
**kwargs,
)
# run dependency function
task: asyncio.Task[Any]
if use_cache and call in dependency_cache:
solved = await dependency_cache[call]
elif is_gen_callable(call) or is_async_gen_callable(call):
assert isinstance(
stack, AsyncExitStack
), "Generator dependency should be called in context"
if is_gen_callable(call):
cm = run_sync_ctx_manager(contextmanager(call)(**sub_values))
else:
cm = asynccontextmanager(call)(**sub_values)
task = asyncio.create_task(stack.enter_async_context(cm))
dependency_cache[call] = task
solved = await task
elif is_coroutine_callable(call):
task = asyncio.create_task(call(**sub_values))
dependency_cache[call] = task
solved = await task
else:
task = asyncio.create_task(run_sync(call)(**sub_values))
dependency_cache[call] = task
solved = await task
return solved
class _BotChecker(Param):
async def _solve(self, bot: "Bot", **kwargs: Any) -> Any:
field: ModelField = self.extra["field"]
try:
return check_field_type(field, bot)
except TypeMisMatch:
logger.debug(
f"Bot type {type(bot)} not match "
f"annotation {field._type_display()}, ignored"
)
raise
class BotParam(Param):
"""{ref}`nonebot.adapters.Bot` 参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["BotParam"]:
from nonebot.adapters import Bot
if param.default == param.empty:
if generic_check_issubclass(param.annotation, Bot):
if param.annotation is not Bot:
dependent.pre_checkers.append(
_BotChecker(
Required,
field=ModelField(
name=name,
type_=param.annotation,
class_validators=None,
model_config=CustomConfig,
default=None,
required=True,
),
)
)
return cls(Required)
elif param.annotation == param.empty and name == "bot":
return cls(Required)
async def _solve(self, bot: "Bot", **kwargs: Any) -> Any:
return bot
class _EventChecker(Param):
async def _solve(self, event: "Event", **kwargs: Any) -> Any:
field: ModelField = self.extra["field"]
try:
return check_field_type(field, event)
except TypeMisMatch:
logger.debug(
f"Event type {type(event)} not match "
f"annotation {field._type_display()}, ignored"
)
raise
class EventParam(Param):
"""{ref}`nonebot.adapters.Event` 参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["EventParam"]:
from nonebot.adapters import Event
if param.default == param.empty:
if generic_check_issubclass(param.annotation, Event):
if param.annotation is not Event:
dependent.pre_checkers.append(
_EventChecker(
Required,
field=ModelField(
name=name,
type_=param.annotation,
class_validators=None,
model_config=CustomConfig,
default=None,
required=True,
),
)
)
return cls(Required)
elif param.annotation == param.empty and name == "event":
return cls(Required)
async def _solve(self, event: "Event", **kwargs: Any) -> Any:
return event
class StateInner(T_State):
...
def State() -> T_State:
"""**Deprecated**: 事件处理状态参数,请直接使用 {ref}`nonebot.typing.T_State`"""
warnings.warn("State() is deprecated, use `T_State` instead", DeprecationWarning)
return StateInner()
class StateParam(Param):
"""事件处理状态参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["StateParam"]:
if isinstance(param.default, StateInner):
return cls(Required)
elif param.default == param.empty:
if param.annotation is T_State:
return cls(Required)
elif param.annotation == param.empty and name == "state":
return cls(Required)
async def _solve(self, state: T_State, **kwargs: Any) -> Any:
return state
class MatcherParam(Param):
"""事件响应器实例参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["MatcherParam"]:
from nonebot.matcher import Matcher
if generic_check_issubclass(param.annotation, Matcher) or (
param.annotation == param.empty and name == "matcher"
):
return cls(Required)
async def _solve(self, matcher: "Matcher", **kwargs: Any) -> Any:
return matcher
class ArgInner:
def __init__(
self, key: Optional[str], type: Literal["message", "str", "plaintext"]
) -> None:
self.key = key
self.type = type
def Arg(key: Optional[str] = None) -> Any:
"""`got` 的 Arg 参数消息"""
return ArgInner(key, "message")
def ArgStr(key: Optional[str] = None) -> str:
"""`got` 的 Arg 参数消息文本"""
return ArgInner(key, "str") # type: ignore
def ArgPlainText(key: Optional[str] = None) -> str:
"""`got` 的 Arg 参数消息纯文本"""
return ArgInner(key, "plaintext") # type: ignore
class ArgParam(Param):
"""`got` 的 Arg 参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["ArgParam"]:
if isinstance(param.default, ArgInner):
return cls(Required, key=param.default.key or name, type=param.default.type)
async def _solve(self, matcher: "Matcher", **kwargs: Any) -> Any:
message = matcher.get_arg(self.extra["key"])
if message is None:
return message
if self.extra["type"] == "message":
return message
elif self.extra["type"] == "str":
return str(message)
else:
return message.extract_plain_text()
class ExceptionParam(Param):
"""`run_postprocessor` 的异常参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["ExceptionParam"]:
if generic_check_issubclass(param.annotation, Exception) or (
param.annotation == param.empty and name == "exception"
):
return cls(Required)
async def _solve(self, exception: Optional[Exception] = None, **kwargs: Any) -> Any:
return exception
class DefaultParam(Param):
"""默认值参数"""
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["DefaultParam"]:
if param.default != param.empty:
return cls(param.default)
async def _solve(self, **kwargs: Any) -> Any:
return Undefined
__autodoc__ = {
"DependsInner": False,
"StateInner": False,
"ArgInner": False,
}

View File

@@ -0,0 +1,139 @@
import asyncio
from contextlib import AsyncExitStack
from typing import Any, Set, Tuple, Union, NoReturn, Optional, Coroutine
from nonebot.dependencies import Dependent
from nonebot.utils import run_coro_with_catch
from nonebot.exception import SkippedException
from nonebot.typing import T_DependencyCache, T_PermissionChecker
from .adapter import Bot, Event
from .params import BotParam, EventParam, DependParam, DefaultParam
class Permission:
"""{ref}`nonebot.matcher.Matcher` 权限类。
当事件传递时,在 {ref}`nonebot.matcher.Matcher` 运行前进行检查。
参数:
checkers: PermissionChecker
用法:
```python
Permission(async_function) | sync_function
# 等价于
Permission(async_function, sync_function)
```
"""
__slots__ = ("checkers",)
HANDLER_PARAM_TYPES = [
DependParam,
BotParam,
EventParam,
DefaultParam,
]
def __init__(self, *checkers: Union[T_PermissionChecker, Dependent[bool]]) -> None:
self.checkers: Set[Dependent[bool]] = set(
checker
if isinstance(checker, Dependent)
else Dependent[bool].parse(
call=checker, allow_types=self.HANDLER_PARAM_TYPES
)
for checker in checkers
)
"""存储 `PermissionChecker`"""
async def __call__(
self,
bot: Bot,
event: Event,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""检查是否满足某个权限
参数:
bot: Bot 对象
event: Event 对象
stack: 异步上下文栈
dependency_cache: 依赖缓存
"""
if not self.checkers:
return True
results = await asyncio.gather(
*(
run_coro_with_catch(
checker(
bot=bot,
event=event,
stack=stack,
dependency_cache=dependency_cache,
),
(SkippedException,),
False,
)
for checker in self.checkers
),
)
return any(results)
def __and__(self, other: object) -> NoReturn:
raise RuntimeError("And operation between Permissions is not allowed.")
def __or__(
self, other: Optional[Union["Permission", T_PermissionChecker]]
) -> "Permission":
if other is None:
return self
elif isinstance(other, Permission):
return Permission(*self.checkers, *other.checkers)
else:
return Permission(*self.checkers, other)
def __ror__(
self, other: Optional[Union["Permission", T_PermissionChecker]]
) -> "Permission":
if other is None:
return self
elif isinstance(other, Permission):
return Permission(*other.checkers, *self.checkers)
else:
return Permission(other, *self.checkers)
class User:
"""检查当前事件是否属于指定会话
参数:
users: 会话 ID 元组
perm: 需同时满足的权限
"""
__slots__ = ("users", "perm")
def __init__(
self, users: Tuple[str, ...], perm: Optional[Permission] = None
) -> None:
self.users = users
self.perm = perm
async def __call__(self, bot: Bot, event: Event) -> bool:
return bool(
event.get_session_id() in self.users
and (self.perm is None or await self.perm(bot, event))
)
def USER(*users: str, perm: Optional[Permission] = None):
"""匹配当前事件属于指定会话
参数:
user: 会话白名单
perm: 需要同时满足的权限
"""
return Permission(User(users, perm))

103
nonebot/internal/rule.py Normal file
View File

@@ -0,0 +1,103 @@
import asyncio
from contextlib import AsyncExitStack
from typing import Set, Union, NoReturn, Optional
from nonebot.dependencies import Dependent
from nonebot.exception import SkippedException
from nonebot.typing import T_State, T_RuleChecker, T_DependencyCache
from .adapter import Bot, Event
from .params import BotParam, EventParam, StateParam, DependParam, DefaultParam
class Rule:
"""{ref}`nonebot.matcher.Matcher` 规则类。
当事件传递时,在 {ref}`nonebot.matcher.Matcher` 运行前进行检查。
参数:
*checkers: RuleChecker
用法:
```python
Rule(async_function) & sync_function
# 等价于
Rule(async_function, sync_function)
```
"""
__slots__ = ("checkers",)
HANDLER_PARAM_TYPES = [
DependParam,
BotParam,
EventParam,
StateParam,
DefaultParam,
]
def __init__(self, *checkers: Union[T_RuleChecker, Dependent[bool]]) -> None:
self.checkers: Set[Dependent[bool]] = set(
checker
if isinstance(checker, Dependent)
else Dependent[bool].parse(
call=checker, allow_types=self.HANDLER_PARAM_TYPES
)
for checker in checkers
)
"""存储 `RuleChecker`"""
async def __call__(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""检查是否符合所有规则
参数:
bot: Bot 对象
event: Event 对象
state: 当前 State
stack: 异步上下文栈
dependency_cache: 依赖缓存
"""
if not self.checkers:
return True
try:
results = await asyncio.gather(
*(
checker(
bot=bot,
event=event,
state=state,
stack=stack,
dependency_cache=dependency_cache,
)
for checker in self.checkers
)
)
except SkippedException:
return False
return all(results)
def __and__(self, other: Optional[Union["Rule", T_RuleChecker]]) -> "Rule":
if other is None:
return self
elif isinstance(other, Rule):
return Rule(*self.checkers, *other.checkers)
else:
return Rule(*self.checkers, other)
def __rand__(self, other: Optional[Union["Rule", T_RuleChecker]]) -> "Rule":
if other is None:
return self
elif isinstance(other, Rule):
return Rule(*other.checkers, *self.checkers)
else:
return Rule(other, *self.checkers)
def __or__(self, other: object) -> NoReturn:
raise RuntimeError("Or operation between rules is not allowed.")

View File

@@ -1,13 +1,15 @@
"""
日志
====
"""本模块定义了 NoneBot 的日志记录 Logger。
NoneBot 使用 `loguru`_ 来记录日志信息。
NoneBot 使用 [`loguru`][loguru] 来记录日志信息。
自定义 logger 请参考 `loguru`_ 文档。
自定义 logger 请参考 [自定义日志](https://v2.nonebot.dev/docs/tutorial/custom-logger)
以及 [`loguru`][loguru] 文档。
.. _loguru:
https://github.com/Delgan/loguru
[loguru]: https://github.com/Delgan/loguru
FrontMatter:
sidebar_position: 7
description: nonebot.log 模块
"""
import sys
@@ -21,24 +23,22 @@ if TYPE_CHECKING:
# because loguru module do not have `Logger` class actually
from loguru import Logger
from nonebot.plugin import Plugin
# logger = logging.getLogger("nonebot")
logger: "Logger" = loguru.logger
"""
:说明:
"""NoneBot 日志记录器对象。
NoneBot 日志记录器对象。
默认信息:
:默认信息:
* 格式: ``[%(asctime)s %(name)s] %(levelname)s: %(message)s``
* 等级: ``INFO`` ,根据 ``config.log_level`` 配置改变
* 输出: 输出至 stdout
:用法:
.. code-block:: python
- 格式: `[%(asctime)s %(name)s] %(levelname)s: %(message)s`
- 等级: `INFO` ,根据 `config.log_level` 配置改变
- 输出: 输出至 stdout
用法:
```python
from nonebot.log import logger
```
"""
# default_handler = logging.StreamHandler(sys.stdout)
@@ -53,9 +53,11 @@ class Filter:
def __call__(self, record):
module_name: str = record["name"]
module = sys.modules.get(module_name)
if module:
module_name = getattr(module, "__module_name__", module_name)
# TODO: get plugin name instead of module name
# module = sys.modules.get(module_name)
# if module and hasattr(module, "__plugin__"):
# plugin: "Plugin" = getattr(module, "__plugin__")
# module_name = plugin.module_name
record["name"] = module_name.split(".")[0]
levelno = (
logger.level(self.level).no if isinstance(self.level, str) else self.level
@@ -81,19 +83,22 @@ class LoguruHandler(logging.Handler): # pragma: no cover
logger.remove()
default_filter = Filter()
default_format = (
default_filter: Filter = Filter()
"""默认日志等级过滤器"""
default_format: str = (
"<g>{time:MM-DD HH:mm:ss}</g> "
"[<lvl>{level}</lvl>] "
"<c><u>{name}</u></c> | "
# "<c>{function}:{line}</c>| "
"{message}"
)
"""默认日志格式"""
logger_id = logger.add(
sys.stdout,
level=0,
colorize=True,
diagnose=False,
filter=default_filter,
format=default_format,
)
__autodoc__ = {"Filter": False, "LoguruHandler": False}

View File

@@ -1,784 +1,18 @@
"""
事件响应器
==========
"""本模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行对话。
该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行对话 。
FrontMatter:
sidebar_position: 3
description: nonebot.matcher 模块
"""
from types import ModuleType
from datetime import datetime
from contextvars import ContextVar
from collections import defaultdict
from contextlib import AsyncExitStack
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Union,
TypeVar,
Callable,
NoReturn,
Optional,
)
from nonebot import params
from nonebot.rule import Rule
from nonebot.log import logger
from nonebot.dependencies import Dependent
from nonebot.permission import USER, Permission
from nonebot.adapters import (
Bot,
Event,
Message,
MessageSegment,
MessageTemplate,
)
from nonebot.consts import (
ARG_KEY,
RECEIVE_KEY,
REJECT_TARGET,
LAST_RECEIVE_KEY,
REJECT_CACHE_TARGET,
)
from nonebot.typing import (
Any,
T_State,
T_Handler,
T_TypeUpdater,
T_DependencyCache,
T_PermissionUpdater,
)
from nonebot.exception import (
TypeMisMatch,
PausedException,
StopPropagation,
SkippedException,
FinishedException,
RejectedException,
)
if TYPE_CHECKING:
from nonebot.plugin import Plugin
T = TypeVar("T")
matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
"""
:类型: ``Dict[int, List[Type[Matcher]]]``
:说明: 用于存储当前所有的事件响应器
"""
current_bot: ContextVar[Bot] = ContextVar("current_bot")
current_event: ContextVar[Event] = ContextVar("current_event")
current_matcher: ContextVar["Matcher"] = ContextVar("current_matcher")
current_handler: ContextVar[Dependent] = ContextVar("current_handler")
class MatcherMeta(type):
if TYPE_CHECKING:
module: Optional[str]
plugin_name: Optional[str]
module_name: Optional[str]
module_prefix: Optional[str]
type: str
rule: Rule
permission: Permission
handlers: List[T_Handler]
priority: int
block: bool
temp: bool
expire_time: Optional[datetime]
def __repr__(self) -> str:
return (
f"<Matcher from {self.module_name or 'unknown'}, "
f"type={self.type}, priority={self.priority}, "
f"temp={self.temp}>"
)
def __str__(self) -> str:
return repr(self)
class Matcher(metaclass=MatcherMeta):
"""事件响应器类"""
plugin: Optional["Plugin"] = None
"""
:类型: ``Optional[Plugin]``
:说明: 事件响应器所在插件
"""
module: Optional[ModuleType] = None
"""
:类型: ``Optional[ModuleType]``
:说明: 事件响应器所在插件模块
"""
plugin_name: Optional[str] = None
"""
:类型: ``Optional[str]``
:说明: 事件响应器所在插件名
"""
module_name: Optional[str] = None
"""
:类型: ``Optional[str]``
:说明: 事件响应器所在点分割插件模块路径
"""
type: str = ""
"""
:类型: ``str``
:说明: 事件响应器类型
"""
rule: Rule = Rule()
"""
:类型: ``Rule``
:说明: 事件响应器匹配规则
"""
permission: Permission = Permission()
"""
:类型: ``Permission``
:说明: 事件响应器触发权限
"""
handlers: List[Dependent[Any]] = []
"""
:类型: ``List[Handler]``
:说明: 事件响应器拥有的事件处理函数列表
"""
priority: int = 1
"""
:类型: ``int``
:说明: 事件响应器优先级
"""
block: bool = False
"""
:类型: ``bool``
:说明: 事件响应器是否阻止事件传播
"""
temp: bool = False
"""
:类型: ``bool``
:说明: 事件响应器是否为临时
"""
expire_time: Optional[datetime] = None
"""
:类型: ``Optional[datetime]``
:说明: 事件响应器过期时间点
"""
_default_state: T_State = {}
"""
:类型: ``T_State``
:说明: 事件响应器默认状态
"""
_default_type_updater: Optional[Dependent[str]] = None
"""
:类型: ``Optional[Dependent]``
:说明: 事件响应器类型更新函数
"""
_default_permission_updater: Optional[Dependent[Permission]] = None
"""
:类型: ``Optional[Dependent]``
:说明: 事件响应器权限更新函数
"""
HANDLER_PARAM_TYPES = [
params.DependParam,
params.BotParam,
params.EventParam,
params.StateParam,
params.ArgParam,
params.MatcherParam,
params.DefaultParam,
]
def __init__(self):
"""实例化 Matcher 以便运行"""
self.handlers = self.handlers.copy()
self.state = self._default_state.copy()
def __repr__(self) -> str:
return (
f"<Matcher from {self.module_name or 'unknown'}, type={self.type}, "
f"priority={self.priority}, temp={self.temp}>"
)
def __str__(self) -> str:
return repr(self)
@classmethod
def new(
cls,
type_: str = "",
rule: Optional[Rule] = None,
permission: Optional[Permission] = None,
handlers: Optional[List[Union[T_Handler, Dependent[Any]]]] = None,
temp: bool = False,
priority: int = 1,
block: bool = False,
*,
plugin: Optional["Plugin"] = None,
module: Optional[ModuleType] = None,
expire_time: Optional[datetime] = None,
default_state: Optional[T_State] = None,
default_type_updater: Optional[T_TypeUpdater] = None,
default_permission_updater: Optional[T_PermissionUpdater] = None,
) -> Type["Matcher"]:
"""
:说明:
创建一个新的事件响应器,并存储至 `matchers <#matchers>`_
:参数:
* ``type_: str``: 事件响应器类型,与 ``event.get_type()`` 一致时触发,空字符串表示任意
* ``rule: Optional[Rule]``: 匹配规则
* ``permission: Optional[Permission]``: 权限
* ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器,即触发一次后删除
* ``priority: int``: 响应优先级
* ``block: bool``: 是否阻止事件向更低优先级的响应器传播
* ``plugin: Optional[Plugin]``: 事件响应器所在插件
* ``module: Optional[ModuleType]``: 事件响应器所在模块
* ``default_state: Optional[T_State]``: 默认状态 ``state``
* ``expire_time: Optional[datetime]``: 事件响应器最终有效时间点,过时即被删除
:返回:
- ``Type[Matcher]``: 新的事件响应器类
"""
NewMatcher = type(
"Matcher",
(Matcher,),
{
"plugin": plugin,
"module": module,
"plugin_name": plugin and plugin.name,
"module_name": module and module.__name__,
"type": type_,
"rule": rule or Rule(),
"permission": permission or Permission(),
"handlers": [
handler
if isinstance(handler, Dependent)
else Dependent[Any].parse(
call=handler, allow_types=cls.HANDLER_PARAM_TYPES
)
for handler in handlers
]
if handlers
else [],
"temp": temp,
"expire_time": expire_time,
"priority": priority,
"block": block,
"_default_state": default_state or {},
"_default_type_updater": default_type_updater,
"_default_permission_updater": default_permission_updater,
},
)
logger.trace(f"Define new matcher {NewMatcher}")
matchers[priority].append(NewMatcher)
return NewMatcher
@classmethod
async def check_perm(
cls,
bot: Bot,
event: Event,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""
:说明:
检查是否满足触发权限
:参数:
* ``bot: Bot``: Bot 对象
* ``event: Event``: 上报事件
:返回:
- ``bool``: 是否满足权限
"""
event_type = event.get_type()
return event_type == (cls.type or event_type) and await cls.permission(
bot, event, stack, dependency_cache
)
@classmethod
async def check_rule(
cls,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""
:说明:
检查是否满足匹配规则
:参数:
* ``bot: Bot``: Bot 对象
* ``event: Event``: 上报事件
* ``state: T_State``: 当前状态
:返回:
- ``bool``: 是否满足匹配规则
"""
event_type = event.get_type()
return event_type == (cls.type or event_type) and await cls.rule(
bot, event, state, stack, dependency_cache
)
@classmethod
def type_updater(cls, func: T_TypeUpdater) -> T_TypeUpdater:
"""
:说明:
装饰一个函数来更改当前事件响应器的默认响应事件类型更新函数
:参数:
* ``func: T_TypeUpdater``: 响应事件类型更新函数
"""
cls._default_type_updater = Dependent[str].parse(
call=func, allow_types=cls.HANDLER_PARAM_TYPES
)
return func
@classmethod
def permission_updater(cls, func: T_PermissionUpdater) -> T_PermissionUpdater:
"""
:说明:
装饰一个函数来更改当前事件响应器的默认会话权限更新函数
:参数:
* ``func: T_PermissionUpdater``: 会话权限更新函数
"""
cls._default_permission_updater = Dependent[Permission].parse(
call=func, allow_types=cls.HANDLER_PARAM_TYPES
)
return func
@classmethod
def append_handler(
cls, handler: T_Handler, parameterless: Optional[List[Any]] = None
) -> Dependent[Any]:
handler_ = Dependent[Any].parse(
call=handler,
parameterless=parameterless,
allow_types=cls.HANDLER_PARAM_TYPES,
)
cls.handlers.append(handler_)
return handler_
@classmethod
def handle(
cls, parameterless: Optional[List[Any]] = None
) -> Callable[[T_Handler], T_Handler]:
"""
:说明:
装饰一个函数来向事件响应器直接添加一个处理函数
:参数:
* ``parameterless: Optional[List[Any]]``: 非参数类型依赖列表
"""
def _decorator(func: T_Handler) -> T_Handler:
cls.append_handler(func, parameterless=parameterless)
return func
return _decorator
@classmethod
def receive(
cls, id: str = "", parameterless: Optional[List[Any]] = None
) -> Callable[[T_Handler], T_Handler]:
"""
:说明:
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
:参数:
* ``id: str``: 消息 ID
* ``parameterless: Optional[List[Any]]``: 非参数类型依赖列表
"""
async def _receive(event: Event, matcher: "Matcher") -> Union[None, NoReturn]:
matcher.set_target(RECEIVE_KEY.format(id=id))
if matcher.get_target() == RECEIVE_KEY.format(id=id):
matcher.set_receive(id, event)
return
if matcher.get_receive(id):
return
await matcher.reject()
_parameterless = [params.Depends(_receive), *(parameterless or [])]
def _decorator(func: T_Handler) -> T_Handler:
if cls.handlers and cls.handlers[-1].call is func:
func_handler = cls.handlers[-1]
for depend in reversed(_parameterless):
func_handler.prepend_parameterless(depend)
else:
cls.append_handler(func, parameterless=_parameterless)
return func
return _decorator
@classmethod
def got(
cls,
key: str,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
parameterless: Optional[List[Any]] = None,
) -> Callable[[T_Handler], T_Handler]:
"""
:说明:
装饰一个函数来指示 NoneBot 当要获取的 ``key`` 不存在时接收用户新的一条消息并经过 ``ArgsParser`` 处理后再运行该函数,如果 ``key`` 已存在则直接继续运行
:参数:
* ``key: str``: 参数名
* ``prompt: Optional[Union[str, Message, MessageSegment, MessageFormatter]]``: 在参数不存在时向用户发送的消息
* ``args_parser: Optional[T_ArgsParser]``: 可选参数解析函数,空则使用默认解析函数
* ``parameterless: Optional[List[Any]]``: 非参数类型依赖列表
"""
async def _key_getter(event: Event, matcher: "Matcher"):
matcher.set_target(ARG_KEY.format(key=key))
if matcher.get_target() == ARG_KEY.format(key=key):
matcher.set_arg(key, event.get_message())
return
if matcher.get_arg(key):
return
await matcher.reject(prompt)
_parameterless = [
params.Depends(_key_getter),
*(parameterless or []),
]
def _decorator(func: T_Handler) -> T_Handler:
if cls.handlers and cls.handlers[-1].call is func:
func_handler = cls.handlers[-1]
for depend in reversed(_parameterless):
func_handler.prepend_parameterless(depend)
else:
cls.append_handler(func, parameterless=_parameterless)
return func
return _decorator
@classmethod
async def send(
cls,
message: Union[str, Message, MessageSegment, MessageTemplate],
**kwargs: Any,
) -> Any:
"""
:说明:
发送一条消息给当前交互用户
:参数:
* ``message: Union[str, Message, MessageSegment]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api
"""
bot = current_bot.get()
event = current_event.get()
state = current_matcher.get().state
if isinstance(message, MessageTemplate):
_message = message.format(**state)
else:
_message = message
return await bot.send(event=event, message=_message, **kwargs)
@classmethod
async def finish(
cls,
message: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""
:说明:
发送一条消息给当前交互用户并结束当前事件响应器
:参数:
* ``message: Union[str, Message, MessageSegment, MessageTemplate]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api
"""
if message is not None:
await cls.send(message, **kwargs)
raise FinishedException
@classmethod
async def pause(
cls,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""
:说明:
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
:参数:
* ``prompt: Union[str, Message, MessageSegment, MessageTemplate]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api
"""
if prompt is not None:
await cls.send(prompt, **kwargs)
raise PausedException
@classmethod
async def reject(
cls,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""
:说明:
最近使用 ``got`` / ``receive`` 接收的消息不符合预期,发送一条消息给当前交互用户并暂停事件响应器,
在接收用户新的一条消息后继续当前处理函数
:参数:
* ``prompt: Union[str, Message, MessageSegment, MessageTemplate]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api
"""
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
async def reject_arg(
cls,
key: str,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""
:说明:
最近使用 ``got`` 接收的消息不符合预期,发送一条消息给当前交互用户并暂停事件响应器,
在接收用户新的一条消息后继续当前处理函数
:参数:
* ``key: str``: 参数名
* ``prompt: Union[str, Message, MessageSegment, MessageTemplate]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api
"""
matcher = current_matcher.get()
matcher.set_target(ARG_KEY.format(key=key))
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
async def reject_receive(
cls,
id: str = "",
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
"""
:说明:
最近使用 ``got`` 接收的消息不符合预期,发送一条消息给当前交互用户并暂停事件响应器,
在接收用户新的一条消息后继续当前处理函数
:参数:
* ``id: str``: 消息 id
* ``prompt: Union[str, Message, MessageSegment, MessageTemplate]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api
"""
matcher = current_matcher.get()
matcher.set_target(RECEIVE_KEY.format(id=id))
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
def skip(cls) -> NoReturn:
raise SkippedException
def get_receive(self, id: str, default: T = None) -> Union[Event, T]:
return self.state.get(RECEIVE_KEY.format(id=id), default)
def set_receive(self, id: str, event: Event) -> None:
self.state[RECEIVE_KEY.format(id=id)] = event
self.state[LAST_RECEIVE_KEY] = event
def get_last_receive(self, default: T = None) -> Union[Event, T]:
return self.state.get(LAST_RECEIVE_KEY, default)
def get_arg(self, key: str, default: T = None) -> Union[Message, T]:
return self.state.get(ARG_KEY.format(key=key), default)
def set_arg(self, key: str, message: Message) -> None:
self.state[ARG_KEY.format(key=key)] = message
def set_target(self, target: str, cache: bool = True) -> None:
if cache:
self.state[REJECT_CACHE_TARGET] = target
else:
self.state[REJECT_TARGET] = target
def get_target(self, default: T = None) -> Union[str, T]:
return self.state.get(REJECT_TARGET, default)
def stop_propagation(self):
"""
:说明:
阻止事件传播
"""
self.block = True
async def update_type(self, bot: Bot, event: Event) -> str:
updater = self.__class__._default_type_updater
if not updater:
return "message"
return await updater(bot=bot, event=event, state=self.state, matcher=self)
async def update_permission(self, bot: Bot, event: Event) -> Permission:
updater = self.__class__._default_permission_updater
if not updater:
return USER(event.get_session_id(), perm=self.permission)
return await updater(bot=bot, event=event, state=self.state, matcher=self)
async def resolve_reject(self):
handler = current_handler.get()
self.handlers.insert(0, handler)
if REJECT_CACHE_TARGET in self.state:
self.state[REJECT_TARGET] = self.state[REJECT_CACHE_TARGET]
async def simple_run(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
):
logger.trace(
f"Matcher {self} run with incoming args: "
f"bot={bot}, event={event}, state={state}"
)
b_t = current_bot.set(bot)
e_t = current_event.set(event)
m_t = current_matcher.set(self)
try:
# Refresh preprocess state
self.state.update(state)
while self.handlers:
handler = self.handlers.pop(0)
current_handler.set(handler)
logger.debug(f"Running handler {handler}")
try:
await handler(
matcher=self,
bot=bot,
event=event,
state=self.state,
stack=stack,
dependency_cache=dependency_cache,
)
except TypeMisMatch as e:
logger.debug(
f"Handler {handler} param {e.param.name} value {e.value} "
f"mismatch type {e.param._type_display()}, skipped"
)
except SkippedException as e:
logger.debug(f"Handler {handler} skipped")
except StopPropagation:
self.block = True
finally:
logger.info(f"Matcher {self} running complete")
current_bot.reset(b_t)
current_event.reset(e_t)
current_matcher.reset(m_t)
# 运行handlers
async def run(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
):
try:
await self.simple_run(bot, event, state, stack, dependency_cache)
except RejectedException:
await self.resolve_reject()
type_ = await self.update_type(bot, event)
permission = await self.update_permission(bot, event)
Matcher.new(
type_,
Rule(),
permission,
self.handlers,
temp=True,
priority=0,
block=True,
plugin=self.plugin,
module=self.module,
expire_time=datetime.now() + bot.config.session_expire_timeout,
default_state=self.state,
default_type_updater=self.__class__._default_type_updater,
default_permission_updater=self.__class__._default_permission_updater,
)
except PausedException:
type_ = await self.update_type(bot, event)
permission = await self.update_permission(bot, event)
Matcher.new(
type_,
Rule(),
permission,
self.handlers,
temp=True,
priority=0,
block=True,
plugin=self.plugin,
module=self.module,
expire_time=datetime.now() + bot.config.session_expire_timeout,
default_state=self.state,
default_type_updater=self.__class__._default_type_updater,
default_permission_updater=self.__class__._default_permission_updater,
)
except FinishedException:
pass
from nonebot.internal.matcher import Matcher as Matcher
from nonebot.internal.matcher import matchers as matchers
from nonebot.internal.matcher import current_bot as current_bot
from nonebot.internal.matcher import current_event as current_event
from nonebot.internal.matcher import current_handler as current_handler
from nonebot.internal.matcher import current_matcher as current_matcher
__autodoc__ = {
"Matcher": True,
"matchers": True,
}

View File

@@ -1,8 +1,10 @@
"""
事件处理
========
"""本模块定义了事件处理主要流程。
NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供了多个插槽以进行事件的预处理等。
FrontMatter:
sidebar_position: 2
description: nonebot.message 模块
"""
import asyncio
@@ -10,12 +12,11 @@ from datetime import datetime
from contextlib import AsyncExitStack
from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional, Coroutine
from nonebot import params
from nonebot.log import logger
from nonebot.rule import TrieRule
from nonebot.utils import escape_tag
from nonebot.dependencies import Dependent
from nonebot.matcher import Matcher, matchers
from nonebot.utils import escape_tag, run_coro_with_catch
from nonebot.exception import (
NoLogException,
StopPropagation,
@@ -30,98 +31,85 @@ from nonebot.typing import (
T_EventPreProcessor,
T_EventPostProcessor,
)
from nonebot.internal.params import (
ArgParam,
BotParam,
EventParam,
StateParam,
DependParam,
DefaultParam,
MatcherParam,
ExceptionParam,
)
if TYPE_CHECKING:
from nonebot.adapters import Bot, Event
_event_preprocessors: Set[Dependent[None]] = set()
_event_postprocessors: Set[Dependent[None]] = set()
_run_preprocessors: Set[Dependent[None]] = set()
_run_postprocessors: Set[Dependent[None]] = set()
_event_preprocessors: Set[Dependent[Any]] = set()
_event_postprocessors: Set[Dependent[Any]] = set()
_run_preprocessors: Set[Dependent[Any]] = set()
_run_postprocessors: Set[Dependent[Any]] = set()
EVENT_PCS_PARAMS = [
params.DependParam,
params.BotParam,
params.EventParam,
params.StateParam,
params.DefaultParam,
DependParam,
BotParam,
EventParam,
StateParam,
DefaultParam,
]
RUN_PREPCS_PARAMS = [
params.DependParam,
params.BotParam,
params.EventParam,
params.StateParam,
params.ArgParam,
params.MatcherParam,
params.DefaultParam,
DependParam,
BotParam,
EventParam,
StateParam,
ArgParam,
MatcherParam,
DefaultParam,
]
RUN_POSTPCS_PARAMS = [
params.DependParam,
params.ExceptionParam,
params.BotParam,
params.EventParam,
params.StateParam,
params.ArgParam,
params.MatcherParam,
params.DefaultParam,
DependParam,
ExceptionParam,
BotParam,
EventParam,
StateParam,
ArgParam,
MatcherParam,
DefaultParam,
]
def event_preprocessor(func: T_EventPreProcessor) -> T_EventPreProcessor:
"""
:说明:
事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。
"""
"""事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。"""
_event_preprocessors.add(
Dependent[None].parse(call=func, allow_types=EVENT_PCS_PARAMS)
Dependent[Any].parse(call=func, allow_types=EVENT_PCS_PARAMS)
)
return func
def event_postprocessor(func: T_EventPostProcessor) -> T_EventPostProcessor:
"""
:说明:
事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。
"""
"""事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。"""
_event_postprocessors.add(
Dependent[None].parse(call=func, allow_types=EVENT_PCS_PARAMS)
Dependent[Any].parse(call=func, allow_types=EVENT_PCS_PARAMS)
)
return func
def run_preprocessor(func: T_RunPreProcessor) -> T_RunPreProcessor:
"""
:说明:
运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。
"""
"""运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。"""
_run_preprocessors.add(
Dependent[None].parse(call=func, allow_types=RUN_PREPCS_PARAMS)
Dependent[Any].parse(call=func, allow_types=RUN_PREPCS_PARAMS)
)
return func
def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor:
"""
:说明:
运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。
"""
"""运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。"""
_run_postprocessors.add(
Dependent[None].parse(call=func, allow_types=RUN_POSTPCS_PARAMS)
Dependent[Any].parse(call=func, allow_types=RUN_POSTPCS_PARAMS)
)
return func
async def _run_coro_with_catch(coro: Coroutine[Any, Any, Any]) -> Any:
try:
return await coro
except SkippedException:
pass
async def _check_matcher(
priority: int,
Matcher: Type[Matcher],
@@ -172,7 +160,7 @@ async def _run_matcher(
coros = list(
map(
lambda x: _run_coro_with_catch(
lambda x: run_coro_with_catch(
x(
matcher=matcher,
bot=bot,
@@ -180,7 +168,8 @@ async def _run_matcher(
state=state,
stack=stack,
dependency_cache=dependency_cache,
)
),
(SkippedException,),
),
_run_preprocessors,
)
@@ -213,7 +202,7 @@ async def _run_matcher(
coros = list(
map(
lambda x: _run_coro_with_catch(
lambda x: run_coro_with_catch(
x(
matcher=matcher,
exception=exception,
@@ -222,7 +211,8 @@ async def _run_matcher(
state=state,
stack=stack,
dependency_cache=dependency_cache,
)
),
(SkippedException,),
),
_run_postprocessors,
)
@@ -241,22 +231,17 @@ async def _run_matcher(
async def handle_event(bot: "Bot", event: "Event") -> None:
"""
:说明:
"""处理一个事件。调用该函数以实现分发事件。
处理一个事件。调用该函数以实现分发事件。
:参数:
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
:示例:
.. code-block:: python
参数:
bot: Bot 对象
event: Event 对象
用法:
```python
import asyncio
asyncio.create_task(handle_event(bot, event))
```
"""
show_log = True
log_msg = f"<m>{escape_tag(bot.type.upper())} {escape_tag(bot.self_id)}</m> | "
@@ -273,14 +258,15 @@ async def handle_event(bot: "Bot", event: "Event") -> None:
async with AsyncExitStack() as stack:
coros = list(
map(
lambda x: _run_coro_with_catch(
lambda x: run_coro_with_catch(
x(
bot=bot,
event=event,
state=state,
stack=stack,
dependency_cache=dependency_cache,
)
),
(SkippedException,),
),
_event_preprocessors,
)
@@ -340,14 +326,15 @@ async def handle_event(bot: "Bot", event: "Event") -> None:
coros = list(
map(
lambda x: _run_coro_with_catch(
lambda x: run_coro_with_catch(
x(
bot=bot,
event=event,
state=state,
stack=stack,
dependency_cache=dependency_cache,
)
),
(SkippedException,),
),
_event_postprocessors,
)

View File

@@ -1,16 +1,28 @@
import asyncio
import inspect
from typing_extensions import Literal
from typing import Any, Dict, List, Tuple, Callable, Optional, cast
from contextlib import AsyncExitStack, contextmanager, asynccontextmanager
"""本模块定义了依赖注入的各类参数。
from pydantic.fields import Required, Undefined, ModelField
FrontMatter:
sidebar_position: 4
description: nonebot.params 模块
"""
from nonebot.log import logger
from nonebot.exception import TypeMisMatch
from nonebot.adapters import Bot, Event, Message
from nonebot.dependencies import Param, Dependent, CustomConfig
from nonebot.typing import T_State, T_Handler, T_DependencyCache
from typing import Any, Dict, List, Tuple, Optional
from nonebot.typing import T_State
from nonebot.matcher import Matcher
from nonebot.adapters import Event, Message
from nonebot.internal.params import Arg as Arg
from nonebot.internal.params import State as State
from nonebot.internal.params import ArgStr as ArgStr
from nonebot.internal.params import Depends as Depends
from nonebot.internal.params import ArgParam as ArgParam
from nonebot.internal.params import BotParam as BotParam
from nonebot.internal.params import EventParam as EventParam
from nonebot.internal.params import StateParam as StateParam
from nonebot.internal.params import DependParam as DependParam
from nonebot.internal.params import ArgPlainText as ArgPlainText
from nonebot.internal.params import DefaultParam as DefaultParam
from nonebot.internal.params import MatcherParam as MatcherParam
from nonebot.internal.params import ExceptionParam as ExceptionParam
from nonebot.consts import (
CMD_KEY,
PREFIX_KEY,
@@ -20,230 +32,9 @@ from nonebot.consts import (
CMD_ARG_KEY,
RAW_CMD_KEY,
REGEX_GROUP,
CMD_START_KEY,
REGEX_MATCHED,
)
from nonebot.utils import (
get_name,
run_sync,
is_gen_callable,
run_sync_ctx_manager,
is_async_gen_callable,
is_coroutine_callable,
generic_check_issubclass,
)
class DependsInner:
def __init__(
self,
dependency: Optional[T_Handler] = None,
*,
use_cache: bool = True,
) -> None:
self.dependency = dependency
self.use_cache = use_cache
def __repr__(self) -> str:
dep = get_name(self.dependency)
cache = "" if self.use_cache else ", use_cache=False"
return f"{self.__class__.__name__}({dep}{cache})"
def Depends(
dependency: Optional[T_Handler] = None,
*,
use_cache: bool = True,
) -> Any:
"""
:说明:
参数依赖注入装饰器
:参数:
* ``dependency: Optional[Callable[..., Any]] = None``: 依赖函数。默认为参数的类型注释。
* ``use_cache: bool = True``: 是否使用缓存。默认为 ``True``。
.. code-block:: python
def depend_func() -> Any:
return ...
def depend_gen_func():
try:
yield ...
finally:
...
async def handler(param_name: Any = Depends(depend_func), gen: Any = Depends(depend_gen_func)):
...
"""
return DependsInner(dependency, use_cache=use_cache)
class DependParam(Param):
@classmethod
def _check_param(
cls,
dependent: Dependent,
name: str,
param: inspect.Parameter,
) -> Optional["DependParam"]:
if isinstance(param.default, DependsInner):
dependency: T_Handler
if param.default.dependency is None:
assert param.annotation is not param.empty, "Dependency cannot be empty"
dependency = param.annotation
else:
dependency = param.default.dependency
sub_dependent = Dependent[Any].parse(
call=dependency,
allow_types=dependent.allow_types,
)
dependent.pre_checkers.extend(sub_dependent.pre_checkers)
sub_dependent.pre_checkers.clear()
return cls(
Required, use_cache=param.default.use_cache, dependent=sub_dependent
)
@classmethod
def _check_parameterless(
cls, dependent: "Dependent", value: Any
) -> Optional["Param"]:
if isinstance(value, DependsInner):
assert value.dependency, "Dependency cannot be empty"
dependent = Dependent[Any].parse(
call=value.dependency, allow_types=dependent.allow_types
)
return cls(Required, use_cache=value.use_cache, dependent=dependent)
async def _solve(
self,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
**kwargs: Any,
) -> Any:
use_cache: bool = self.extra["use_cache"]
dependency_cache = {} if dependency_cache is None else dependency_cache
sub_dependent: Dependent = self.extra["dependent"]
sub_dependent.call = cast(Callable[..., Any], sub_dependent.call)
call = sub_dependent.call
# solve sub dependency with current cache
sub_values = await sub_dependent.solve(
stack=stack,
dependency_cache=dependency_cache,
**kwargs,
)
# run dependency function
task: asyncio.Task[Any]
if use_cache and call in dependency_cache:
solved = await dependency_cache[call]
elif is_gen_callable(call) or is_async_gen_callable(call):
assert isinstance(
stack, AsyncExitStack
), "Generator dependency should be called in context"
if is_gen_callable(call):
cm = run_sync_ctx_manager(contextmanager(call)(**sub_values))
else:
cm = asynccontextmanager(call)(**sub_values)
task = asyncio.create_task(stack.enter_async_context(cm))
dependency_cache[call] = task
solved = await task
elif is_coroutine_callable(call):
task = asyncio.create_task(call(**sub_values))
dependency_cache[call] = task
solved = await task
else:
task = asyncio.create_task(run_sync(call)(**sub_values))
dependency_cache[call] = task
solved = await task
return solved
class _BotChecker(Param):
async def _solve(self, bot: Bot, **kwargs: Any) -> Any:
field: ModelField = self.extra["field"]
_, errs_ = field.validate(bot, {}, loc=("bot",))
if errs_:
logger.debug(
f"Bot type {type(bot)} not match "
f"annotation {field._type_display()}, ignored"
)
raise TypeMisMatch(field, bot)
class BotParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["BotParam"]:
if param.default == param.empty:
if generic_check_issubclass(param.annotation, Bot):
if param.annotation is not Bot:
dependent.pre_checkers.append(
_BotChecker(
Required,
field=ModelField(
name=name,
type_=param.annotation,
class_validators=None,
model_config=CustomConfig,
default=None,
required=True,
),
)
)
return cls(Required)
elif param.annotation == param.empty and name == "bot":
return cls(Required)
async def _solve(self, bot: Bot, **kwargs: Any) -> Any:
return bot
class _EventChecker(Param):
async def _solve(self, event: Event, **kwargs: Any) -> Any:
field: ModelField = self.extra["field"]
_, errs_ = field.validate(event, {}, loc=("event",))
if errs_:
logger.debug(
f"Event type {type(event)} not match "
f"annotation {field._type_display()}, ignored"
)
raise TypeMisMatch(field, event)
class EventParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["EventParam"]:
if param.default == param.empty:
if generic_check_issubclass(param.annotation, Event):
if param.annotation is not Event:
dependent.pre_checkers.append(
_EventChecker(
Required,
field=ModelField(
name=name,
type_=param.annotation,
class_validators=None,
model_config=CustomConfig,
default=None,
required=True,
),
)
)
return cls(Required)
elif param.annotation == param.empty and name == "event":
return cls(Required)
async def _solve(self, event: Event, **kwargs: Any) -> Any:
return event
async def _event_type(event: Event) -> str:
@@ -251,6 +42,7 @@ async def _event_type(event: Event) -> str:
def EventType() -> str:
"""{ref}`nonebot.adapters.Event` 类型参数"""
return Depends(_event_type)
@@ -259,6 +51,7 @@ async def _event_message(event: Event) -> Message:
def EventMessage() -> Any:
"""{ref}`nonebot.adapters.Event` 消息参数"""
return Depends(_event_message)
@@ -267,6 +60,7 @@ async def _event_plain_text(event: Event) -> str:
def EventPlainText() -> str:
"""{ref}`nonebot.adapters.Event` 纯文本消息参数"""
return Depends(_event_plain_text)
@@ -275,108 +69,94 @@ async def _event_to_me(event: Event) -> bool:
def EventToMe() -> bool:
"""{ref}`nonebot.adapters.Event` `to_me` 参数"""
return Depends(_event_to_me)
class StateInner:
...
def State() -> T_State:
return StateInner() # type: ignore
class StateParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["StateParam"]:
if isinstance(param.default, StateInner):
return cls(Required)
async def _solve(self, state: T_State, **kwargs: Any) -> Any:
return state
def _command(state=State()) -> Message:
def _command(state: T_State) -> Message:
return state[PREFIX_KEY][CMD_KEY]
def Command() -> Tuple[str, ...]:
return Depends(_command, use_cache=False)
"""消息命令元组"""
return Depends(_command)
def _raw_command(state=State()) -> Message:
def _raw_command(state: T_State) -> Message:
return state[PREFIX_KEY][RAW_CMD_KEY]
def RawCommand() -> str:
return Depends(_raw_command, use_cache=False)
"""消息命令文本"""
return Depends(_raw_command)
def _command_arg(state=State()) -> Message:
def _command_arg(state: T_State) -> Message:
return state[PREFIX_KEY][CMD_ARG_KEY]
def CommandArg() -> Any:
return Depends(_command_arg, use_cache=False)
"""消息命令参数"""
return Depends(_command_arg)
def _shell_command_args(state=State()) -> Any:
def _command_start(state: T_State) -> str:
return state[PREFIX_KEY][CMD_START_KEY]
def CommandStart() -> str:
"""消息命令开头"""
return Depends(_command_start)
def _shell_command_args(state: T_State) -> Any:
return state[SHELL_ARGS]
def ShellCommandArgs():
"""shell 命令解析后的参数字典"""
return Depends(_shell_command_args, use_cache=False)
def _shell_command_argv(state=State()) -> List[str]:
def _shell_command_argv(state: T_State) -> List[str]:
return state[SHELL_ARGV]
def ShellCommandArgv() -> Any:
"""shell 命令原始参数列表"""
return Depends(_shell_command_argv, use_cache=False)
def _regex_matched(state=State()) -> str:
def _regex_matched(state: T_State) -> str:
return state[REGEX_MATCHED]
def RegexMatched() -> str:
"""正则匹配结果"""
return Depends(_regex_matched, use_cache=False)
def _regex_group(state=State()):
def _regex_group(state: T_State):
return state[REGEX_GROUP]
def RegexGroup() -> Tuple[Any, ...]:
"""正则匹配结果 group 元组"""
return Depends(_regex_group, use_cache=False)
def _regex_dict(state=State()):
def _regex_dict(state: T_State):
return state[REGEX_DICT]
def RegexDict() -> Dict[str, Any]:
"""正则匹配结果 group 字典"""
return Depends(_regex_dict, use_cache=False)
class MatcherParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["MatcherParam"]:
if generic_check_issubclass(param.annotation, Matcher) or (
param.annotation == param.empty and name == "matcher"
):
return cls(Required)
async def _solve(self, matcher: "Matcher", **kwargs: Any) -> Any:
return matcher
def Received(id: Optional[str] = None, default: Any = None) -> Any:
"""`receive` 事件参数"""
def _received(matcher: "Matcher"):
return matcher.get_receive(id or "", default)
@@ -384,76 +164,26 @@ def Received(id: Optional[str] = None, default: Any = None) -> Any:
def LastReceived(default: Any = None) -> Any:
"""`last_receive` 事件参数"""
def _last_received(matcher: "Matcher") -> Any:
return matcher.get_last_receive(default)
return Depends(_last_received, use_cache=False)
class ArgInner:
def __init__(
self, key: Optional[str], type: Literal["message", "str", "plaintext"]
) -> None:
self.key = key
self.type = type
def Arg(key: Optional[str] = None) -> Any:
return ArgInner(key, "message")
def ArgStr(key: Optional[str] = None) -> str:
return ArgInner(key, "str") # type: ignore
def ArgPlainText(key: Optional[str] = None) -> str:
return ArgInner(key, "plaintext") # type: ignore
class ArgParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["ArgParam"]:
if isinstance(param.default, ArgInner):
return cls(Required, key=param.default.key or name, type=param.default.type)
async def _solve(self, matcher: "Matcher", **kwargs: Any) -> Any:
message = matcher.get_arg(self.extra["key"])
if message is None:
return message
if self.extra["type"] == "message":
return message
elif self.extra["type"] == "str":
return str(message)
else:
return message.extract_plain_text()
class ExceptionParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["ExceptionParam"]:
if generic_check_issubclass(param.annotation, Exception) or (
param.annotation == param.empty and name == "exception"
):
return cls(Required)
async def _solve(self, exception: Optional[Exception] = None, **kwargs: Any) -> Any:
return exception
class DefaultParam(Param):
@classmethod
def _check_param(
cls, dependent: Dependent, name: str, param: inspect.Parameter
) -> Optional["DefaultParam"]:
if param.default != param.empty:
return cls(param.default)
async def _solve(self, **kwargs: Any) -> Any:
return Undefined
from nonebot.matcher import Matcher
__autodoc__ = {
"Arg": True,
"State": True,
"ArgStr": True,
"Depends": True,
"ArgParam": True,
"BotParam": True,
"EventParam": True,
"StateParam": True,
"DependParam": True,
"ArgPlainText": True,
"DefaultParam": True,
"MatcherParam": True,
"ExceptionParam": True,
}

View File

@@ -1,210 +1,83 @@
r"""
权限
====
"""本模块是 {ref}`nonebot.matcher.Matcher.permission` 的类型定义。
每个 ``Matcher`` 拥有一个 ``Permission`` ,其中是 ``PermissionChecker`` 的集合,只要有一个 ``PermissionChecker`` 检查结果为 ``True`` 时就会继续运行。
每个 {ref}`nonebot.matcher.Matcher` 拥有一个 {ref}`nonebot.permission.Permission`
其中是 `PermissionChecker` 的集合,只要有一个 `PermissionChecker` 检查结果为 `True` 时就会继续运行。
\:\:\:tip 提示
``PermissionChecker`` 既可以是 async function 也可以是 sync function
\:\:\:
FrontMatter:
sidebar_position: 6
description: nonebot.permission 模块
"""
import asyncio
from contextlib import AsyncExitStack
from typing import Any, Set, Tuple, Union, NoReturn, Optional, Coroutine
from nonebot.params import EventType
from nonebot.adapters import Bot, Event
from nonebot.dependencies import Dependent
from nonebot.exception import SkippedException
from nonebot.typing import T_Handler, T_DependencyCache, T_PermissionChecker
from nonebot.params import (
BotParam,
EventType,
EventParam,
DependParam,
DefaultParam,
)
async def _run_coro_with_catch(coro: Coroutine[Any, Any, Any]):
try:
return await coro
except SkippedException:
return False
class Permission:
"""
:说明:
``Matcher`` 规则类,当事件传递时,在 ``Matcher`` 运行前进行检查。
:示例:
.. code-block:: python
Permission(async_function) | sync_function
# 等价于
from nonebot.utils import run_sync
Permission(async_function, run_sync(sync_function))
"""
__slots__ = ("checkers",)
HANDLER_PARAM_TYPES = [
DependParam,
BotParam,
EventParam,
DefaultParam,
]
def __init__(self, *checkers: Union[T_PermissionChecker, Dependent[bool]]) -> None:
"""
:参数:
* ``*checkers: Union[T_PermissionChecker, Dependent[bool]``: PermissionChecker
"""
self.checkers: Set[Dependent[bool]] = set(
checker
if isinstance(checker, Dependent)
else Dependent[bool].parse(
call=checker, allow_types=self.HANDLER_PARAM_TYPES
)
for checker in checkers
)
"""
:说明:
存储 ``PermissionChecker``
:类型:
* ``Set[Dependent[bool]]``
"""
async def __call__(
self,
bot: Bot,
event: Event,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""
:说明:
检查是否满足某个权限
:参数:
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
* ``stack: Optional[AsyncExitStack]``: 异步上下文栈
* ``dependency_cache: Optional[CacheDict[T_Handler, Any]]``: 依赖缓存
:返回:
- ``bool``
"""
if not self.checkers:
return True
results = await asyncio.gather(
*(
_run_coro_with_catch(
checker(
bot=bot,
event=event,
stack=stack,
dependency_cache=dependency_cache,
)
)
for checker in self.checkers
),
)
return any(results)
def __and__(self, other) -> NoReturn:
raise RuntimeError("And operation between Permissions is not allowed.")
def __or__(
self, other: Optional[Union["Permission", T_PermissionChecker]]
) -> "Permission":
if other is None:
return self
elif isinstance(other, Permission):
return Permission(*self.checkers, *other.checkers)
else:
return Permission(*self.checkers, other)
from nonebot.internal.permission import USER as USER
from nonebot.internal.permission import User as User
from nonebot.internal.permission import Permission as Permission
class Message:
"""检查是否为消息事件"""
__slots__ = ()
async def __call__(self, type: str = EventType()) -> bool:
return type == "message"
class Notice:
"""检查是否为通知事件"""
__slots__ = ()
async def __call__(self, type: str = EventType()) -> bool:
return type == "notice"
class Request:
"""检查是否为请求事件"""
__slots__ = ()
async def __call__(self, type: str = EventType()) -> bool:
return type == "request"
class MetaEvent:
"""检查是否为元事件"""
__slots__ = ()
async def __call__(self, type: str = EventType()) -> bool:
return type == "meta_event"
MESSAGE = Permission(Message())
MESSAGE: Permission = Permission(Message())
"""匹配任意 `message` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 message type 的 Matcher。
"""
- **说明**: 匹配任意 ``message`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 message type 的 Matcher。
NOTICE: Permission = Permission(Notice())
"""匹配任意 `notice` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 notice type 的 Matcher。
"""
NOTICE = Permission(Notice())
REQUEST: Permission = Permission(Request())
"""匹配任意 `request` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 request type 的 Matcher。
"""
- **说明**: 匹配任意 ``notice`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 notice type 的 Matcher。
METAEVENT: Permission = Permission(MetaEvent())
"""匹配任意 `meta_event` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 meta_event type 的 Matcher。
"""
REQUEST = Permission(Request())
"""
- **说明**: 匹配任意 ``request`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 request type 的 Matcher。
"""
METAEVENT = Permission(MetaEvent())
"""
- **说明**: 匹配任意 ``meta_event`` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 meta_event type 的 Matcher。
"""
class User:
def __init__(
self, users: Tuple[str, ...], perm: Optional[Permission] = None
) -> None:
self.users = users
self.perm = perm
async def __call__(self, bot: Bot, event: Event) -> bool:
return bool(
event.get_session_id() in self.users
and (self.perm is None or await self.perm(bot, event))
)
def USER(*users: str, perm: Optional[Permission] = None):
"""
:说明:
``event`` 的 ``session_id`` 在白名单内且满足 perm
:参数:
* ``*user: str``: 白名单
* ``perm: Optional[Permission]``: 需要同时满足的权限
"""
return Permission(User(users, perm))
class SuperUser:
"""检查当前事件是否是消息事件且属于超级管理员"""
__slots__ = ()
async def __call__(self, bot: Bot, event: Event) -> bool:
return event.get_type() == "message" and (
f"{bot.adapter.get_name().split(maxsplit=1)[0].lower()}:{event.get_user_id()}"
@@ -213,7 +86,12 @@ class SuperUser:
)
SUPERUSER = Permission(SuperUser())
"""
- **说明**: 匹配任意超级用户消息类型事件
"""
SUPERUSER: Permission = Permission(SuperUser())
"""匹配任意超级用户消息类型事件"""
__autodoc__ = {
"Permission": True,
"Permission.__call__": True,
"User": True,
"USER": True,
}

View File

@@ -1,18 +1,111 @@
"""
插件
====
"""本模块为 NoneBot 插件开发提供便携的定义函数。
为 NoneBot 插件开发提供便携的定义函数。
## 快捷导入
为方便使用,本模块从子模块导入了部分内容,以下内容可以直接通过本模块导入:
- `on` => {ref}``on` <nonebot.plugin.on.on>`
- `on_metaevent` => {ref}``on_metaevent` <nonebot.plugin.on.on_metaevent>`
- `on_message` => {ref}``on_message` <nonebot.plugin.on.on_message>`
- `on_notice` => {ref}``on_notice` <nonebot.plugin.on.on_notice>`
- `on_request` => {ref}``on_request` <nonebot.plugin.on.on_request>`
- `on_startswith` => {ref}``on_startswith` <nonebot.plugin.on.on_startswith>`
- `on_endswith` => {ref}``on_endswith` <nonebot.plugin.on.on_endswith>`
- `on_fullmatch` => {ref}``on_fullmatch` <nonebot.plugin.on.on_fullmatch>`
- `on_keyword` => {ref}``on_keyword` <nonebot.plugin.on.on_keyword>`
- `on_command` => {ref}``on_command` <nonebot.plugin.on.on_command>`
- `on_shell_command` => {ref}``on_shell_command` <nonebot.plugin.on.on_shell_command>`
- `on_regex` => {ref}``on_regex` <nonebot.plugin.on.on_regex>`
- `CommandGroup` => {ref}``CommandGroup` <nonebot.plugin.on.CommandGroup>`
- `Matchergroup` => {ref}``MatcherGroup` <nonebot.plugin.on.MatcherGroup>`
- `load_plugin` => {ref}``load_plugin` <nonebot.plugin.load.load_plugin>`
- `load_plugins` => {ref}``load_plugins` <nonebot.plugin.load.load_plugins>`
- `load_all_plugins` => {ref}``load_all_plugins` <nonebot.plugin.load.load_all_plugins>`
- `load_from_json` => {ref}``load_from_json` <nonebot.plugin.load.load_from_json>`
- `load_from_toml` => {ref}``load_from_toml` <nonebot.plugin.load.load_from_toml>`
- `load_builtin_plugin` => {ref}``load_builtin_plugin` <nonebot.plugin.load.load_builtin_plugin>`
- `load_builtin_plugins` => {ref}``load_builtin_plugins` <nonebot.plugin.load.load_builtin_plugins>`
- `get_plugin` => {ref}``get_plugin` <nonebot.plugin.plugin.get_plugin>`
- `get_loaded_plugins` => {ref}``get_loaded_plugins` <nonebot.plugin.plugin.get_loaded_plugins>`
- `export` => {ref}``export` <nonebot.plugin.export.export>`
- `require` => {ref}``require` <nonebot.plugin.load.require>`
FrontMatter:
sidebar_position: 0
description: nonebot.plugin 模块
"""
from typing import List, Optional
from itertools import chain
from types import ModuleType
from contextvars import ContextVar
from typing import Set, Dict, List, Optional
_plugins: Dict[str, "Plugin"] = {}
_managers: List["PluginManager"] = []
_current_plugin: ContextVar[Optional["Plugin"]] = ContextVar(
"_current_plugin", default=None
)
def _module_name_to_plugin_name(module_name: str) -> str:
return module_name.rsplit(".", 1)[-1]
def _new_plugin(
module_name: str, module: ModuleType, manager: "PluginManager"
) -> "Plugin":
plugin_name = _module_name_to_plugin_name(module_name)
if plugin_name in _plugins:
raise RuntimeError("Plugin already exists! Check your plugin name.")
plugin = Plugin(plugin_name, module, module_name, manager)
_plugins[plugin_name] = plugin
return plugin
def _revert_plugin(plugin: "Plugin") -> None:
if plugin.name not in _plugins:
raise RuntimeError("Plugin not found!")
del _plugins[plugin.name]
def get_plugin(name: str) -> Optional["Plugin"]:
"""获取已经导入的某个插件。
如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。
参数:
name: 插件名,即 {ref}`nonebot.plugin.plugin.Plugin.name`。
"""
return _plugins.get(name)
def get_plugin_by_module_name(module_name: str) -> Optional["Plugin"]:
"""通过模块名获取已经导入的某个插件。
如果提供的模块名为某个插件的子模块,同样会返回该插件。
参数:
module_name: 模块名,即 {ref}`nonebot.plugin.plugin.Plugin.module_name`。
"""
splits = module_name.split(".")
loaded = {plugin.module_name: plugin for plugin in _plugins.values()}
while splits:
name = ".".join(splits)
if name in loaded:
return loaded[name]
splits.pop()
def get_loaded_plugins() -> Set["Plugin"]:
"""获取当前已导入的所有插件。"""
return set(_plugins.values())
def get_available_plugin_names() -> Set[str]:
"""获取当前所有可用的插件名(包含尚未加载的插件)。"""
return {*chain.from_iterable(manager.available_plugins for manager in _managers)}
from .on import on as on
from .manager import PluginManager
from .export import Export as Export
@@ -29,13 +122,14 @@ from .on import on_endswith as on_endswith
from .load import load_plugin as load_plugin
from .on import CommandGroup as CommandGroup
from .on import MatcherGroup as MatcherGroup
from .on import on_fullmatch as on_fullmatch
from .on import on_metaevent as on_metaevent
from .plugin import get_plugin as get_plugin
from .load import load_plugins as load_plugins
from .on import on_startswith as on_startswith
from .load import load_from_json as load_from_json
from .load import load_from_toml as load_from_toml
from .on import on_shell_command as on_shell_command
from .plugin import PluginMetadata as PluginMetadata
from .load import load_all_plugins as load_all_plugins
from .plugin import get_loaded_plugins as get_loaded_plugins
from .load import load_builtin_plugin as load_builtin_plugin
from .load import load_builtin_plugins as load_builtin_plugins

View File

@@ -1,16 +1,22 @@
"""本模块定义了插件导出的内容对象。
在新版插件系统中,推荐优先使用直接 import 所需要的插件内容。
FrontMatter:
sidebar_position: 4
description: nonebot.plugin.export 模块
"""
import warnings
from . import _current_plugin
class Export(dict):
"""
:说明:
插件导出内容以使得其他插件可以获得。
:示例:
.. code-block:: python
"""插件导出内容以使得其他插件可以获得。
用法:
```python
nonebot.export().default = "bar"
@nonebot.export()
@@ -25,6 +31,7 @@ class Export(dict):
@nonebot.export().sub
def something_else():
pass
```
"""
def __call__(self, func, **kwargs):
@@ -45,15 +52,12 @@ class Export(dict):
def export() -> Export:
"""
:说明:
获取插件的导出内容对象
:返回:
- ``Export``
"""
"""获取当前插件的导出内容对象"""
warnings.warn(
"nonebot.export() is deprecated. "
"See https://github.com/nonebot/nonebot2/issues/935.",
DeprecationWarning,
)
plugin = _current_plugin.get()
if not plugin:
raise RuntimeError("Export outside of the plugin!")

View File

@@ -1,28 +1,26 @@
"""本模块定义插件加载接口。
FrontMatter:
sidebar_position: 1
description: nonebot.plugin.load 模块
"""
import json
import warnings
from typing import Set, Iterable, Optional
import tomlkit
from . import _managers
from .export import Export
from .plugin import Plugin
from .manager import PluginManager
from .plugin import Plugin, get_plugin
from . import _managers, get_plugin, _module_name_to_plugin_name
def load_plugin(module_path: str) -> Optional[Plugin]:
"""
:说明:
"""加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。
使用 ``PluginManager`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。
:参数:
* ``module_path: str``: 插件名称 ``path.to.your.plugin``
:返回:
- ``Optional[Plugin]``
参数:
module_path: 插件名称 `path.to.your.plugin`
"""
manager = PluginManager([module_path])
@@ -31,18 +29,10 @@ def load_plugin(module_path: str) -> Optional[Plugin]:
def load_plugins(*plugin_dir: str) -> Set[Plugin]:
"""
:说明:
"""导入文件夹下多个插件,以 `_` 开头的插件不会被导入!
导入目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``*plugin_dir: str``: 插件路径
:返回:
- ``Set[Plugin]``
参数:
plugin_dir: 文件夹路径
"""
manager = PluginManager(search_path=plugin_dir)
_managers.append(manager)
@@ -52,19 +42,11 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]:
def load_all_plugins(
module_path: Iterable[str], plugin_dir: Iterable[str]
) -> Set[Plugin]:
"""
:说明:
"""导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入!
导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``module_path: Iterable[str]``: 指定插件集合
- ``plugin_dir: Iterable[str]``: 指定插件路径集合
:返回:
- ``Set[Plugin]``
参数:
module_path: 指定插件集合
plugin_dir: 指定文件夹路径集合
"""
manager = PluginManager(module_path, plugin_dir)
_managers.append(manager)
@@ -72,19 +54,23 @@ def load_all_plugins(
def load_from_json(file_path: str, encoding: str = "utf-8") -> Set[Plugin]:
"""
:说明:
"""导入指定 json 文件中的 `plugins` 以及 `plugin_dirs` 下多个插件,以 `_` 开头的插件不会被导入!
导入指定 json 文件中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,以 ``_`` 开头的插件不会被导入!
参数:
file_path: 指定 json 文件路径
encoding: 指定 json 文件编码
:参数:
用法:
```json title=plugins.json
{
"plugins": ["some_plugin"],
"plugin_dirs": ["some_dir"]
}
```
- ``file_path: str``: 指定 json 文件路径
- ``encoding: str``: 指定 json 文件编码
:返回:
- ``Set[Plugin]``
```python
nonebot.load_from_json("plugins.json")
```
"""
with open(file_path, "r", encoding=encoding) as f:
data = json.load(f)
@@ -96,20 +82,22 @@ def load_from_json(file_path: str, encoding: str = "utf-8") -> Set[Plugin]:
def load_from_toml(file_path: str, encoding: str = "utf-8") -> Set[Plugin]:
"""
:说明:
"""导入指定 toml 文件 `[tool.nonebot]` 中的 `plugins` 以及 `plugin_dirs` 下多个插件,以 `_` 开头的插件不会被导入!
导入指定 toml 文件 ``[tool.nonebot]`` 中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,
以 ``_`` 开头的插件不会被导入!
参数:
file_path: 指定 toml 文件路径
encoding: 指定 toml 文件编码
:参数:
用法:
```toml title=pyproject.toml
[tool.nonebot]
plugins = ["some_plugin"]
plugin_dirs = ["some_dir"]
```
- ``file_path: str``: 指定 toml 文件路径
- ``encoding: str``: 指定 toml 文件编码
:返回:
- ``Set[Plugin]``
```python
nonebot.load_from_toml("pyproject.toml")
```
"""
with open(file_path, "r", encoding=encoding) as f:
data = tomlkit.parse(f.read()) # type: ignore
@@ -119,7 +107,7 @@ def load_from_toml(file_path: str, encoding: str = "utf-8") -> Set[Plugin]:
nonebot_data = data.get("nonebot", {}).get("plugins")
if nonebot_data:
warnings.warn(
"[nonebot.plugins] table are now deprecated. Use [tool.nonebot] instead.",
"[nonebot.plugins] table is deprecated. Use [tool.nonebot] instead.",
DeprecationWarning,
)
else:
@@ -131,37 +119,48 @@ def load_from_toml(file_path: str, encoding: str = "utf-8") -> Set[Plugin]:
return load_all_plugins(plugins, plugin_dirs)
def load_builtin_plugins(name: str) -> Optional[Plugin]:
"""
:说明:
def load_builtin_plugin(name: str) -> Optional[Plugin]:
"""导入 NoneBot 内置插件。
导入 NoneBot 内置插件
:返回:
- ``Plugin``
参数:
name: 插件名称
"""
return load_plugin(f"nonebot.plugins.{name}")
def load_builtin_plugins(*plugins: str) -> Set[Plugin]:
"""导入多个 NoneBot 内置插件。
参数:
plugins: 插件名称列表
"""
return load_all_plugins([f"nonebot.plugins.{p}" for p in plugins], [])
def _find_manager_by_name(name: str) -> Optional[PluginManager]:
for manager in reversed(_managers):
if name in manager.plugins or name in manager.searched_plugins:
return manager
def require(name: str) -> Export:
"""获取一个插件的导出内容。
如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。
参数:
name: 插件名,即 {ref}`nonebot.plugin.plugin.Plugin.name`。
异常:
RuntimeError: 插件无法加载
"""
:说明:
获取一个插件的导出内容
:参数:
* ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。
:返回:
- ``Export``
:异常:
- ``RuntimeError``: 插件无法加载
"""
plugin = get_plugin(name) or load_plugin(name)
plugin = get_plugin(_module_name_to_plugin_name(name))
if not plugin:
manager = _find_manager_by_name(name)
if manager:
plugin = manager.load_plugin(name)
else:
plugin = load_plugin(name)
if not plugin:
raise RuntimeError(f'Cannot load plugin "{name}"!')
return plugin.export

View File

@@ -1,3 +1,11 @@
"""本模块实现插件加载流程。
参考: [import hooks](https://docs.python.org/3/reference/import.html#import-hooks), [PEP302](https://www.python.org/dev/peps/pep-0302/)
FrontMatter:
sidebar_position: 5
description: nonebot.plugin.manager 模块
"""
import sys
import pkgutil
import importlib
@@ -10,23 +18,53 @@ from typing import Set, Dict, List, Union, Iterable, Optional, Sequence
from nonebot.log import logger
from nonebot.utils import escape_tag
from .plugin import Plugin, _new_plugin
from . import _managers, _current_plugin
from .plugin import Plugin, PluginMetadata
from . import (
_managers,
_new_plugin,
_revert_plugin,
_current_plugin,
_module_name_to_plugin_name,
)
class PluginManager:
"""插件管理器。
参数:
plugins: 独立插件模块名集合。
search_path: 插件搜索路径(文件夹)。
"""
def __init__(
self,
plugins: Optional[Iterable[str]] = None,
search_path: Optional[Iterable[str]] = None,
):
# simple plugin not in search path
self.plugins: Set[str] = set(plugins or [])
self.search_path: Set[str] = set(search_path or [])
# cache plugins
self.searched_plugins: Dict[str, Path] = {}
self.list_plugins()
self._third_party_plugin_names: Dict[str, str] = {}
self._searched_plugin_names: Dict[str, Path] = {}
self.prepare_plugins()
@property
def third_party_plugins(self) -> Set[str]:
"""返回所有独立插件名称。"""
return set(self._third_party_plugin_names.keys())
@property
def searched_plugins(self) -> Set[str]:
"""返回已搜索到的插件名称。"""
return set(self._searched_plugin_names.keys())
@property
def available_plugins(self) -> Set[str]:
"""返回当前插件管理器中可用的插件名称。"""
return self.third_party_plugins | self.searched_plugins
def _path_to_module_name(self, path: Path) -> str:
rel_path = path.resolve().relative_to(Path(".").resolve())
@@ -35,45 +73,51 @@ class PluginManager:
else:
return ".".join(rel_path.parts[:-1] + (rel_path.stem,))
def _previous_plugins(self) -> List[str]:
def _previous_plugins(self) -> Set[str]:
_pre_managers: List[PluginManager]
if self in _managers:
_pre_managers = _managers[: _managers.index(self)]
else:
_pre_managers = _managers[:]
return [
*chain.from_iterable(
[*manager.plugins, *manager.searched_plugins.keys()]
for manager in _pre_managers
)
]
return {
*chain.from_iterable(manager.available_plugins for manager in _pre_managers)
}
def prepare_plugins(self) -> Set[str]:
"""搜索插件并缓存插件名称。"""
def list_plugins(self) -> Set[str]:
# get all previous ready to load plugins
previous_plugins = self._previous_plugins()
searched_plugins: Dict[str, Path] = {}
third_party_plugins: Set[str] = set()
third_party_plugins: Dict[str, str] = {}
# check third party plugins
for plugin in self.plugins:
name = plugin.rsplit(".", 1)[-1] if "." in plugin else plugin
name = _module_name_to_plugin_name(plugin)
if name in third_party_plugins or name in previous_plugins:
raise RuntimeError(
f"Plugin already exists: {name}! Check your plugin name"
)
third_party_plugins.add(plugin)
third_party_plugins[name] = plugin
self._third_party_plugin_names = third_party_plugins
# check plugins in search path
for module_info in pkgutil.iter_modules(self.search_path):
# ignore if startswith "_"
if module_info.name.startswith("_"):
continue
if (
module_info.name in searched_plugins.keys()
module_info.name in searched_plugins
or module_info.name in previous_plugins
or module_info.name in third_party_plugins
):
raise RuntimeError(
f"Plugin already exists: {module_info.name}! Check your plugin name"
)
module_spec = module_info.module_finder.find_spec(module_info.name, None)
if not module_spec:
continue
@@ -82,33 +126,51 @@ class PluginManager:
continue
searched_plugins[module_info.name] = Path(module_path).resolve()
self.searched_plugins = searched_plugins
self._searched_plugin_names = searched_plugins
return third_party_plugins | set(self.searched_plugins.keys())
return self.available_plugins
def load_plugin(self, name: str) -> Optional[Plugin]:
"""加载指定插件。
对于独立插件,可以使用完整插件模块名或者插件名称。
参数:
name: 插件名称。
"""
def load_plugin(self, name) -> Optional[Plugin]:
try:
if name in self.plugins:
module = importlib.import_module(name)
elif name not in self.searched_plugins:
raise RuntimeError(f"Plugin not found: {name}! Check your plugin name")
else:
elif name in self._third_party_plugin_names:
module = importlib.import_module(self._third_party_plugin_names[name])
elif name in self._searched_plugin_names:
module = importlib.import_module(
self._path_to_module_name(self.searched_plugins[name])
self._path_to_module_name(self._searched_plugin_names[name])
)
else:
raise RuntimeError(f"Plugin not found: {name}! Check your plugin name")
logger.opt(colors=True).success(
f'Succeeded to import "<y>{escape_tag(name)}</y>"'
)
return getattr(module, "__plugin__", None)
plugin = getattr(module, "__plugin__", None)
if plugin is None:
raise RuntimeError(
f"Module {module.__name__} is not loaded as a plugin! "
"Make sure not to import it before loading."
)
return plugin
except Exception as e:
logger.opt(colors=True, exception=e).error(
f'<r><bg #f8bbd0>Failed to import "{escape_tag(name)}"</bg #f8bbd0></r>'
)
def load_all_plugins(self) -> Set[Plugin]:
"""加载所有可用插件。"""
return set(
filter(None, (self.load_plugin(name) for name in self.list_plugins()))
filter(None, (self.load_plugin(name) for name in self.available_plugins))
)
@@ -120,7 +182,6 @@ class PluginFinder(MetaPathFinder):
target: Optional[ModuleType] = None,
):
if _managers:
index = -1
module_spec = PathFinder.find_spec(fullname, path, target)
if not module_spec:
return
@@ -129,17 +190,14 @@ class PluginFinder(MetaPathFinder):
return
module_path = Path(module_origin).resolve()
while -index <= len(_managers):
manager = _managers[index]
for manager in reversed(_managers):
# use path instead of name in case of submodule name conflict
if (
fullname in manager.plugins
or module_path in manager.searched_plugins.values()
or module_path in manager._searched_plugin_names.values()
):
module_spec.loader = PluginLoader(manager, fullname, module_origin)
return module_spec
index -= 1
return
@@ -160,7 +218,11 @@ class PluginLoader(SourceFileLoader):
if self.loaded:
return
# create plugin before executing
plugin = _new_plugin(self.name, module, self.manager)
setattr(module, "__plugin__", plugin)
# detect parent plugin before entering current plugin context
parent_plugin = _current_plugin.get()
if parent_plugin and _managers.index(parent_plugin.manager) < _managers.index(
self.manager
@@ -168,19 +230,22 @@ class PluginLoader(SourceFileLoader):
plugin.parent_plugin = parent_plugin
parent_plugin.sub_plugins.add(plugin)
# enter plugin context
_plugin_token = _current_plugin.set(plugin)
setattr(module, "__plugin__", plugin)
# try:
# super().exec_module(module)
# except Exception as e:
# raise ImportError(
# f"Error when executing module {module_name} from {module.__file__}."
# ) from e
try:
super().exec_module(module)
except Exception:
_revert_plugin(plugin)
raise
finally:
# leave plugin context
_current_plugin.reset(_plugin_token)
# get plugin metadata
metadata: Optional[PluginMetadata] = getattr(module, "__plugin_meta__", None)
plugin.metadata = metadata
return

View File

@@ -1,19 +1,18 @@
"""本模块定义事件响应器便携定义函数。
FrontMatter:
sidebar_position: 2
description: nonebot.plugin.on 模块
"""
import re
import sys
import inspect
from types import ModuleType
from typing import Any, Set, Dict, List, Type, Tuple, Union, Optional
from nonebot.matcher import Matcher
from .manager import _current_plugin
from nonebot.permission import Permission
from nonebot.dependencies import Dependent
from nonebot.typing import (
T_State,
T_Handler,
T_RuleChecker,
T_PermissionChecker,
)
from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker
from nonebot.rule import (
Rule,
ArgumentParser,
@@ -21,10 +20,13 @@ from nonebot.rule import (
command,
keyword,
endswith,
fullmatch,
startswith,
shell_command,
)
from .manager import _current_plugin
def _store_matcher(matcher: Type[Matcher]) -> None:
plugin = _current_plugin.get()
@@ -38,8 +40,7 @@ def _get_matcher_module(depth: int = 1) -> Optional[ModuleType]:
if current_frame is None:
return None
frame = inspect.getouterframes(current_frame)[depth + 1].frame
module_name = frame.f_globals["__name__"]
return sys.modules.get(module_name)
return inspect.getmodule(frame)
def on(
@@ -55,24 +56,17 @@ def on(
_depth: int = 0,
) -> Type[Matcher]:
"""
:说明:
注册一个基础事件响应器,可自定义类型。
:参数:
* ``type: str``: 事件响应器类型
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
type: 事件响应器类型
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
matcher = Matcher.new(
type,
@@ -101,22 +95,15 @@ def on_metaevent(
_depth: int = 0,
) -> Type[Matcher]:
"""
:说明:
注册一个元事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
matcher = Matcher.new(
"meta_event",
@@ -146,23 +133,16 @@ def on_message(
_depth: int = 0,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
matcher = Matcher.new(
"message",
@@ -191,22 +171,15 @@ def on_notice(
_depth: int = 0,
) -> Type[Matcher]:
"""
:说明:
注册一个通知事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
matcher = Matcher.new(
"notice",
@@ -235,22 +208,15 @@ def on_request(
_depth: int = 0,
) -> Type[Matcher]:
"""
:说明:
注册一个请求事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
matcher = Matcher.new(
"request",
@@ -270,66 +236,76 @@ def on_request(
def on_startswith(
msg: Union[str, Tuple[str, ...]],
rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = None,
rule: Optional[Union[Rule, T_RuleChecker]] = None,
ignorecase: bool = False,
_depth: int = 0,
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``ignorecase: bool``: 是否忽略大小写
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
msg: 指定消息开头内容
rule: 事件响应规则
ignorecase: 是否忽略大小写
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
return on_message(startswith(msg, ignorecase) & rule, **kwargs, _depth=_depth + 1)
def on_endswith(
msg: Union[str, Tuple[str, ...]],
rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = None,
rule: Optional[Union[Rule, T_RuleChecker]] = None,
ignorecase: bool = False,
_depth: int = 0,
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``ignorecase: bool``: 是否忽略大小写
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
msg: 指定消息结尾内容
rule: 事件响应规则
ignorecase: 是否忽略大小写
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
return on_message(endswith(msg, ignorecase) & rule, **kwargs, _depth=_depth + 1)
def on_fullmatch(
msg: Union[str, Tuple[str, ...]],
rule: Optional[Union[Rule, T_RuleChecker]] = None,
ignorecase: bool = False,
_depth: int = 0,
**kwargs,
) -> Type[Matcher]:
"""
注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。
参数:
msg: 指定消息全匹配内容
rule: 事件响应规则
ignorecase: 是否忽略大小写
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
return on_message(fullmatch(msg, ignorecase) & rule, **kwargs, _depth=_depth + 1)
def on_keyword(
keywords: Set[str],
rule: Optional[Union[Rule, T_RuleChecker]] = None,
@@ -337,24 +313,17 @@ def on_keyword(
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。
:参数:
* ``keywords: Set[str]``: 关键词列表
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
keywords: 关键词列表
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
return on_message(keyword(*keywords) & rule, **kwargs, _depth=_depth + 1)
@@ -367,27 +336,20 @@ def on_command(
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`_
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
cmd: 指定命令内容
rule: 事件响应规则
aliases: 命令别名
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
commands = set([cmd]) | (aliases or set())
@@ -406,30 +368,23 @@ def on_shell_command(
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个支持 `shell_like` 解析参数的命令消息事件响应器。
注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器
与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息
与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。
并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]` 中
并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
cmd: 指定命令内容
rule: 事件响应规则
aliases: 命令别名
parser: `nonebot.rule.ArgumentParser` 对象
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
commands = set([cmd]) | (aliases or set())
@@ -448,27 +403,20 @@ def on_regex(
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`_
:参数:
* ``pattern: str``: 正则表达式
* ``flags: Union[int, re.RegexFlag]``: 正则匹配标志
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
pattern: 正则表达式
flags: 正则匹配标志
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
return on_message(regex(pattern, flags) & rule, **kwargs, _depth=_depth + 1)
@@ -478,38 +426,28 @@ class CommandGroup:
def __init__(self, cmd: Union[str, Tuple[str, ...]], **kwargs):
"""
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 命令前缀
* ``**kwargs``: 其他传递给 ``on_command`` 的参数默认值,参考 `on_command <#on-command-cmd-rule-none-aliases-none-kwargs>`_
参数:
cmd: 命令前缀
**kwargs: `on_command` 的参数默认值,参考 `on_command <#on-command-cmd-rule-none-aliases-none-kwargs>`_
"""
self.basecmd: Tuple[str, ...] = (cmd,) if isinstance(cmd, str) else cmd
"""
- **类型**: ``Tuple[str, ...]``
- **说明**: 命令前缀
命令前缀
"""
if "aliases" in kwargs:
del kwargs["aliases"]
self.base_kwargs: Dict[str, Any] = kwargs
"""
- **类型**: ``Dict[str, Any]``
- **说明**: 其他传递给 ``on_command`` 的参数默认值
其他传递给 `on_command` 的参数默认值
"""
def command(self, cmd: Union[str, Tuple[str, ...]], **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个新的命令。
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 命令前缀
* ``**kwargs``: 其他传递给 ``on_command`` 的参数,将会覆盖命令组默认值
:返回:
- ``Type[Matcher]``
参数:
cmd: 命令前缀
**kwargs: `on_command` 的参数,将会覆盖命令组默认值
"""
sub_cmd = (cmd,) if isinstance(cmd, str) else cmd
cmd = self.basecmd + sub_cmd
@@ -522,18 +460,11 @@ class CommandGroup:
self, cmd: Union[str, Tuple[str, ...]], **kwargs
) -> Type[Matcher]:
"""
:说明:
注册一个新的命令。
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 命令前缀
* ``**kwargs``: 其他传递给 ``on_shell_command`` 的参数,将会覆盖命令组默认值
:返回:
- ``Type[Matcher]``
参数:
cmd: 命令前缀
**kwargs: `on_shell_command` 的参数,将会覆盖命令组默认值
"""
sub_cmd = (cmd,) if isinstance(cmd, str) else cmd
cmd = self.basecmd + sub_cmd
@@ -544,45 +475,34 @@ class CommandGroup:
class MatcherGroup:
"""事件响应器组合,统一管理。为 ``Matcher`` 创建提供默认属性。"""
"""事件响应器组合,统一管理。为 `Matcher` 创建提供默认属性。"""
def __init__(self, **kwargs):
"""
:说明:
创建一个事件响应器组合,参数为默认值,与 ``on`` 一致
创建一个事件响应器组合,参数为默认值,与 `on` 一致
"""
self.matchers: List[Type[Matcher]] = []
"""
:类型: ``List[Type[Matcher]]``
:说明: 组内事件响应器列表
组内事件响应器列表
"""
self.base_kwargs: Dict[str, Any] = kwargs
"""
- **类型**: ``Dict[str, Any]``
- **说明**: 其他传递给 ``on`` 的参数默认值
其他传递给 `on` 的参数默认值
"""
def on(self, **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个基础事件响应器,可自定义类型。
:参数:
* ``type: str``: 事件响应器类型
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
type: 事件响应器类型
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -592,22 +512,15 @@ class MatcherGroup:
def on_metaevent(self, **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个元事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -619,23 +532,16 @@ class MatcherGroup:
def on_message(self, **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -646,22 +552,15 @@ class MatcherGroup:
def on_notice(self, **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个通知事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -672,22 +571,15 @@ class MatcherGroup:
def on_request(self, **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个请求事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
rule: 事件响应规则
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -700,25 +592,18 @@ class MatcherGroup:
self, msg: Union[str, Tuple[str, ...]], **kwargs
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容
* ``ignorecase: bool``: 是否忽略大小写
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
msg: 指定消息开头内容
ignorecase: 是否忽略大小写
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -729,25 +614,18 @@ class MatcherGroup:
def on_endswith(self, msg: Union[str, Tuple[str, ...]], **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容
* ``ignorecase: bool``: 是否忽略大小写
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
msg: 指定消息结尾内容
ignorecase: 是否忽略大小写
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -756,26 +634,41 @@ class MatcherGroup:
self.matchers.append(matcher)
return matcher
def on_fullmatch(self, msg: Union[str, Tuple[str, ...]], **kwargs) -> Type[Matcher]:
"""
注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。
参数:
msg: 指定消息全匹配内容
rule: 事件响应规则
ignorecase: 是否忽略大小写
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
final_kwargs.pop("type", None)
matcher = on_fullmatch(msg, **final_kwargs, _depth=1)
self.matchers.append(matcher)
return matcher
def on_keyword(self, keywords: Set[str], **kwargs) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。
:参数:
* ``keywords: Set[str]``: 关键词列表
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
keywords: 关键词列表
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -791,27 +684,20 @@ class MatcherGroup:
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`_
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
cmd: 指定命令内容
aliases: 命令别名
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -828,30 +714,23 @@ class MatcherGroup:
**kwargs,
) -> Type[Matcher]:
"""
:说明:
注册一个支持 `shell_like` 解析参数的命令消息事件响应器。
注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器
与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息
与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。
并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]` 中
并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
cmd: 指定命令内容
aliases: 命令别名
parser: `nonebot.rule.ArgumentParser` 对象
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)
@@ -866,27 +745,20 @@ class MatcherGroup:
self, pattern: str, flags: Union[int, re.RegexFlag] = 0, **kwargs
) -> Type[Matcher]:
"""
:说明:
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`_
:参数:
* ``pattern: str``: 正则表达式
* ``flags: Union[int, re.RegexFlag]``: 正则匹配标志
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Union[Permission, T_PermissionChecker]] =]]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Dependent]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
:返回:
- ``Type[Matcher]``
参数:
pattern: 正则表达式
flags: 正则匹配标志
rule: 事件响应规则
permission: 事件响应权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器(仅执行一次)
priority: 事件响应器优先级
block: 是否阻止事件向更低优先级传递
state: 默认 state
"""
final_kwargs = self.base_kwargs.copy()
final_kwargs.update(kwargs)

View File

@@ -5,12 +5,7 @@ from nonebot.matcher import Matcher
from nonebot.permission import Permission
from nonebot.dependencies import Dependent
from nonebot.rule import Rule, ArgumentParser
from nonebot.typing import (
T_State,
T_Handler,
T_RuleChecker,
T_PermissionChecker,
)
from nonebot.typing import T_State, T_Handler, T_RuleChecker, T_PermissionChecker
def on(
type: str = "",
@@ -62,7 +57,7 @@ def on_request(
) -> Type[Matcher]: ...
def on_startswith(
msg: Union[str, Tuple[str, ...]],
rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ...,
rule: Optional[Union[Rule, T_RuleChecker]] = ...,
ignorecase: bool = ...,
*,
permission: Optional[Union[Permission, T_PermissionChecker]] = ...,
@@ -74,7 +69,19 @@ def on_startswith(
) -> Type[Matcher]: ...
def on_endswith(
msg: Union[str, Tuple[str, ...]],
rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ...,
rule: Optional[Union[Rule, T_RuleChecker]] = ...,
ignorecase: bool = ...,
*,
permission: Optional[Union[Permission, T_PermissionChecker]] = ...,
handlers: Optional[List[Union[T_Handler, Dependent]]] = ...,
temp: bool = ...,
priority: int = ...,
block: bool = ...,
state: Optional[T_State] = ...,
) -> Type[Matcher]: ...
def on_fullmatch(
msg: Union[str, Tuple[str, ...]],
rule: Optional[Union[Rule, T_RuleChecker]] = ...,
ignorecase: bool = ...,
*,
permission: Optional[Union[Permission, T_PermissionChecker]] = ...,
@@ -266,6 +273,19 @@ class MatcherGroup:
block: bool = ...,
state: Optional[T_State] = ...,
) -> Type[Matcher]: ...
def on_fullmatch(
self,
msg: Union[str, Tuple[str, ...]],
*,
ignorecase: bool = ...,
rule: Optional[Union[Rule, T_RuleChecker]] = ...,
permission: Optional[Union[Permission, T_PermissionChecker]] = ...,
handlers: Optional[List[Union[T_Handler, Dependent]]] = ...,
temp: bool = ...,
priority: int = ...,
block: bool = ...,
state: Optional[T_State] = ...,
) -> Type[Matcher]: ...
def on_keyword(
self,
keywords: Set[str],

View File

@@ -1,100 +1,57 @@
"""本模块定义插件对象。
FrontMatter:
sidebar_position: 3
description: nonebot.plugin.plugin 模块
"""
from types import ModuleType
from dataclasses import field, dataclass
from typing import TYPE_CHECKING, Set, Dict, Type, Optional
from typing import TYPE_CHECKING, Any, Set, Dict, Type, Optional
from pydantic import BaseModel
from nonebot.matcher import Matcher
from .export import Export
from nonebot.matcher import Matcher
from . import _plugins as plugins # FIXME: backport for nonebug
if TYPE_CHECKING:
from .manager import PluginManager
plugins: Dict[str, "Plugin"] = {}
"""
:类型: ``Dict[str, Plugin]``
:说明: 已加载的插件
"""
@dataclass(eq=False)
class PluginMetadata:
"""插件元信息,由插件编写者提供"""
name: str
"""插件可阅读名称"""
description: str
"""插件功能介绍"""
usage: str
"""插件使用方法"""
config: Optional[Type[BaseModel]] = None
"""插件配置项"""
extra: Dict[Any, Any] = field(default_factory=dict)
@dataclass(eq=False)
class Plugin(object):
class Plugin:
"""存储插件信息"""
name: str
"""
- **类型**: ``str``
- **说明**: 插件名称,使用 文件/文件夹 名称作为插件名
"""
"""插件索引标识NoneBot 使用 文件/文件夹 名称作为标识符"""
module: ModuleType
"""
- **类型**: ``ModuleType``
- **说明**: 插件模块对象
"""
"""插件模块对象"""
module_name: str
"""
- **类型**: ``str``
- **说明**: 点分割模块路径
"""
"""点分割模块路径"""
manager: "PluginManager"
"""
- **类型**: ``PluginManager``
- **说明**: 导入该插件的插件管理器
"""
"""导入该插件的插件管理器"""
export: Export = field(default_factory=Export)
"""
- **类型**: ``Export``
- **说明**: 插件内定义的导出内容
"""
"""**Deprecated:** 插件内定义的导出内容"""
matcher: Set[Type[Matcher]] = field(default_factory=set)
"""
- **类型**: ``Set[Type[Matcher]]``
- **说明**: 插件内定义的 ``Matcher``
"""
"""插件内定义的 `Matcher`"""
parent_plugin: Optional["Plugin"] = None
"""
- **类型**: ``Optional[Plugin]``
- **说明**: 父插件
"""
"""父插件"""
sub_plugins: Set["Plugin"] = field(default_factory=set)
"""
- **类型**: ``Set[Plugin]``
- **说明**: 子插件集合
"""
def get_plugin(name: str) -> Optional[Plugin]:
"""
:说明:
获取当前导入的某个插件。
:参数:
* ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。
:返回:
- ``Optional[Plugin]``
"""
return plugins.get(name)
def get_loaded_plugins() -> Set[Plugin]:
"""
:说明:
获取当前已导入的所有插件。
:返回:
- ``Set[Plugin]``
"""
return set(plugins.values())
def _new_plugin(fullname: str, module: ModuleType, manager: "PluginManager") -> Plugin:
name = fullname.rsplit(".", 1)[-1] if "." in fullname else fullname
if name in plugins:
raise RuntimeError("Plugin already exists! Check your plugin name.")
plugin = Plugin(name, module, fullname, manager)
plugins[name] = plugin
return plugin
"""子插件集合"""
metadata: Optional[PluginMetadata] = None

View File

@@ -1,34 +1,31 @@
from typing import Dict
from typing import Dict, AsyncGenerator
from nonebot.adapters import Event
from nonebot.message import (
IgnoredException,
run_preprocessor,
run_postprocessor,
)
from nonebot.params import Depends
from nonebot.message import IgnoredException, event_preprocessor
_running_matcher: Dict[str, int] = {}
@run_preprocessor
async def preprocess(event: Event):
async def matcher_mutex(event: Event) -> AsyncGenerator[bool, None]:
result = False
try:
session_id = event.get_session_id()
except Exception:
return
yield result
else:
current_event_id = id(event)
event_id = _running_matcher.get(session_id, None)
if event_id and event_id != current_event_id:
raise IgnoredException("Another matcher running")
if event_id:
result = event_id != current_event_id
else:
_running_matcher[session_id] = current_event_id
@run_postprocessor
async def postprocess(event: Event):
try:
session_id = event.get_session_id()
except Exception:
return
if session_id in _running_matcher:
yield result
if not result:
del _running_matcher[session_id]
@event_preprocessor
async def preprocess(mutex: bool = Depends(matcher_mutex)):
if mutex:
raise IgnoredException("Another matcher running")

View File

@@ -1,32 +1,37 @@
r"""
规则
====
"""本模块是 {ref}`nonebot.matcher.Matcher.rule` 的类型定义。
每个事件响应器 ``Matcher`` 拥有一个匹配规则 ``Rule`` ,其中是 ``RuleChecker`` 的集合,只有当所有 ``RuleChecker`` 检查结果为 ``True`` 时继续运行。
每个事件响应器 {ref}`nonebot.matcher.Matcher` 拥有一个匹配规则 {ref}`nonebot.rule.Rule`
其中是 `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
\:\:\:tip 提示
``RuleChecker`` 既可以是 async function 也可以是 sync function
\:\:\:
FrontMatter:
sidebar_position: 5
description: nonebot.rule 模块
"""
import re
import shlex
import asyncio
from itertools import product
from argparse import Namespace
from contextlib import AsyncExitStack
from typing_extensions import TypedDict
from argparse import ArgumentParser as ArgParser
from typing import Any, Set, List, Tuple, Union, NoReturn, Optional, Sequence
from typing import Any, List, Tuple, Union, Optional, Sequence, NamedTuple
from pygtrie import CharTrie
from nonebot import get_driver
from nonebot.log import logger
from nonebot.dependencies import Dependent
from nonebot.exception import ParserExit, SkippedException
from nonebot.typing import T_State
from nonebot.exception import ParserExit
from nonebot.internal.rule import Rule as Rule
from nonebot.adapters import Bot, Event, Message, MessageSegment
from nonebot.typing import T_State, T_RuleChecker, T_DependencyCache
from nonebot.params import (
Command,
EventToMe,
EventType,
CommandArg,
EventMessage,
EventPlainText,
)
from nonebot.consts import (
CMD_KEY,
PREFIX_KEY,
@@ -36,21 +41,9 @@ from nonebot.consts import (
CMD_ARG_KEY,
RAW_CMD_KEY,
REGEX_GROUP,
CMD_START_KEY,
REGEX_MATCHED,
)
from nonebot.params import (
State,
Command,
BotParam,
EventToMe,
EventType,
EventParam,
StateParam,
DependParam,
DefaultParam,
EventMessage,
EventPlainText,
)
CMD_RESULT = TypedDict(
"CMD_RESULT",
@@ -58,122 +51,20 @@ CMD_RESULT = TypedDict(
"command": Optional[Tuple[str, ...]],
"raw_command": Optional[str],
"command_arg": Optional[Message[MessageSegment]],
"command_start": Optional[str],
},
)
class Rule:
"""
:说明:
``Matcher`` 规则类,当事件传递时,在 ``Matcher`` 运行前进行检查。
:示例:
.. code-block:: python
Rule(async_function) & sync_function
# 等价于
from nonebot.utils import run_sync
Rule(async_function, run_sync(sync_function))
"""
__slots__ = ("checkers",)
HANDLER_PARAM_TYPES = [
DependParam,
BotParam,
EventParam,
StateParam,
DefaultParam,
]
def __init__(self, *checkers: Union[T_RuleChecker, Dependent[bool]]) -> None:
"""
:参数:
* ``*checkers: Union[T_RuleChecker, Dependent[bool]]``: RuleChecker
"""
self.checkers: Set[Dependent[bool]] = set(
checker
if isinstance(checker, Dependent)
else Dependent[bool].parse(
call=checker, allow_types=self.HANDLER_PARAM_TYPES
)
for checker in checkers
)
"""
:说明:
存储 ``RuleChecker``
:类型:
* ``Set[Dependent[bool]]``
"""
async def __call__(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""
:说明:
检查是否符合所有规则
:参数:
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
* ``state: T_State``: 当前 State
* ``stack: Optional[AsyncExitStack]``: 异步上下文栈
* ``dependency_cache: Optional[CacheDict[T_Handler, Any]]``: 依赖缓存
:返回:
- ``bool``
"""
if not self.checkers:
return True
try:
results = await asyncio.gather(
*(
checker(
bot=bot,
event=event,
state=state,
stack=stack,
dependency_cache=dependency_cache,
)
for checker in self.checkers
)
)
except SkippedException:
return False
return all(results)
def __and__(self, other: Optional[Union["Rule", T_RuleChecker]]) -> "Rule":
if other is None:
return self
elif isinstance(other, Rule):
return Rule(*self.checkers, *other.checkers)
else:
return Rule(*self.checkers, other)
def __or__(self, other) -> NoReturn:
raise RuntimeError("Or operation between rules is not allowed.")
TRIE_VALUE = NamedTuple(
"TRIE_VALUE", [("command_start", str), ("command", Tuple[str, ...])]
)
class TrieRule:
prefix: CharTrie = CharTrie()
@classmethod
def add_prefix(cls, prefix: str, value: Any):
def add_prefix(cls, prefix: str, value: TRIE_VALUE) -> None:
if prefix in cls.prefix:
logger.warning(f'Duplicated prefix rule "{prefix}"')
return
@@ -181,7 +72,9 @@ class TrieRule:
@classmethod
def get_value(cls, bot: Bot, event: Event, state: T_State) -> CMD_RESULT:
prefix = CMD_RESULT(command=None, raw_command=None, command_arg=None)
prefix = CMD_RESULT(
command=None, raw_command=None, command_arg=None, command_start=None
)
state[PREFIX_KEY] = prefix
if event.get_type() != "message":
return prefix
@@ -191,9 +84,11 @@ class TrieRule:
if message_seg.is_text():
segment_text = str(message_seg).lstrip()
pf = cls.prefix.longest_prefix(segment_text)
if pf:
value: TRIE_VALUE = pf.value
prefix[RAW_CMD_KEY] = pf.key
prefix[CMD_KEY] = pf.value
if pf.key:
prefix[CMD_START_KEY] = value.command_start
prefix[CMD_KEY] = value.command
msg = message.copy()
msg.pop(0)
new_message = msg.__class__(segment_text[len(pf.key) :].lstrip())
@@ -205,6 +100,15 @@ class TrieRule:
class StartswithRule:
"""检查消息纯文本是否以指定字符串开头。
参数:
msg: 指定消息开头字符串元组
ignorecase: 是否忽略大小写
"""
__slots__ = ("msg", "ignorecase")
def __init__(self, msg: Tuple[str, ...], ignorecase: bool = False):
self.msg = msg
self.ignorecase = ignorecase
@@ -224,14 +128,11 @@ class StartswithRule:
def startswith(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule:
"""
:说明:
"""匹配消息纯文本开头。
匹配消息开头
:参数:
* ``msg: str``: 消息开头字符串
参数:
msg: 指定消息开头字符串元组
ignorecase: 是否忽略大小写
"""
if isinstance(msg, str):
msg = (msg,)
@@ -240,6 +141,15 @@ def startswith(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Ru
class EndswithRule:
"""检查消息纯文本是否以指定字符串结尾。
参数:
msg: 指定消息结尾字符串元组
ignorecase: 是否忽略大小写
"""
__slots__ = ("msg", "ignorecase")
def __init__(self, msg: Tuple[str, ...], ignorecase: bool = False):
self.msg = msg
self.ignorecase = ignorecase
@@ -259,14 +169,11 @@ class EndswithRule:
def endswith(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule:
"""
:说明:
"""匹配消息纯文本结尾。
匹配消息结尾
:参数:
* ``msg: str``: 消息结尾字符串
参数:
msg: 指定消息开头字符串元组
ignorecase: 是否忽略大小写
"""
if isinstance(msg, str):
msg = (msg,)
@@ -274,7 +181,51 @@ def endswith(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule
return Rule(EndswithRule(msg, ignorecase))
class FullmatchRule:
"""检查消息纯文本是否与指定字符串全匹配。
参数:
msg: 指定消息全匹配字符串元组
ignorecase: 是否忽略大小写
"""
__slots__ = ("msg", "ignorecase")
def __init__(self, msg: Tuple[str, ...], ignorecase: bool = False):
self.msg = frozenset(map(str.casefold, msg) if ignorecase else msg)
self.ignorecase = ignorecase
async def __call__(
self, type_: str = EventType(), text: str = EventPlainText()
) -> bool:
return (
type_ == "message"
and (text.casefold() if self.ignorecase else text) in self.msg
)
def fullmatch(msg: Union[str, Tuple[str, ...]], ignorecase: bool = False) -> Rule:
"""完全匹配消息。
参数:
msg: 指定消息全匹配字符串元组
ignorecase: 是否忽略大小写
"""
if isinstance(msg, str):
msg = (msg,)
return Rule(FullmatchRule(msg, ignorecase))
class KeywordsRule:
"""检查消息纯文本是否包含指定关键字。
参数:
keywords: 指定关键字元组
"""
__slots__ = ("keywords",)
def __init__(self, *keywords: str):
self.keywords = keywords
@@ -287,20 +238,24 @@ class KeywordsRule:
def keyword(*keywords: str) -> Rule:
"""
:说明:
"""匹配消息纯文本关键词。
匹配消息关键词
:参数:
* ``*keywords: str``: 关键词
参数:
keywords: 指定关键字元组
"""
return Rule(KeywordsRule(*keywords))
class CommandRule:
"""检查消息是否为指定命令。
参数:
cmds: 指定命令元组列表
"""
__slots__ = ("cmds",)
def __init__(self, cmds: List[Tuple[str, ...]]):
self.cmds = cmds
@@ -312,27 +267,27 @@ class CommandRule:
def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule:
r"""
:说明:
"""匹配消息命令。
命令形式匹配,根据配置里提供的 ``command_start``, ``command_sep`` 判断消息是否为命令。
根据配置里提供的 {ref}``command_start` <nonebot.config.Config.command_start>`,
{ref}``command_sep` <nonebot.config.Config.command_sep>` 判断消息是否为命令。
可以通过 ``state["_prefix"]["command"]`` 获取匹配成功的命令(例:``("test",)``),通过 ``state["_prefix"]["raw_command"]`` 获取匹配成功的原始命令文本(例:``"/test"``
可以通过 {ref}`nonebot.params.Command` 获取匹配成功的命令(例: `("test",)`
通过 {ref}`nonebot.params.RawCommand` 获取匹配成功的原始命令文本(例: `"/test"`
通过 {ref}`nonebot.params.CommandArg` 获取匹配成功的命令参数。
:参数:
参数:
cmds: 命令文本或命令元组
* ``*cmds: Union[str, Tuple[str, ...]]``: 命令内容
用法:
使用默认 `command_start`, `command_sep` 配置
:示例:
命令 `("test",)` 可以匹配: `/test` 开头的消息
命令 `("test", "sub")` 可以匹配: `/test.sub` 开头的消息
使用默认 ``command_start``, ``command_sep`` 配置
命令 ``("test",)`` 可以匹配:``/test`` 开头的消息
命令 ``("test", "sub")`` 可以匹配”``/test.sub`` 开头的消息
\:\:\:tip 提示
命令内容与后续消息间无需空格!
\:\:\:
:::tip 提示
命令内容与后续消息间无需空格!
:::
"""
config = get_driver().config
@@ -347,19 +302,22 @@ def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule:
if len(command) == 1:
for start in command_start:
TrieRule.add_prefix(f"{start}{command[0]}", command)
TrieRule.add_prefix(f"{start}{command[0]}", TRIE_VALUE(start, command))
else:
for start, sep in product(command_start, command_sep):
TrieRule.add_prefix(f"{start}{sep.join(command)}", command)
TrieRule.add_prefix(
f"{start}{sep.join(command)}", TRIE_VALUE(start, command)
)
return Rule(CommandRule(commands))
class ArgumentParser(ArgParser):
"""
:说明:
"""`shell_like` 命令参数解析器,解析出错时不会退出程序。
``shell_like`` 命令参数解析器,解析出错时不会退出程序。
用法:
用法与 `argparse.ArgumentParser` 相同,
参考文档: [argparse](https://docs.python.org/3/library/argparse.html)
"""
def _print_message(self, message, file=None):
@@ -384,20 +342,28 @@ class ArgumentParser(ArgParser):
class ShellCommandRule:
"""检查消息是否为指定 shell 命令。
参数:
cmds: 指定命令元组列表
parser: 可选参数解析器
"""
__slots__ = ("cmds", "parser")
def __init__(self, cmds: List[Tuple[str, ...]], parser: Optional[ArgumentParser]):
self.cmds = cmds
self.parser = parser
async def __call__(
self,
state: T_State,
cmd: Optional[Tuple[str, ...]] = Command(),
msg: Message = EventMessage(),
state: T_State = State(),
msg: Optional[Message] = CommandArg(),
) -> bool:
if cmd in self.cmds:
if cmd in self.cmds and msg is not None:
message = str(msg)
strip_message = message[len(state[PREFIX_KEY][RAW_CMD_KEY]) :].lstrip()
state[SHELL_ARGV] = shlex.split(strip_message)
state[SHELL_ARGV] = shlex.split(message)
if self.parser:
try:
args = self.parser.parse_args(state[SHELL_ARGV])
@@ -412,38 +378,40 @@ class ShellCommandRule:
def shell_command(
*cmds: Union[str, Tuple[str, ...]], parser: Optional[ArgumentParser] = None
) -> Rule:
r"""
:说明:
"""匹配 `shell_like` 形式的消息命令。
支持 ``shell_like`` 解析参数的命令形式匹配,根据配置里提供的 ``command_start``, ``command_sep`` 判断消息是否为命令。
根据配置里提供的 {ref}``command_start` <nonebot.config.Config.command_start>`,
{ref}``command_sep` <nonebot.config.Config.command_sep>` 判断消息是否为命令。
可以通过 ``state["_prefix"]["command"]`` 获取匹配成功的命令(例:``("test",)``),通过 ``state["_prefix"]["raw_command"]`` 获取匹配成功的原始命令文本(例:``"/test"``
可以通过 {ref}`nonebot.params.Command` 获取匹配成功的命令(例: `("test",)`
通过 {ref}`nonebot.params.RawCommand` 获取匹配成功的原始命令文本(例: `"/test"`
通过 {ref}`nonebot.params.ShellCommandArgv` 获取解析前的参数列表(例: `["arg", "-h"]`
通过 {ref}`nonebot.params.ShellCommandArgs` 获取解析后的参数字典(例: `{"arg": "arg", "h": True}`)。
可以通过 ``state["argv"]`` 获取用户输入的原始参数列表
:::warning 警告
如果参数解析失败,则通过 {ref}`nonebot.params.ShellCommandArgs`
获取的将是 {ref}`nonebot.exception.ParserExit` 异常。
:::
添加 ``parser`` 参数后, 可以自动处理消息并将结果保存在 ``state["args"]`` 中。
参数:
cmds: 命令文本或命令元组
parser: {ref}`nonebot.rule.ArgumentParser` 对象
:参数:
* ``*cmds: Union[str, Tuple[str, ...]]``: 命令内容
* ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象
:示例:
使用默认 ``command_start``, ``command_sep`` 配置,更多示例参考 ``argparse`` 标准库文档。
.. code-block:: python
用法:
使用默认 `command_start`, `command_sep` 配置,更多示例参考 `argparse` 标准库文档。
```python
from nonebot.rule import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-a", action="store_true")
rule = shell_command("ls", parser=parser)
```
\:\:\:tip 提示
命令内容与后续消息间无需空格
\:\:\:
:::tip 提示
命令内容与后续消息间无需空格!
:::
"""
if parser is not None and not isinstance(parser, ArgumentParser):
raise TypeError("`parser` must be an instance of nonebot.rule.ArgumentParser")
@@ -460,24 +428,35 @@ def shell_command(
if len(command) == 1:
for start in command_start:
TrieRule.add_prefix(f"{start}{command[0]}", command)
TrieRule.add_prefix(f"{start}{command[0]}", TRIE_VALUE(start, command))
else:
for start, sep in product(command_start, command_sep):
TrieRule.add_prefix(f"{start}{sep.join(command)}", command)
TrieRule.add_prefix(
f"{start}{sep.join(command)}", TRIE_VALUE(start, command)
)
return Rule(ShellCommandRule(commands, parser))
class RegexRule:
"""检查消息字符串是否符合指定正则表达式。
参数:
regex: 正则表达式
flags: 正则表达式标记
"""
__slots__ = ("regex", "flags")
def __init__(self, regex: str, flags: int = 0):
self.regex = regex
self.flags = flags
async def __call__(
self,
state: T_State,
type: str = EventType(),
msg: Message = EventMessage(),
state: T_State = State(),
) -> bool:
if type != "message":
return False
@@ -492,41 +471,47 @@ class RegexRule:
def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule:
r"""
:说明:
"""匹配符合正则表达式的消息字符串。
根据正则表达式进行匹配。
可以通过 {ref}`nonebot.params.RegexMatched` 获取匹配成功的字符串,
通过 {ref}`nonebot.params.RegexGroup` 获取匹配成功的 group 元组,
通过 {ref}`nonebot.params.RegexDict` 获取匹配成功的 group 字典。
可以通过 ``state["_matched"]`` ``state["_matched_groups"]`` ``state["_matched_dict"]``
获取正则表达式匹配成功的文本。
参数:
regex: 正则表达式
flags: 正则表达式标记
:参数:
:::tip 提示
正则表达式匹配使用 search 而非 match如需从头匹配请使用 `r"^xxx"` 来确保匹配开头
:::
* ``regex: str``: 正则表达式
* ``flags: Union[int, re.RegexFlag]``: 正则标志
\:\:\:tip 提示
正则表达式匹配使用 search 而非 match如需从头匹配请使用 ``r"^xxx"`` 来确保匹配开头
\:\:\:
:::tip 提示
正则表达式匹配使用 `EventMessage` 的 `str` 字符串,而非 `EventMessage` 的 `PlainText` 纯文本字符串
:::
"""
return Rule(RegexRule(regex, flags))
class ToMeRule:
"""检查事件是否与机器人有关。"""
__slots__ = ()
async def __call__(self, to_me: bool = EventToMe()) -> bool:
return to_me
def to_me() -> Rule:
"""
:说明:
通过 ``event.is_tome()`` 判断事件是否与机器人有关
:参数:
* 无
"""
"""匹配与机器人有关的事件。"""
return Rule(ToMeRule())
__autodoc__ = {
"Rule": True,
"Rule.__call__": True,
"TrieRule": False,
"ArgumentParser.exit": False,
"ArgumentParser.parse_args": False,
}

View File

@@ -1,21 +1,15 @@
"""
类型
====
"""本模块定义了 NoneBot 模块中共享的一些类型。
下面的文档中,「类型」部分使用 Python 的 Type Hint 语法,见 `PEP 484`_、`PEP 526`_ 和 `typing`_。
下面的文档中,「类型」部分使用 Python 的 Type Hint 语法,
参考 [`PEP 484`](https://www.python.org/dev/peps/pep-0484/),
[`PEP 526`](https://www.python.org/dev/peps/pep-0526/) 和
[`typing`](https://docs.python.org/3/library/typing.html)。
除了 Python 内置的类型,下面还出现了如下 NoneBot 自定类型,实际上它们是 Python 内置类型的别名。
以下类型均可从 nonebot.typing 模块导入。
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
.. _PEP 526:
https://www.python.org/dev/peps/pep-0526/
.. _typing:
https://docs.python.org/3/library/typing.html
FrontMatter:
sidebar_position: 11
description: nonebot.typing 模块
"""
from typing import (
TYPE_CHECKING,
@@ -31,13 +25,15 @@ from typing import (
if TYPE_CHECKING:
from asyncio import Task
from nonebot.adapters import Bot, Event
from nonebot.adapters import Bot
from nonebot.permission import Permission
T_Wrapped = TypeVar("T_Wrapped", bound=Callable)
def overrides(InterfaceClass: object):
def overrides(InterfaceClass: object) -> Callable[[T_Wrapped], T_Wrapped]:
"""标记一个方法为父类 interface 的 implement"""
def overrider(func: T_Wrapped) -> T_Wrapped:
assert func.__name__ in dir(InterfaceClass), f"Error method: {func.__name__}"
return func
@@ -46,194 +42,128 @@ def overrides(InterfaceClass: object):
T_State = Dict[Any, Any]
"""事件处理状态 State 类型"""
T_BotConnectionHook = Callable[..., Awaitable[Any]]
"""Bot 连接建立时钩子函数
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- DefaultParam: 带有默认值的参数
"""
:类型: ``Dict[Any, Any]``
T_BotDisconnectionHook = Callable[..., Awaitable[Any]]
"""Bot 连接断开时钩子函数
:说明:
依赖参数:
事件处理状态 State 类型
"""
T_BotConnectionHook = Callable[["Bot"], Awaitable[None]]
"""
:类型: ``Callable[[Bot], Awaitable[None]]``
:说明:
Bot 连接建立时执行的函数
"""
T_BotDisconnectionHook = Callable[["Bot"], Awaitable[None]]
"""
:类型: ``Callable[[Bot], Awaitable[None]]``
:说明:
Bot 连接断开时执行的函数
"""
T_CallingAPIHook = Callable[["Bot", str, Dict[str, Any]], Awaitable[None]]
"""
:类型: ``Callable[[Bot, str, Dict[str, Any]], Awaitable[None]]``
:说明:
``bot.call_api`` 时执行的函数
- DependParam: 子依赖参数
- BotParam: Bot 对象
- DefaultParam: 带有默认值的参数
"""
T_CallingAPIHook = Callable[["Bot", str, Dict[str, Any]], Awaitable[Any]]
"""`bot.call_api` 钩子函数"""
T_CalledAPIHook = Callable[
["Bot", Optional[Exception], str, Dict[str, Any], Any], Awaitable[None]
["Bot", Optional[Exception], str, Dict[str, Any], Any], Awaitable[Any]
]
"""`bot.call_api` 后执行的函数,参数分别为 bot, exception, api, data, result"""
T_EventPreProcessor = Callable[..., Union[Any, Awaitable[Any]]]
"""事件预处理函数 EventPreProcessor 类型
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- DefaultParam: 带有默认值的参数
"""
:类型: ``Callable[[Bot, Optional[Exception], str, Dict[str, Any], Any], Awaitable[None]]``
T_EventPostProcessor = Callable[..., Union[Any, Awaitable[Any]]]
"""事件预处理函数 EventPostProcessor 类型
:说明:
依赖参数:
``bot.call_api`` 后执行的函数,参数分别为 bot, exception, api, data, result
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- DefaultParam: 带有默认值的参数
"""
T_RunPreProcessor = Callable[..., Union[Any, Awaitable[Any]]]
"""事件响应器运行前预处理函数 RunPreProcessor 类型
T_EventPreProcessor = Callable[..., Union[None, Awaitable[None]]]
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- DefaultParam: 带有默认值的参数
"""
:类型: ``Callable[..., Union[None, Awaitable[None]]]``
T_RunPostProcessor = Callable[..., Union[Any, Awaitable[Any]]]
"""事件响应器运行前预处理函数 RunPostProcessor 类型
:依赖参数:
依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
事件预处理函数 EventPreProcessor 类型
"""
T_EventPostProcessor = Callable[..., Union[None, Awaitable[None]]]
"""
:类型: ``Callable[..., Union[None, Awaitable[None]]]``
:依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
事件预处理函数 EventPostProcessor 类型
"""
T_RunPreProcessor = Callable[..., Union[None, Awaitable[None]]]
"""
:类型: ``Callable[..., Union[None, Awaitable[None]]]``
:依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``MatcherParam``: Matcher 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
事件响应器运行前预处理函数 RunPreProcessor 类型
"""
T_RunPostProcessor = Callable[..., Union[None, Awaitable[None]]]
"""
:类型: ``Callable[..., Union[None, Awaitable[None]]]``
:依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``MatcherParam``: Matcher 对象
* ``ExceptionParam``: 异常对象(可能为 None
* ``DefaultParam``: 带有默认值的参数
:说明:
事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在)
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- ExceptionParam: 异常对象(可能为 None
- DefaultParam: 带有默认值的参数
"""
T_RuleChecker = Callable[..., Union[bool, Awaitable[bool]]]
"""
:类型: ``Callable[..., Union[bool, Awaitable[bool]]]``
"""RuleChecker 即判断是否响应事件的处理函数。
:依赖参数:
依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
RuleChecker 即判断是否响应事件的处理函数。
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- DefaultParam: 带有默认值的参数
"""
T_PermissionChecker = Callable[..., Union[bool, Awaitable[bool]]]
"""
:类型: ``Callable[..., Union[bool, Awaitable[bool]]]``
"""PermissionChecker 即判断事件是否满足权限的处理函数。
:依赖参数:
依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
RuleChecker 即判断是否响应消息的处理函数。
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- DefaultParam: 带有默认值的参数
"""
T_Handler = Callable[..., Any]
"""
:类型: ``Callable[..., Any]``
:说明:
Handler 处理函数。
"""
"""Handler 处理函数。"""
T_TypeUpdater = Callable[..., Union[str, Awaitable[str]]]
"""
:类型: ``Callable[..., Union[None, Awaitable[None]]]``
"""TypeUpdater 在 Matcher.pause, Matcher.reject 时被运行,用于更新响应的事件类型。默认会更新为 `message`。
:依赖参数:
依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``MatcherParam``: Matcher 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
TypeUpdater 在 Matcher.pause, Matcher.reject 时被运行,用于更新响应的事件类型。默认会更新为 ``message``。
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- DefaultParam: 带有默认值的参数
"""
T_PermissionUpdater = Callable[..., Union["Permission", Awaitable["Permission"]]]
"""
:类型: ``Callable[..., Union[Permission, Awaitable[Permission]]]``
"""PermissionUpdater 在 Matcher.pause, Matcher.reject 时被运行,用于更新会话对象权限。默认会更新为当前事件的触发对象。
:依赖参数:
依赖参数:
* ``DependParam``: 子依赖参数
* ``BotParam``: Bot 对象
* ``EventParam``: Event 对象
* ``StateParam``: State 对象
* ``MatcherParam``: Matcher 对象
* ``DefaultParam``: 带有默认值的参数
:说明:
PermissionUpdater 在 Matcher.pause, Matcher.reject 时被运行,用于更新会话对象权限。默认会更新为当前事件的触发对象。
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- DefaultParam: 带有默认值的参数
"""
T_DependencyCache = Dict[Callable[..., Any], "Task[Any]"]
"""
:类型: ``Dict[Callable[..., Any], Task[Any]]``
:说明:
依赖缓存, 用于存储依赖函数的返回值
"""
"""依赖缓存, 用于存储依赖函数的返回值"""

View File

@@ -1,3 +1,10 @@
"""本模块包含了 NoneBot 的一些工具函数
FrontMatter:
sidebar_position: 8
description: nonebot.utils 模块
"""
import re
import json
import asyncio
@@ -14,11 +21,13 @@ from typing import (
TypeVar,
Callable,
Optional,
Awaitable,
Coroutine,
AsyncGenerator,
ContextManager,
)
from pydantic.typing import is_union, is_none_type
from nonebot.log import logger
from nonebot.typing import overrides
@@ -30,18 +39,12 @@ V = TypeVar("V")
def escape_tag(s: str) -> str:
"""
:说明:
"""用于记录带颜色日志时转义 `<tag>` 类型特殊标签
用于记录带颜色日志时转义 ``<tag>`` 类型特殊标签
参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color)
:参数:
* ``s: str``: 需要转义的字符串
:返回:
- ``str``
参数:
s: 需要转义的字符串
"""
return re.sub(r"</?((?:[fb]g\s)?[^<>\s]*)>", r"\\\g<0>", s)
@@ -49,23 +52,27 @@ def escape_tag(s: str) -> str:
def generic_check_issubclass(
cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]]
) -> bool:
"""检查 cls 是否是 class_or_tuple 中的一个类型子类。
特别的,如果 cls 是 `typing.Union` 或 `types.UnionType` 类型,
则会检查其中的类型是否是 class_or_tuple 中的一个类型子类。None 会被忽略)
"""
try:
return issubclass(cls, class_or_tuple)
except TypeError:
origin = get_origin(cls)
if origin is Union:
for type_ in get_args(cls):
if type_ is not type(None) and not generic_check_issubclass(
type_, class_or_tuple
):
return False
return True
if is_union(origin):
return all(
is_none_type(type_) or generic_check_issubclass(type_, class_or_tuple)
for type_ in get_args(cls)
)
elif origin:
return issubclass(origin, class_or_tuple)
return False
def is_coroutine_callable(call: Callable[..., Any]) -> bool:
"""检查 call 是否是一个 callable 协程函数"""
if inspect.isroutine(call):
return inspect.iscoroutinefunction(call)
if inspect.isclass(call):
@@ -75,6 +82,7 @@ def is_coroutine_callable(call: Callable[..., Any]) -> bool:
def is_gen_callable(call: Callable[..., Any]) -> bool:
"""检查 call 是否是一个生成器函数"""
if inspect.isgeneratorfunction(call):
return True
func_ = getattr(call, "__call__", None)
@@ -82,25 +90,18 @@ def is_gen_callable(call: Callable[..., Any]) -> bool:
def is_async_gen_callable(call: Callable[..., Any]) -> bool:
"""检查 call 是否是一个异步生成器函数"""
if inspect.isasyncgenfunction(call):
return True
func_ = getattr(call, "__call__", None)
return inspect.isasyncgenfunction(func_)
def run_sync(call: Callable[P, R]) -> Callable[P, Awaitable[R]]:
"""
:说明:
def run_sync(call: Callable[P, R]) -> Callable[P, Coroutine[None, None, R]]:
"""一个用于包装 sync function 为 async function 的装饰器
一个用于包装 sync function 为 async function 的装饰器
:参数:
* ``call: Callable[P, R]``: 被装饰的同步函数
:返回:
- ``Callable[P, Awaitable[R]]``
参数:
call: 被装饰的同步函数
"""
@wraps(call)
@@ -117,6 +118,7 @@ def run_sync(call: Callable[P, R]) -> Callable[P, Awaitable[R]]:
async def run_sync_ctx_manager(
cm: ContextManager[T],
) -> AsyncGenerator[T, None]:
"""一个用于包装 sync context manager 为 async context manager 的执行函数"""
try:
yield await run_sync(cm.__enter__)()
except Exception as e:
@@ -127,37 +129,46 @@ async def run_sync_ctx_manager(
await run_sync(cm.__exit__)(None, None, None)
async def run_coro_with_catch(
coro: Coroutine[Any, Any, T],
exc: Tuple[Type[Exception], ...],
return_on_err: R = None,
) -> Union[T, R]:
try:
return await coro
except exc:
return return_on_err
def get_name(obj: Any) -> str:
"""获取对象的名称"""
if inspect.isfunction(obj) or inspect.isclass(obj):
return obj.__name__
return obj.__class__.__name__
class DataclassEncoder(json.JSONEncoder):
"""
:说明:
在JSON序列化 ``Message`` (List[Dataclass]) 时使用的 ``JSONEncoder``
"""
"""在JSON序列化 {re}`nonebot.adapters._message.Message` (List[Dataclass]) 时使用的 `JSONEncoder`"""
@overrides(json.JSONEncoder)
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return {f.name: getattr(o, f.name) for f in dataclasses.fields(o)}
return super().default(o)
def logger_wrapper(logger_name: str):
"""
:说明:
"""用于打印 adapter 的日志。
用于打印 adapter 的日志。
参数:
logger_name: adapter 的名称
:log 参数:
返回:
日志记录函数
* ``level: Literal["CRITICAL", "WARNING", "INFO", "DEBUG", "TRACE"]``: 日志等级
* ``message: str``: 日志信息
* ``exception: Optional[Exception]``: 异常信息
- level: 日志等级
- message: 日志信息
- exception: 异常信息
"""
def log(level: str, message: str, exception: Optional[Exception] = None):

View File

@@ -1,8 +1,9 @@
from pathlib import Path
from nonebot.drivers.fastapi import Driver
from fastapi.staticfiles import StaticFiles
from nonebot.drivers.fastapi import Driver
def register_route(driver: Driver):
app = driver.server_app

View File

@@ -17,21 +17,6 @@ nonebot2 = "^2.0.0-beta.1"
[tool.poetry.dev-dependencies]
[tool.black]
line-length = 88
target-version = ["py37", "py38", "py39"]
include = '\.pyi?$'
extend-exclude = '''
'''
[tool.isort]
profile = "black"
line_length = 80
length_sort = true
skip_gitignore = true
force_sort_within_sections = true
extra_standard_library = ["typing_extensions"]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

1634
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot2"
version = "2.0.0-beta.1"
version = "2.0.0-beta.4"
description = "An asynchronous python bot framework."
authors = ["yanyongyu <yyy@nonebot.dev>"]
license = "MIT"
@@ -24,25 +24,27 @@ include = ["nonebot/py.typed"]
[tool.poetry.dependencies]
python = "^3.7.3"
yarl = "^1.7.2"
loguru = "^0.5.1"
loguru = "^0.6.0"
pygtrie = "^2.4.1"
tomlkit = "^0.7.0"
fastapi = "^0.70.0"
fastapi = "^0.78.0"
tomlkit = ">=0.10.0,<1.0.0"
typing-extensions = ">=3.10.0,<5.0.0"
Quart = { version = "^0.16.0", optional = true }
websockets = { version=">=9.1", optional = true }
Quart = { version = "^0.17.0", optional = true }
websockets = { version="^10.0", optional = true }
pydantic = { version = "~1.9.0", extras = ["dotenv"] }
uvicorn = { version = "^0.15.0", extras = ["standard"] }
uvicorn = { version = "^0.17.0", extras = ["standard"] }
aiohttp = { version = "^3.7.4", extras = ["speedups"], optional = true }
httpx = { version = ">=0.20.0, <1.0.0", extras = ["http2"], optional = true }
[tool.poetry.dev-dependencies]
sphinx = "^4.1.1"
isort = "^5.10.1"
black = "^21.11b1"
black = "^22.1.0"
pytest-cov = "^3.0.0"
pre-commit = "^2.16.0"
pytest-xdist = "^2.5.0"
pytest-asyncio = "^0.18.1"
nonebug = { git = "https://github.com/nonebot/nonebug.git" }
sphinx-markdown-builder = { git = "https://github.com/nonebot/sphinx-markdown-builder.git" }
nb-autodoc = { git = "https://github.com/nonebot/nb-autodoc.git" }
[tool.poetry.extras]
quart = ["quart"]
@@ -57,7 +59,12 @@ all = ["quart", "aiohttp", "httpx", "websockets"]
# default = true
[tool.pytest.ini_options]
asyncio_mode = "auto"
addopts = "--cov=nonebot --cov-report=term-missing"
filterwarnings = [
"error",
"ignore::DeprecationWarning",
]
[tool.black]
line-length = 88
@@ -68,11 +75,11 @@ extend-exclude = '''
[tool.isort]
profile = "black"
line_length = 80
line_length = 88
length_sort = true
skip_gitignore = true
force_sort_within_sections = true
known_local_folder = ["nonebot"]
src_paths = ["nonebot", "tests"]
extra_standard_library = ["typing_extensions"]
[build-system]

View File

@@ -1,3 +1,5 @@
LOG_LEVEL=TRACE
NICKNAME=["test"]
SUPERUSERS=["test", "fake:faketest"]
CONFIG_FROM_ENV=
CONFIG_OVERRIDE=old

View File

@@ -1,8 +0,0 @@
[settings]
profile=black
line_length=80
length_sort=true
skip_gitignore=true
force_sort_within_sections=true
known_local_folder=plugins
extra_standard_library=typing_extensions

View File

@@ -0,0 +1,6 @@
import nonebot
plugin = nonebot.get_plugin("bad_plugin")
assert plugin
x = 1 / 0

1
tests/plugins/_hidden.py Normal file
View File

@@ -0,0 +1 @@
assert False

View File

@@ -3,4 +3,4 @@ from nonebot import export
@export()
def test():
...
return "export"

16
tests/plugins/metadata.py Normal file
View File

@@ -0,0 +1,16 @@
from pydantic import BaseModel
from nonebot.plugin import PluginMetadata
class Config(BaseModel):
custom: str = ""
__plugin_meta__ = PluginMetadata(
name="测试插件",
description="测试插件元信息",
usage="无法使用",
config=Config,
extra={"author": "NoneBot"},
)

View File

@@ -0,0 +1,6 @@
from pathlib import Path
import nonebot
_sub_plugins = set()
_sub_plugins |= nonebot.load_plugins(str((Path(__file__).parent / "plugins").resolve()))

Some files were not shown because too many files have changed in this diff Show More