Compare commits

..

490 Commits

Author SHA1 Message Date
Ju4tCode
050137fb3f 🔀 Merge pull request #194
Pre Release 2.0.0a9.post1
2021-02-05 13:41:35 +08:00
yanyongyu
f2d04c598c 📝 update doc 2021-02-05 13:34:38 +08:00
nonebot
49307a3df2 📝 update api docs 2021-02-05 05:32:52 +00:00
yanyongyu
ff9f0bc74a 📝 update doc 2021-02-05 13:31:33 +08:00
yanyongyu
f929f25abd 🔖 Pre Release 2.0.0a9.post1 2021-02-05 13:05:46 +08:00
Ju4tCode
6af0a2574d 🔀 Merge pull request #193
Fix: MatcherGroup rule override
2021-02-05 11:56:05 +08:00
nonebot
c61a159eff 📝 update api docs 2021-02-05 03:51:53 +00:00
yanyongyu
59bdd03b1e 🐛 fix rule override bug 2021-02-05 11:49:12 +08:00
yanyongyu
35ea1e78ec 📝 update readme 2021-02-03 14:47:26 +08:00
yanyongyu
7db386b752 🔖 bump version a9.post1 2021-02-03 11:29:51 +08:00
yanyongyu
e6a68feb0c 🚑 hotfix missing return when rule check failed 2021-02-03 11:23:13 +08:00
Ju4tCode
78b0450d66 🔀 Merge pull request #188
update doc
2021-02-02 22:01:49 +08:00
Ju4tCode
bd5fb46e0a 🔥 Delete yarn.lock 2021-02-02 21:56:12 +08:00
Ju4tCode
cc3ed735f1 📝 update doc 2021-02-02 21:55:18 +08:00
StarHeartHunt
3f0c3f1f37 🔧 revert e1ff0a7 and add yarn.lock 2021-02-02 20:00:49 +08:00
StarHeartHunt
e1ff0a7221 🔧 ignore yarn.lock 2021-02-02 19:45:17 +08:00
StarHeartHunt
2bf8b4d313 📝 docs grammar 2021-02-02 19:45:17 +08:00
StarHeartHunt
188aa8a50a 🎨 lint 2021-02-02 19:45:17 +08:00
StarHeart
1538d2094a 📝 Update runtime-hook.md 2021-02-02 19:44:52 +08:00
StarHeart
16eb74e88b 📝 Update scheduler.md 2021-02-02 18:32:08 +08:00
Ju4tCode
3460d445b8 🔀 Merge pull request #187
Pre Release 2.0.0a9
2021-02-02 15:00:48 +08:00
yanyongyu
461b65700f 📝 archive doc 2021-02-02 14:36:51 +08:00
yanyongyu
e809c7c500 📝 update readme 2021-02-02 13:17:29 +08:00
yanyongyu
8e0572d5d3 📝 update changelog 2021-02-02 13:13:27 +08:00
yanyongyu
7555051df6 🔖 Pre Release 2.0.0a9 2021-02-02 13:09:20 +08:00
yanyongyu
d913be5c0d 🐛 fix matcher 2021-02-02 12:48:16 +08:00
yanyongyu
98b67ad829 📝 update docstring 2021-02-02 12:39:23 +08:00
Ju4tCode
0d8e51ff3f 🔀 Merge pull request #186
New shell like command support
2021-02-02 12:20:53 +08:00
AkiraXie
223b9bc887 📝 update api docs 2021-02-02 04:16:37 +00:00
yanyongyu
a54fd2f235 💡 update docstring 2021-02-02 12:15:20 +08:00
AkiraXie
88bbb57c66 📝 update api docs 2021-02-02 04:06:57 +00:00
Ju4tCode
c9a8e7ff0d Merge branch 'dev' into master 2021-02-02 12:04:01 +08:00
yanyongyu
9e4e9f29d1 rewrite shell command 2021-02-02 11:59:14 +08:00
AkiraXie
c8ebaf38b6 📝 update api docs 2021-02-01 17:22:53 +00:00
AkiraXie
f8fb36a1f7 Support shell-like command 2021-02-02 01:20:36 +08:00
Ju4tCode
bbeeb11502 🔀 Merge pull request #179
New mah adapter
2021-02-01 21:16:20 +08:00
yanyongyu
27c6457c20 📝 update README 2021-02-01 21:11:41 +08:00
nonebot
02a780f3b0 📝 update api docs 2021-02-01 13:00:25 +00:00
yanyongyu
00858416f9 🎨 format code and bump dependency 2021-02-01 20:58:12 +08:00
nonebot
9b79c83c3d 📝 update api docs 2021-02-01 11:30:11 +00:00
Mix
d6ae1ca01c 📄 add agpl v3 license for mirai adapter 2021-02-01 19:28:56 +08:00
Mix
f446411f08 📝 add start guide for mirai adapter 2021-02-01 18:37:30 +08:00
Mix
ad3a08f514 💡 🗑️ remove some invalid comments in mirai adapter 2021-02-01 16:53:06 +08:00
nonebot
f2ab618083 📝 update api docs 2021-02-01 08:39:38 +00:00
Mix
da1218221c add specified test for mirai adapter 2021-02-01 16:38:15 +08:00
Mix
c0fa137fed 🚸 add support of rule to_me in mirai adapter 2021-02-01 16:38:15 +08:00
Mix
5a63827f22 💬 💡 rename MiraiBot to Bot, fix a comment style 2021-02-01 16:38:15 +08:00
Mix
a739e71df6 📝 update scheduler.md @StarHeartHunt (#184) 2021-02-01 14:05:55 +08:00
nonebot
6c0b20e5b7 📝 update api docs 2021-02-01 05:51:45 +00:00
Mix
d2a62ebd3d 📝 💡 fix some typo and style in mirai adapter 2021-02-01 13:50:25 +08:00
StarHeart
b67d2ebce6 Update scheduler.md 2021-02-01 13:45:31 +08:00
nonebot
6a273a8eea 📝 update api docs 2021-02-01 05:21:33 +00:00
Mix
35d34a787b 📝 update document building struct to fit changes in mirai adapter 2021-02-01 13:20:09 +08:00
Mix
8fe562e864 💡 🚸 complete comments and optimize usage in mirai adapter 2021-02-01 13:19:37 +08:00
Ju4tCode
34c2ba8faa 🔀 Merge pull request #183
Fix rule override state
2021-02-01 11:52:48 +08:00
nonebot
616e07cd2d 📝 update api docs 2021-02-01 03:49:26 +00:00
yanyongyu
f6c24ec92f 🐛 change matcher check-run 2021-02-01 11:42:05 +08:00
Ju4tCode
68945d2f20 Merge pull request #182 from nonebot/plugin/issue181
Plugin: 风格化字符串管理
2021-02-01 11:03:34 +08:00
jks15satoshi
977c10524e 🍻 publish 风格化字符串管理 2021-01-31 18:31:29 +00:00
nonebot
923cbd3b8c 📝 update api docs 2021-01-31 17:05:56 +00:00
Mix
56592fc413 🚧 💡 add comments for message etc. in mirai adapter 2021-02-01 01:04:41 +08:00
nonebot
7fdfd89525 📝 update api docs 2021-01-31 16:02:54 +00:00
Mix
7c9cbe7b58 💬 💡 rename some dataclass, add comments for events in mirai adapter 2021-02-01 00:01:31 +08:00
nonebot
ceeb37f8ec 📝 update api docs 2021-01-31 14:45:07 +00:00
Mix
858639bebe 💡 📝 add some comments in code, add document build struct for mirai adapter 2021-01-31 22:43:43 +08:00
Mix
a39785d6d9 💡 add some comments in mirai adapter 2021-01-31 18:00:40 +08:00
nonebot
7b04854b43 📝 update api docs 2021-01-31 18:00:40 +08:00
Mix
20b299c758 🚸 add .approve and .reject method for request event in mirai adapter 2021-01-31 17:01:04 +08:00
Mix
3f56da9245 🚧 add support of reverse post and forward ws for mirai adapter 2021-01-31 16:03:15 +08:00
Ju4tCode
0428b1dd81 Merge pull request #178 from nonebot/plugin/issue177
Plugin: songpicker2
2021-01-31 13:10:07 +08:00
maxesisn
95aad49fb4 🍻 publish songpicker2 2021-01-31 05:07:38 +00:00
Mix
73be9151b0 🚸 add factory classmethods in MessageSegment at mirai adapter 2021-01-30 21:51:51 +08:00
Mix
95f27824ee 🚧 add api methods define 2021-01-30 20:40:00 +08:00
Mix
c82ceefc8b revert call method to http post, add api handle 2021-01-30 19:11:17 +08:00
Ju4tCode
ea615946f6 Merge pull request #175 from nonebot/plugin/issue174
Plugin: 消息交互式 python 解释器
2021-01-30 18:40:23 +08:00
iyume
84504c9daf 🍻 publish 消息交互式 python 解释器 2021-01-30 10:37:12 +00:00
Ju4tCode
6137c1f341 Merge pull request #173 from nonebot/plugin/issue172
Plugin: mqtt接入
2021-01-30 13:46:04 +08:00
Mix
5b3ef53301 🎨 add support for on_bot_* event handler 2021-01-30 13:45:55 +08:00
Mix
8b3eb4e076 add retry for mirai adapter when websocket connection down 2021-01-30 13:36:31 +08:00
synodriver
9cbe182ff4 🍻 publish mqtt接入 2021-01-30 05:31:40 +00:00
yanyongyu
b140ebd149 🐛 fix wrong data in CQ:share #170 2021-01-30 10:56:58 +08:00
Mix
e2f837055e add dependency of websockets 2021-01-30 10:55:06 +08:00
Mix
5de41a18f9 🎨 sort imports in file 2021-01-30 06:10:04 +08:00
Mix
02af1c1227 🚧 finish forward websocket receive 2021-01-30 05:58:30 +08:00
Mix
0bb0d16d93 🚧 basically completed event serialize 2021-01-29 21:19:13 +08:00
Mix
5a9798121c 🚧 add some support for mirai basic events 2021-01-29 17:38:39 +08:00
Mix
8574b2ec72 🚧 start working on mirai-api-http adapter 2021-01-29 17:37:44 +08:00
Artin
5f6a2fffc5 📝 update ding-guide 2021-01-29 14:41:04 +08:00
Artin
27e06dd4e8 🐛 fix ding adapter
1. fix send `at_sender`
2. fix event parse error
3. `MessageSegment` add `atDingtalkIds`/`code`
2021-01-29 14:31:36 +08:00
Artin
06837d4a56 📝 add ding-guide 2021-01-29 14:29:29 +08:00
Ju4tCode
62cb63aa1d Merge pull request #168 from nonebot/plugin/issue167
Plugin: 冷却事件
2021-01-28 11:09:46 +08:00
jks15satoshi
d43dcdf03f 🍻 publish 冷却事件 2021-01-27 15:56:14 +00:00
yanyongyu
a6fcc1ea2a 📝 add group link to doc 2021-01-27 12:08:22 +08:00
Ju4tCode
3047214676 🔀 Merge pull request #166
New: common config loading from .env
2021-01-27 11:54:27 +08:00
nonebot
115132a188 📝 update api docs 2021-01-27 03:46:47 +00:00
yanyongyu
5e3f1b5435 new common config loading from .env 2021-01-27 11:39:34 +08:00
yanyongyu
2e75671d56 ⚗️ add processor to ensure single matcher 2021-01-26 15:03:37 +08:00
yanyongyu
f8304406c5 ⚗️ add new builtin plugin 2021-01-25 18:15:25 +08:00
Ju4tCode
e8d892ebc8 Merge pull request #164 from nonebot/plugin/issue161
Plugin: nonebot-plugin-wordbank
2021-01-25 13:49:08 +08:00
Joenothing-lst
9f37fb23d6 🍻 publish nonebot-plugin-wordbank 2021-01-25 05:45:55 +00:00
yanyongyu
853b797cd9 🐛 change USER perm and temp matcher type 2021-01-24 18:16:18 +08:00
yanyongyu
eb330c3260 🐛 fix plugin store pagination error 2021-01-24 14:36:11 +08:00
yanyongyu
109125b583 🐛 remove args in creating bot 2021-01-21 12:41:52 +08:00
Ju4tCode
c06e9bd432 🔀 Merge pull request #160
Plugin: 模拟抽卡
2021-01-21 11:18:06 +08:00
Ju4tCode
30132e21e8 🔀 Merge pull request #158
fix doc typo
2021-01-21 11:17:51 +08:00
yanyongyu
fbf2eb638e ✏️ fix typo 2021-01-21 11:14:35 +08:00
abrahum
a729b8fa3c 🍻 publish 模拟抽卡 2021-01-21 03:09:57 +00:00
StarHeartHunt
de0bca5c51 📝 update api docs 2021-01-20 23:42:48 +00:00
StarHeart
a028766cf8 Update creating-a-matcher.md 2021-01-21 07:41:12 +08:00
yanyongyu
8973e66ec5 👷 update ci add cache 2021-01-18 14:43:06 +08:00
yanyongyu
b0a71b461f missing aiofiles dependency for docs plugin 2021-01-18 14:38:08 +08:00
yanyongyu
9685a4b1bf ⚗️ seperate configs 2021-01-17 13:46:29 +08:00
yanyongyu
7c3b2b514a add request event approve reject 2021-01-16 11:47:48 +08:00
yanyongyu
fcac6f8a0f improve session id support 2021-01-16 11:10:54 +08:00
Ju4tCode
27189ebfbe 🔀 Merge pull request #149
add fastapi driver configs
2021-01-12 18:07:17 +08:00
yanyongyu
a1d801ba14 ⚗️ new fastapi config settings 2021-01-12 18:02:05 +08:00
yanyongyu
9d047daef5 🚧 move cqhttp config into adapter 2021-01-12 17:55:27 +08:00
yanyongyu
719858168e 📝 update change log 2021-01-12 17:27:23 +08:00
yanyongyu
01fa2ece6e 🐛 fix wrong space strip 2021-01-12 15:48:31 +08:00
yanyongyu
e7993a4485 🐛 fix plain text escaped 2021-01-08 18:14:18 +08:00
yanyongyu
b6bf477551 ⚗️ add got receive overload #142 2021-01-06 18:29:41 +08:00
Ju4tCode
a211f09a99 🔀 Merge pull request #143
fix config typo
2021-01-05 23:11:35 +08:00
theprimone
fe3122adbd 📝 update api docs 2021-01-05 15:08:58 +00:00
yanyongyu
0c517acee2 ✏️ fix config typo 2021-01-05 23:06:36 +08:00
theprimone
9d31fcce2e 📝 update api docs 2021-01-05 14:51:38 +00:00
云生
5abac36647 Fix typo 2021-01-05 22:48:59 +08:00
yanyongyu
60fd092410 🐛 fix none message 2021-01-05 12:12:41 +08:00
Artin
877fa1a75a 🐛 Fix cqhttp Message null parameter 2021-01-04 22:24:43 +08:00
yanyongyu
2218fa2b33 🐛 fix missing return after close ws 2021-01-04 18:09:42 +08:00
Ju4tCode
6b26cecd17 🔀 Merge pull request #140
fix empty array process error
2021-01-04 13:32:16 +08:00
yanyongyu
bc5391d711 🐛 ensure message is not empty 2021-01-04 13:27:49 +08:00
Ju4tCode
3ea2c27e17 🔀 Merge pull request #138
PreRelease 2.0.0a8.post2
2021-01-02 04:10:10 -06:00
yanyongyu
17960b2868 🔖 PreRelease 2.0.0a8.post2 2021-01-02 18:04:44 +08:00
Ju4tCode
22416bf512 🔀 Merge pull request #137 2021-01-02 01:10:43 -06:00
yanyongyu
a4cb7f13be 🐛 fix error guess when reply to event #136 2021-01-02 14:42:13 +08:00
Ju4tCode
822709ceeb 🔀 Merge pull request #135
fix incorrect removing temp matcher
2021-01-01 21:02:18 -06:00
yanyongyu
4dffc879d9 🐛 fix incorrect remove temp matcher 2021-01-02 10:57:55 +08:00
Ju4tCode
f036057b2b 🔀 Merge pull request #133
Pre Release 2.0.0a8.post1
2021-01-01 09:55:13 -06:00
yanyongyu
38ab392b91 🚑 Fix Release 2.0.0a8.post1 2021-01-01 23:47:51 +08:00
Ju4tCode
a45d88ef29 🔀 Merge pull request #132
Fix doc typo
2021-01-01 09:32:06 -06:00
Lan
996c57df62 📝 Update creating-a-handler.md 2021-01-01 19:23:51 +08:00
Lan
8f69b2449d 📝 Update creating-a-matcher.md 2021-01-01 19:21:46 +08:00
Lan
db7e10cb4d ✏️ Fix typo 2021-01-01 18:21:02 +08:00
yanyongyu
b446fcc929 🐛 fix action failed info display error 2021-01-01 18:18:01 +08:00
yanyongyu
5cc5375cb5 🐛 fix missing group_id when PokeNotifyEvent 2021-01-01 18:01:05 +08:00
Ju4tCode
ebf3766cfb 🔀 Merge pull request #131
Fix GroupMessageEvent parse error
2021-01-01 15:25:45 +08:00
Mix
fbaf19e454 :critical: fix group event serialization error 2021-01-01 15:16:55 +08:00
Ju4tCode
a966f82192 🔀 Merge pull request #128
PreRelease 2.0.0a8
2020-12-31 20:19:07 +08:00
yanyongyu
210496f760 📝 update changelog 2020-12-31 20:10:26 +08:00
yanyongyu
13adfa5b55 📝 update doc 2020-12-31 19:56:27 +08:00
yanyongyu
d7e4b52d10 📌 bump version 2.0.0a8 2020-12-31 18:07:38 +08:00
yanyongyu
53c8028646 ⬆️ update dependency 2020-12-31 18:05:49 +08:00
yanyongyu
49201f5346 📝 update doc 2020-12-31 17:58:09 +08:00
yanyongyu
938b5bf275 🐛 fix message construct typing and plugins loading 2020-12-31 14:00:59 +08:00
Ju4tCode
a98417a878 🔀 Merge pull request #127
Update ding adapter
2020-12-30 20:29:18 +08:00
Ju4tCode
1bd223eab2 Restore test_permission.py 2020-12-30 20:19:24 +08:00
yanyongyu
55f1bd1f2d ✏️ update code style 2020-12-30 20:08:22 +08:00
nonebot
380977bc67 📝 update api docs 2020-12-30 10:35:51 +00:00
Artin
086a998b20 improve ding adapter
add tests/test_ding.py
add some log
2020-12-30 18:33:54 +08:00
yanyongyu
d4f344d247 improve command 2020-12-30 12:42:10 +08:00
nonebot
3cb2b44130 📝 update api docs 2020-12-29 16:38:15 +00:00
yanyongyu
c8cd6de2f2 improve ding adapter 2020-12-30 00:36:29 +08:00
nonebot
0221d02ca7 📝 update api docs 2020-12-29 06:51:55 +00:00
Artin
a5947922b6 Update nonebot/adapters/__init__.py
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2020-12-29 14:50:24 +08:00
Artin
13f6a692a7 Update nonebot/adapters/__init__.py
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2020-12-29 14:50:15 +08:00
Artin
f13befc4d8 Update nonebot/adapters/__init__.py
Co-authored-by: Ju4tCode <42488585+yanyongyu@users.noreply.github.com>
2020-12-29 14:50:07 +08:00
nonebot
f4ba97ebab 📝 update api docs 2020-12-29 04:20:09 +00:00
Artin
1bdbbca12f Update ding adapter event logic 2020-12-29 12:12:35 +08:00
Ju4tCode
5028f6408a 🔀 Merge pull request #125
typo fixed
2020-12-29 02:10:27 +08:00
jinser
f53cf80221 Update creating-a-plugin.md 2020-12-29 02:02:23 +08:00
Ju4tCode
e052692a57 🔀 Merge pull request #124
Add scheduler doc
2020-12-28 17:42:12 +08:00
yanyongyu
ab61be26a9 improve radd support for messagesegment 2020-12-28 17:39:33 +08:00
yanyongyu
e02b5f1de8 📝 update scheduler doc 2020-12-28 16:53:53 +08:00
Ju4tCode
de5ca44d6b fix warning block syntax 2020-12-28 15:57:43 +08:00
Lan
9de421b2d2 Revert changes 2020-12-28 15:51:46 +08:00
Lan
82abd2e6ce 📝 Update scheduler.md 2020-12-28 15:43:03 +08:00
Lan
13fb2de964 ✏️ Fix typo 2020-12-28 15:23:18 +08:00
Lan
53de7eab96 📝 Add scheduler.md 2020-12-28 15:18:16 +08:00
Ju4tCode
e14d3d8d73 🔀 Merge pull request #123
New: WebSocket Connection Hook
2020-12-28 14:12:04 +08:00
nonebot
c23a777a9f 📝 update api docs 2020-12-28 06:01:32 +00:00
yanyongyu
1c9df5ac02 🎨 change method into private 2020-12-28 13:59:54 +08:00
nonebot
0c43d83494 📝 update api docs 2020-12-28 05:57:28 +00:00
yanyongyu
299c259d50 🐛 fix hook block event receiving bug 2020-12-28 13:53:24 +08:00
yanyongyu
c993f15bca ⚗️ add ws connection hook 2020-12-28 13:36:00 +08:00
yanyongyu
2d63eb32e1 🚑 hotfix due to cq security problem 2020-12-28 00:24:18 +08:00
yanyongyu
2ae76ff78b ⚗️ new stop propagation method 2020-12-24 22:19:08 +08:00
yanyongyu
41663e1b08 🚧 update cqcode 2020-12-23 17:12:53 +08:00
yanyongyu
c3df90c541 📝 update changelog 2020-12-22 20:14:52 +08:00
yanyongyu
ab256e57b1 🐛 fix missing escape in builtin plugin #117 2020-12-22 20:12:00 +08:00
yanyongyu
054df580eb 📝 update docs 2020-12-22 09:59:48 +08:00
yanyongyu
5fecb5f506 📝 update readme badge 2020-12-22 00:41:33 +08:00
yanyongyu
44a15d684b ✏️ fix typo 2020-12-21 19:32:58 +08:00
yanyongyu
f3243f8989 📝 update changelog 2020-12-21 16:23:29 +08:00
yanyongyu
bc459b5ff4 🐛 fix non text cqcode not unescaped 2020-12-21 16:19:02 +08:00
Ju4tCode
338d5e6f17 🔀 Merge pull request #115
Add default state factory support
2020-12-20 12:20:22 +08:00
nonebot
340e8c3760 📝 update api docs 2020-12-20 04:15:01 +00:00
yanyongyu
e44cde0600 add test case 2020-12-20 12:09:30 +08:00
yanyongyu
1b00fe7921 add state factory support #113 2020-12-20 11:59:51 +08:00
yanyongyu
168cc3801a 📝 build api doc 2020-12-19 15:31:14 +08:00
yanyongyu
4ec4adf003 💡 add adapter docstring 2020-12-19 15:30:34 +08:00
yanyongyu
a88a2f4a4f 🔊 revert log string 2020-12-19 14:16:47 +08:00
yanyongyu
a539fd0062 🔊 improve adapter not found log 2020-12-19 11:20:41 +08:00
yanyongyu
83addf045f improve actionfailed info 2020-12-19 00:50:17 +08:00
yanyongyu
00305a8436 🎨 change event log 2020-12-19 00:26:24 +08:00
yanyongyu
799144e64d finish typing change 2020-12-17 21:09:30 +08:00
yanyongyu
6bd69e6708 🐛 fix typing 2020-12-17 01:52:16 +08:00
yanyongyu
784bc7b0cf ⚗️ new dynamic handler args 2020-12-16 23:13:00 +08:00
yanyongyu
ca8f764b8b 📝 update changelog 2020-12-16 13:36:40 +08:00
yanyongyu
a63a5fea3c 🐛 fix invalid cq code catched 2020-12-16 13:35:34 +08:00
Ju4tCode
a068040cbf Merge pull request #112 from nonebot/plugin/issue111
Plugin: translator
2020-12-15 13:55:03 +08:00
Lancercmd
f5d3ae9efb 🍻 publish translator 2020-12-15 05:43:04 +00:00
yanyongyu
e4377faa67 💄 update docs 2020-12-13 12:53:33 +08:00
yanyongyu
12ef3e7bf1 🚧 update cqhttp adapter event 2020-12-13 12:53:16 +08:00
yanyongyu
3d4adaa444 ⚗️ auto import plugin when require 2020-12-13 12:19:01 +08:00
yanyongyu
7d2a87b73e 🐛 fix plugin publish link 2020-12-12 17:20:37 +08:00
yanyongyu
6c08982ca7 🚧 update process 2020-12-11 16:29:12 +08:00
yanyongyu
f4cea065d8 ✏️ fix validator 2020-12-10 21:33:51 +08:00
Ju4tCode
b651f89865 🔀 Merge pull request #108
Plugin: 通用数据库连接
2020-12-10 17:14:46 +08:00
synodriver
ae73facd89 🍻 publish 通用数据库连接 2020-12-10 08:38:28 +00:00
yanyongyu
72653c6116 🚧 update messages 2020-12-10 02:13:25 +08:00
yanyongyu
a57cd396fa 🚧 update cqhttp event parse 2020-12-10 00:39:43 +08:00
yanyongyu
783efeaf0e 🚧 add event parser 2020-12-09 19:57:49 +08:00
yanyongyu
2c97902f4e 🚧 update cqhttp bot 2020-12-09 17:51:24 +08:00
yanyongyu
2bc05b2576 🚧 update event models 2020-12-09 14:39:25 +08:00
yanyongyu
73bda494d9 🏗️ update cqhttp models 2020-12-09 13:20:14 +08:00
Ju4tCode
e7b44710cc Merge pull request #106
Plugin: 图片搜索
2020-12-09 11:56:01 +08:00
synodriver
2d76209c8a 🍻 publish 图片搜索 2020-12-09 03:52:26 +00:00
yanyongyu
ddf044d6d3 🏗️ add model for cqhttp 2020-12-09 11:13:37 +08:00
yanyongyu
f220a01a30 📝 update doc 2020-12-07 22:15:26 +08:00
Artin
8443c01303 📝 update docs 2020-12-07 21:02:08 +08:00
yanyongyu
f8d0b691ec 📝 update docs typing 2020-12-07 14:09:43 +08:00
yanyongyu
e0d44f3fa7 📝 update api docs 2020-12-07 00:52:26 +08:00
yanyongyu
a420af75fc 🐛 fix type checking for bot 2020-12-07 00:31:14 +08:00
yanyongyu
6b3f6a46e6 🎨 impove typing 2020-12-07 00:06:09 +08:00
yanyongyu
629eed08b6 🎨 update typing support 2020-12-06 02:30:19 +08:00
Ju4tCode
9ab7176eaf 🔀 Merge pull request #104
Fix typing
2020-12-05 20:44:11 +08:00
yanyongyu
3345142db2 🔥 remove useless noreturn 2020-12-05 20:32:38 +08:00
Mix
b1ab5d91a4 🐛 Fix some wrong type hint 2020-12-05 17:19:23 +08:00
yanyongyu
3ba59da0ab 📌 update lock file 2020-12-05 15:58:37 +08:00
Ju4tCode
308acff19a 🔀 Merge pull request #103 2020-12-05 13:33:07 +08:00
Mix
de64e38a07 📝 Optimize expression in installation.md 2020-12-05 13:06:27 +08:00
Ju4tCode
4a22a50f19 🔀 Merge pull request #102
Plugin: 定时任务
2020-12-05 02:05:54 +08:00
yanyongyu
997114477c 🍻 publish 定时任务 2020-12-04 18:00:08 +00:00
Ju4tCode
700407ba98 🔀 Merge pull request #100
Plugin: 前端测试机器人插件
2020-12-05 01:59:44 +08:00
yanyongyu
d42d975d9e 🍻 publish 前端测试机器人插件 2020-12-04 17:56:08 +00:00
Ju4tCode
b6bbc7d228 🔀 Merge pull request #98
PreRelease 2.0.0a7
2020-12-05 01:46:47 +08:00
yanyongyu
621f93f75a 📝 update nonebot docstring 2020-12-05 01:43:58 +08:00
yanyongyu
5ebe7ff1cb 🔖 PreRelease 2.0.0a7 2020-12-05 01:22:28 +08:00
yanyongyu
d7a4593fcf 📝 update changelog 2020-12-04 02:11:20 +08:00
Ju4tCode
dc70f9a9cd 🔀 Merge pull request #97
Add MatcherGroup
2020-12-04 02:00:59 +08:00
yanyongyu
f6806c1d55 test matchergroup 2020-12-04 01:55:03 +08:00
yanyongyu
5b42454a55 add matcher group for plugin #90 2020-12-04 01:41:23 +08:00
Ju4tCode
b24649b6af 🔀 Merge pull request #94
Add dingding adapter
2020-12-03 19:33:58 +08:00
Ju4tCode
0838cdfbe7 🎨 improve format 2020-12-03 19:24:55 +08:00
Ju4tCode
71c5cdc445 revert plain text 2020-12-03 19:12:46 +08:00
Artin
be244f4538 🐛 Fix Message._construct error 2020-12-03 18:47:58 +08:00
yanyongyu
afd01796aa 🚧 update ding adapter 2020-12-03 17:08:16 +08:00
yanyongyu
dc691889e3 🎨 improve cqhttp 2020-12-03 16:04:14 +08:00
nonebot
4b764ccba3 📝 update api docs 2020-12-03 07:09:09 +00:00
yanyongyu
9658e446e5 🏗️ change exception structure 2020-12-03 15:07:03 +08:00
nonebot
8f89e0f26e 📝 update api docs 2020-12-03 05:23:47 +00:00
yanyongyu
7116532081 🚧 add exception 2020-12-03 13:22:12 +08:00
yanyongyu
b47bef3ef6 ✏️ fix builtin typo #96 2020-12-03 13:02:34 +08:00
Artin
3638da7f2d 🐛 Fix ding adapter exception 2020-12-03 12:22:45 +08:00
nonebot
da62e012c2 📝 update api docs 2020-12-03 04:09:54 +00:00
Artin
e718f25c3f 🏷️ 完善 typing 及注释 2020-12-03 12:08:09 +08:00
nonebot
f1a0ac099b 📝 update api docs 2020-12-02 17:49:14 +00:00
Artin
8c5c02f040 🏷️ Update BaseEvent typing 2020-12-03 01:46:55 +08:00
nonebot
33bd9d0fb8 📝 update api docs 2020-12-02 17:04:45 +00:00
Artin
edb4458031 Add ding adapter 2020-12-03 01:02:09 +08:00
Artin
f332199baa ♻️ Encapsulation MessageSegment
close: #93
2020-12-03 00:57:02 +08:00
Artin
8cda1b5417 ♻️ Split adapter by category 2020-12-03 00:56:25 +08:00
yanyongyu
45ceba47f3 👌 update changelog 2020-12-02 16:16:19 +08:00
yanyongyu
8a9a77656f 🍻 add funding 2020-12-02 16:11:46 +08:00
yanyongyu
064ed81758 📝 update adapter connection guide 2020-12-02 15:14:24 +08:00
Ju4tCode
0d5930fc3a 🔀 Merge pull request #92
Refactor: 更新内置 register_adapter 逻辑
2020-12-02 13:45:07 +08:00
yanyongyu
8601c61cd8 💄 update log style 2020-12-02 13:25:57 +08:00
yanyongyu
0738b275a5 💥 remove builtin adapter auto register 2020-12-02 13:17:27 +08:00
yanyongyu
6a25e42571 ⬆️ update lock file 2020-12-02 12:52:02 +08:00
yanyongyu
81d96888bd 📝 update plugin info 2020-12-01 19:10:05 +08:00
yanyongyu
c9d7b63f23 📝 update plugin installation guide 2020-12-01 18:53:03 +08:00
yanyongyu
4c179d9910 📝 update star guide 2020-12-01 17:08:15 +08:00
yanyongyu
a085b47eac 📝 update guide docs 2020-12-01 12:24:14 +08:00
yanyongyu
ad994f04fc 💬 update cqhttp links 2020-12-01 11:03:08 +08:00
yanyongyu
301e9093bd 📄 update license 2020-12-01 10:57:00 +08:00
yanyongyu
39a2658a25 👷 update release drafter 2020-12-01 10:48:46 +08:00
yanyongyu
d624f13f96 💥 remove nonebot test auto init 2020-12-01 10:44:58 +08:00
yanyongyu
6ac04d6507 remove extra dependency 2020-12-01 10:42:59 +08:00
yanyongyu
cc7ebe2f73 ⬆️ bump dependency version 2020-12-01 10:40:21 +08:00
Ju4tCode
bdb4d584e4 🔀 Merge pull request #91
Breaking change: remove built-in scheduler support
2020-12-01 10:33:20 +08:00
yanyongyu
38d502f7f5 💥 remove built-in scheduler support 2020-12-01 10:28:03 +08:00
yanyongyu
e931b535f1 📝 update readme 2020-12-01 00:56:19 +08:00
yanyongyu
0775a232ce ✏️ fix docstring typo 2020-11-30 12:43:44 +08:00
yanyongyu
e5463cc564 🎨 format docstring 2020-11-30 11:08:00 +08:00
Ju4tCode
5554c6e62d 🔀 Merge pull request #88
Plugin: 合并nonebot-plugin-docs
2020-11-28 12:24:14 +08:00
Ju4tCode
96cdb9c23e 🔀 Merge pull request #87
Plugin: 合并docs插件至官方仓库
2020-11-28 12:06:32 +08:00
yanyongyu
b75343d3e7 📝 update homepage and repo link 2020-11-28 11:59:26 +08:00
yanyongyu
62b93c1ba7 🔥 remove file header 2020-11-28 11:55:12 +08:00
yanyongyu
146134a1a7 🔖 update nonebot-plugin-docs author 2020-11-28 11:44:34 +08:00
yanyongyu
da5d63ae29 🔥 remove useless pull and lock file 2020-11-28 11:43:13 +08:00
pull[bot]
9cfcbc5b32 Merge pull request #18 from nonebot/master
[pull] master from nonebot:master
2020-11-26 19:34:04 +00:00
yanyongyu
ee80a4ea60 👷 update user info for pr 2020-11-26 23:54:24 +08:00
yanyongyu
dc0c634eab 🐛 fix workflow vulnerability #79 2020-11-26 23:54:24 +08:00
yanyongyu
168f366efc 📝 update guide 2020-11-26 23:54:24 +08:00
yanyongyu
39d96d9667 📝 add plugin publish guide 2020-11-26 23:54:24 +08:00
yanyongyu
47d1fab4bd 📝 add cross plugin guide 2020-11-26 23:54:24 +08:00
Ju4tCode
84756f3092 🔀Merge pull request #83
👷 update user info for pr
2020-11-26 21:05:16 +08:00
yanyongyu
309c6d1ed0 👷 update user info for pr 2020-11-26 20:53:28 +08:00
Ju4tCode
2bf63ce8aa 🔀 Merge pull request #81 2020-11-26 20:30:03 +08:00
Ju4tCode
b2902407d7 🔀 Merge pull request #80
Fix: GHSL-2020-244
2020-11-26 20:23:32 +08:00
yanyongyu
1fe38afa95 🐛 fix workflow vulnerability #79 2020-11-26 20:18:36 +08:00
pull[bot]
0200167ce2 Merge pull request #16 from nonebot/master
[pull] master from nonebot:master
2020-11-23 17:42:02 +00:00
yanyongyu
0dddbedd70 🍻 publish Sentry日志监控 2020-11-24 01:39:46 +08:00
Ju4tCode
458728ffdd Merge branch 'master' into master 2020-11-24 01:39:17 +08:00
Ju4tCode
df71a1e6ee 🔀 Merge pull request #77
Plugin: Sentry日志监控
2020-11-23 21:46:50 +08:00
yanyongyu
7e35f591d7 🍻 publish Sentry日志监控 2020-11-23 13:35:26 +00:00
yanyongyu
b7642394f4 📝 update guide 2020-11-23 14:15:30 +08:00
yanyongyu
bdd7e9514a 📝 add plugin publish guide 2020-11-23 13:46:36 +08:00
yanyongyu
f214c0b2cb 📝 add cross plugin guide 2020-11-23 13:41:57 +08:00
yanyongyu
5ff638f9e7 🔀 Merge branch 'origin/master' 2020-11-22 21:12:57 +08:00
yanyongyu
e92cbf2f50 🐛 bump version due to vuepress base error 2020-11-22 21:12:07 +08:00
yanyongyu
9d30f2dff3 👷 update release drafter 2020-11-22 09:18:27 +00:00
nonebot
f01295d936 🍻 publish NoneBot离线文档 2020-11-22 09:18:27 +00:00
yanyongyu
343a345ed2 👷 update release drafter 2020-11-22 16:40:06 +08:00
Ju4tCode
2965867516 🔀 Merge pull request #75
Plugin NoneBot离线文档
2020-11-22 16:31:29 +08:00
nonebot
68887086a6 🍻 publish NoneBot离线文档 2020-11-22 08:25:25 +00:00
pull[bot]
47b015a2d0 Merge pull request #5 from nonebot/master
[pull] master from nonebot:master
2020-11-21 21:18:25 +00:00
yanyongyu
1affeb8e20 🔖 release 2.0.0a6 2020-11-22 03:05:28 +08:00
yanyongyu
b5b8ff165c 👷 add release ci 2020-11-22 02:42:27 +08:00
yanyongyu
389211f740 🐛 fix error arg 2020-11-22 02:17:13 +08:00
yanyongyu
68ed443fa3 👽 update vuepress base 2020-11-21 18:00:59 +00:00
yanyongyu
9a819fc12c 💡 update docstring 2020-11-21 18:00:59 +00:00
yanyongyu
2b10f81326 ⚗️ add export require option 2020-11-21 18:00:59 +00:00
yanyongyu
689180ebe8 📝 update change log 2020-11-21 18:00:59 +00:00
yanyongyu
1aba139136 get plugin func 2020-11-21 18:00:59 +00:00
yanyongyu
e5213eb95a 🚑 fix not delete empty text 2020-11-21 18:00:59 +00:00
yanyongyu
5fb9799807 ✏️ fix typo 2020-11-21 18:00:59 +00:00
yanyongyu
9241f4df79 🐛 fix remain space after reply 2020-11-21 18:00:59 +00:00
yanyongyu
d55459cfcd 🚑 fix matcher check 2020-11-21 18:00:59 +00:00
yanyongyu
17747f94c8 🐛 fix #69 stop running expired matcher 2020-11-21 18:00:59 +00:00
yanyongyu
829f47c5e7 🐛 fix #66 resolve reply message 2020-11-21 18:00:59 +00:00
Muchan
557054cb8b feat(message): 传递matcher抛出的StopPropagation 2020-11-21 18:00:59 +00:00
yanyongyu
d726b75721 📝 add changelog 2020-11-21 18:00:59 +00:00
yanyongyu
47aede8f67 🐛 fix index error when check to me 2020-11-21 18:00:59 +00:00
synodriver
1557158cd9 修复了at机器人时的bug 2020-11-21 18:00:59 +00:00
Ju4tCode
de07a6594d 🔀 Merge pull request #73 2020-11-22 01:59:11 +08:00
yanyongyu
07b72f87d7 👽 update vuepress base 2020-11-22 01:51:23 +08:00
yanyongyu
8f4961613d 👷 update pull upstream ci 2020-11-22 01:25:13 +08:00
yanyongyu
339e6cd665 📦 add nonebot plugin docs 2020-11-22 01:20:14 +08:00
yanyongyu
1c87c83c45 👷 add pull upstream ci 2020-11-22 01:18:46 +08:00
yanyongyu
d70f622a24 💡 update docstring 2020-11-21 20:50:33 +08:00
yanyongyu
9373bd09ed ⚗️ add export require option 2020-11-21 20:40:09 +08:00
yanyongyu
b36f95862a 📝 update change log 2020-11-21 20:38:03 +08:00
yanyongyu
71fad44d23 get plugin func 2020-11-21 18:33:35 +08:00
Ju4tCode
cfbfeec69b 🔀 Merge pull request #72
👷 update plugin issue bot
2020-11-20 17:11:36 +08:00
hemengyang
318aa98c98 👷 update plugin issue bot 2020-11-20 16:39:52 +08:00
yanyongyu
009cca3c9d 👷 change ci secret 2020-11-20 13:38:28 +08:00
Ju4tCode
f53644ef26 🔀 Merge pull request #71
add plugin publish action
2020-11-20 13:31:44 +08:00
yanyongyu
7b15d0d01f 🚑 fix not delete empty text 2020-11-20 12:53:31 +08:00
yanyongyu
7fdddf4d8f ✏️ fix typo 2020-11-20 01:37:53 +08:00
yanyongyu
a734790bcf 🐛 fix remain space after reply 2020-11-20 01:07:24 +08:00
hemengyang
9e598cfa70 fix: 忘记改 push 的触发分支名 2020-11-20 00:36:07 +08:00
hemengyang
aca37736c4 ci: 添加插件议题机器人 2020-11-20 00:30:46 +08:00
yanyongyu
a5935e77c9 🚑 fix matcher check 2020-11-19 23:18:03 +08:00
Ju4tCode
93ee9a3b58 🔀 Merge pull request #70
Fix: running expired matcher
2020-11-19 22:08:31 +08:00
yanyongyu
0b6a1ca1a4 🐛 fix #69 stop running expired matcher 2020-11-19 22:04:44 +08:00
Ju4tCode
e9127f505a 🔀 Merge pull request #67
dynamic propagation block
2020-11-19 21:36:52 +08:00
Ju4tCode
30b839d736 🔀 Merge pull request #68
Fix: resolve reply message
2020-11-19 21:29:02 +08:00
yanyongyu
49ad65f449 🐛 fix #66 resolve reply message 2020-11-19 21:21:54 +08:00
Muchan
8b3af9fb47 feat(message): 传递matcher抛出的StopPropagation 2020-11-19 20:53:28 +08:00
yanyongyu
0c39b06355 📝 add changelog 2020-11-19 14:54:58 +08:00
Ju4tCode
73ce79472e 🔀 Merge pull request #64
修复了at机器人时的IndexError
2020-11-19 14:46:57 +08:00
yanyongyu
9e1eee166b 🐛 fix index error when check to me 2020-11-19 13:57:49 +08:00
synodriver
03c7b59df5 修复了at机器人时的bug 2020-11-19 13:07:02 +08:00
Ju4tCode
1654dffa4d 🔀 Merge pull request #63
Plugin: rauthman
2020-11-19 13:02:27 +08:00
yanyongyu
26a4daad33 🍻 publish rauthman 2020-11-19 12:58:35 +08:00
yanyongyu
c666366673 ✏️ fix bot send doc #62 2020-11-19 12:53:20 +08:00
synodriver
d5eb110626 Merge pull request #4 from nonebot/dev
Dev
2020-11-19 10:23:40 +08:00
Ju4tCode
04a3712bc7 🔀 Merge pull request #61
hot fix #60
2020-11-18 15:17:47 +08:00
yanyongyu
39f508bbdf 🔖 Pre Release 2.0.0a6 2020-11-18 15:12:48 +08:00
yanyongyu
0a6008ddc0 update changelog 2020-11-18 15:05:03 +08:00
Ju4tCode
9ba1dc614c 🔀 Merge pull request #60 2020-11-18 14:56:42 +08:00
hemengyang
31123b0573 修复阻止事件传递信号无效的问题 2020-11-18 14:43:12 +08:00
yanyongyu
aaa860de33 🚑 fix full extra apscheduler error 2020-11-18 12:02:26 +08:00
Ju4tCode
5efe1907ad 🔀 Merge pull request #58
Plugin Haruka Bot
2020-11-18 11:29:09 +08:00
yanyongyu
d0c19d09a3 🍻 publish Haruka Bot 2020-11-18 11:24:11 +08:00
yanyongyu
e6268f319d 📝 add advanced and changelog 2020-11-18 08:48:23 +08:00
yanyongyu
42e714ee7d 📝 add sub plugin guide 2020-11-17 17:35:53 +08:00
Ju4tCode
4bee48e9e5 🔀 Merge pull request #57
Pre Release 2.0.0a5
2020-11-17 17:01:41 +08:00
yanyongyu
c71c182834 📦 archive version doc 2020-11-17 16:50:37 +08:00
yanyongyu
9fc354af43 🔖 bump version to 2.0.0a5 2020-11-17 16:36:42 +08:00
Ju4tCode
bc8833ce8e 🔀 Merge pull request #54
fix temp matcher delete
2020-11-16 20:05:49 +08:00
nonebot
8524c32b93 📝 update api docs 2020-11-16 11:59:05 +00:00
yanyongyu
872df975f5 ✏️ fix rst typo 2020-11-16 19:57:49 +08:00
nonebot
36c0d995af 📝 update api docs 2020-11-16 11:42:47 +00:00
yanyongyu
1c31453ba0 🔥 remove unused exception 2020-11-16 19:39:51 +08:00
yanyongyu
2e2f3eee04 ✏️ fix config typo 2020-11-16 15:27:20 +08:00
yanyongyu
b3e6d1c803 💡 add message docstring 2020-11-16 15:06:37 +08:00
yanyongyu
829f085340 🐛 fix coding error 2020-11-16 12:35:04 +08:00
yanyongyu
6986232290 🎨 change temp matcher process #50 2020-11-16 11:25:42 +08:00
Ju4tCode
b5ea66359c 🔀 Merge pull request #53
Add __version__
2020-11-15 16:28:17 +08:00
yanyongyu
730cb82eb7 🥚 add __version__ 2020-11-15 16:18:23 +08:00
Ju4tCode
c4f99d8c77 🔀 Merge pull request #52
Plugin: nonebot-plugin-status
2020-11-15 15:30:41 +08:00
yanyongyu
218c8ea398 🍻 publish nonebot-plugin-status 2020-11-15 15:26:57 +08:00
yanyongyu
47869ccad5 👷 fix import typo 2020-11-15 15:20:15 +08:00
yanyongyu
bde256608b ✏️ fix doc typo 2020-11-15 13:26:20 +08:00
yanyongyu
bc00c1be82 💡 add message docstring 2020-11-13 17:15:45 +08:00
yanyongyu
781ec1ef67 🚑 fix index error in cqhttp check to_me 2020-11-13 16:51:14 +08:00
yanyongyu
c79a6df400 ✏️ fix issue template typo 2020-11-13 11:31:24 +08:00
yanyongyu
28e3177e60 💡 update source docstring #46 #49 2020-11-13 01:46:26 +08:00
yanyongyu
5c29abd724 ✏️ fix tip typo 2020-11-12 13:10:41 +08:00
yanyongyu
9803925bbb 📝 finish plugin guide 2020-11-12 09:32:35 +08:00
yanyongyu
47b1affc56 📝 update handler create doc 2020-11-11 16:49:11 +08:00
yanyongyu
b2a2234d5c 🎨 change permission check from driver into adapter #46 2020-11-11 15:14:29 +08:00
Ju4tCode
1f1f9cd7e6 🔀 Merge pull request #48 2020-11-10 17:42:08 +08:00
nonebot
3903b718cb 📝 update api docs 2020-11-10 09:36:13 +00:00
Artin
c3c2c7935d ♻️ add adapters/cqhttp directory 2020-11-10 17:34:02 +08:00
yanyongyu
09a511acf8 📝 add poetry install 2020-11-10 14:44:24 +08:00
yanyongyu
b3f7aaa580 📝 add create handler guide 2020-11-10 14:30:18 +08:00
yanyongyu
286036a936 ✏️ fix module docstring 2020-11-10 14:29:50 +08:00
synodriver
11889b57fe Merge pull request #2 from nonebot/dev
Dev
2020-11-10 01:16:35 +08:00
yanyongyu
9b3dffaab9 ⚗️ add prompt format support 2020-11-09 16:34:14 +08:00
yanyongyu
bb869b5263 📝 update matcher rule docs 2020-11-09 15:09:21 +08:00
yanyongyu
3528d38be1 📝 add create matcher guide 2020-11-09 12:47:59 +08:00
yanyongyu
17ad11212e 👷 add lint script 2020-11-09 12:46:28 +08:00
yanyongyu
50056228b6 📝 update plugin create 2020-11-09 12:33:17 +08:00
yanyongyu
946750a189 📝 add create plugin guide 2020-11-09 11:14:23 +08:00
yanyongyu
7ce69fb6f8 add processor test 2020-11-07 18:15:09 +08:00
Ju4tCode
b87df479a2 🔀 Merge pull request #45
add pre and post processors
2020-11-07 17:56:01 +08:00
nonebot
5458248403 📝 update api docs 2020-11-07 09:52:23 +00:00
yanyongyu
9b4121053c ⬆️ update lock file 2020-11-07 17:51:17 +08:00
yanyongyu
746b608d10 ⚗️ add pre and post processor #40 2020-11-07 17:35:44 +08:00
yanyongyu
9d7da873c4 📝 add plugin load doc 2020-11-07 12:36:47 +08:00
Ju4tCode
70c400da7f 🔀 Merge pull request #43
Pre Release 2.0.0a4
2020-11-04 13:46:05 +08:00
yanyongyu
2a5cfe712f 📝 update doc version 2020-11-04 13:41:52 +08:00
yanyongyu
533a045622 ⬆️ bump version and update dependency 2020-11-04 13:27:49 +08:00
Ju4tCode
93aa1791c9 🔀 Merge pull request #42
Fix: Plugin publish template
2020-11-02 20:25:28 +08:00
yanyongyu
06c76cc096 👷 fix plugin template 2020-11-02 20:20:41 +08:00
Ju4tCode
04df0e5f51 🔀 Merge pull request #41 2020-11-02 19:39:55 +08:00
yanyongyu
f99e029567 📌 update poetry lock file 2020-11-02 19:33:45 +08:00
yanyongyu
71ee9aee21 🚧 update plugin store 2020-11-02 19:07:53 +08:00
yanyongyu
d9ea95c67e 🚑 fix message segment get 2020-11-01 19:20:18 +08:00
yanyongyu
af7f42ac60 📝 update plugin store page 2020-11-01 18:21:31 +08:00
yanyongyu
15e59a1778 👷 update plugin template 2020-11-01 18:21:10 +08:00
yanyongyu
22962d55e1 👷 create plugin issue template 2020-11-01 16:18:57 +08:00
yanyongyu
70c7927006 💡 add docstring for cqhttp message 2020-10-30 16:49:31 +08:00
yanyongyu
89c3aa38a6 🎨 allow multi value for keyword rule 2020-10-30 16:26:04 +08:00
Ju4tCode
2eb330b8a8 🔀 Merge pull request #39 2020-10-30 15:57:31 +08:00
yanyongyu
383c0031a5 📝 update plugin 2020-10-30 01:59:45 +08:00
yanyongyu
06f20281a5 🔇 remove meta event logs #21 2020-10-29 17:06:07 +08:00
yanyongyu
a40f1a453c 📝 replace say with echo due to superuser perm 2020-10-29 16:27:20 +08:00
Ju4tCode
5d9f354209 🔀 Merge pull request #37 2020-10-28 13:49:53 +08:00
Ju4tCode
c3bd8ebf57 🚧 change result store 2020-10-28 13:45:54 +08:00
yanyongyu
c9c615c8cb 👷 try pull request target 2020-10-28 13:42:20 +08:00
Ju4tCode
47f491039c 💡 update regex docstring 2020-10-28 13:23:48 +08:00
yanyongyu
dc5c35a9ed 💡 update command docstrinrg 2020-10-28 13:17:41 +08:00
yanyongyu
c636186321 👷 update api doc action 2020-10-28 13:05:51 +08:00
Ju4tCode
aafc3dd060 🔀 Merge pull request #38 2020-10-28 12:52:27 +08:00
ayayaneru
38469611a4 Update README 2020-10-28 10:01:33 +08:00
rkroom
59a8bd8c97 add matched_string when rule regex
当使用正则匹配消息成功时,向state添加matched_string以保存匹配到的内容供接下来使用。
2020-10-26 17:18:26 +08:00
Ju4tCode
50cfd3c9b5 🔀 Merge pull request #36
Issue35:修改鉴权限制
2020-10-25 14:48:00 +08:00
yanyongyu
5d08d53c27 👽 update auth header 2020-10-25 14:42:46 +08:00
Ju4tCode
4f6f99146c 🔀 Merge pull request #33
修改 Command 实现逻辑
2020-10-22 22:36:23 +08:00
yanyongyu
32388d070d 🎨 improve command implementation 2020-10-22 22:08:19 +08:00
yanyongyu
d9f8bf38c6 🐛 fix matcher group send 2020-10-22 00:00:29 +08:00
yanyongyu
4e2b74af75 🚧 add plugin store page 2020-10-21 00:55:23 +08:00
yanyongyu
c2c28cebf5 👽 update nonebot theme 2020-10-21 00:54:09 +08:00
yanyongyu
24141b1a4b 🎨 remove shebang line #31 2020-10-20 22:40:16 +08:00
Ju4tCode
c85e50d73d 👷 Add release draft config 2020-10-20 17:28:51 +08:00
Ju4tCode
444156766a 👷 Update release drafter 2020-10-20 17:27:41 +08:00
yanyongyu
308824d0b1 🐛 fix matcher group args parser 2020-10-20 00:01:26 +08:00
yanyongyu
c3ed962837 add site cache to improve performance #29 2020-10-19 17:49:04 +08:00
Ju4tCode
2c13303d89 👷 Update issue templates 2020-10-19 00:00:11 +08:00
Ju4tCode
1304b94b61 🔀 Merge pull request #28
Update vuepress theme
2020-10-18 03:05:42 -05:00
yanyongyu
8ca677c271 👽 fix home link 2020-10-18 15:34:14 +08:00
yanyongyu
7c17412106 💡 add plugin docstring 2020-10-18 15:04:45 +08:00
yanyongyu
26207f762b 🏷️ fix class inherit in pyi 2020-10-18 15:02:56 +08:00
yanyongyu
8db70dbb0c 👽 fix theme smooth scroll 2020-10-18 02:30:01 +08:00
yanyongyu
1b6924a104 👽 update lock file 2020-10-18 02:04:32 +08:00
yanyongyu
c5a30a8a79 use custom theme 2020-10-18 01:39:34 +08:00
yanyongyu
56c9c24dc6 add kwargs support for matcher send/finish/pause/reject 2020-10-17 19:50:25 +08:00
yanyongyu
9ad629841b 📝 add uninstall nonebot 1.x tip 2020-10-16 17:15:40 +08:00
yanyongyu
78433bdae9 🚑 restore markdown 2020-10-16 16:08:51 +08:00
yanyongyu
5f44212faa 🚑 restore div 2020-10-16 16:07:04 +08:00
yanyongyu
df517b6b36 📝 use p instead of div 2020-10-16 16:03:49 +08:00
yanyongyu
6afe9b6f4f 📝 Update Readme (fix #27) 2020-10-16 15:59:34 +08:00
yanyongyu
1d79ac232f 🐛 fix missing param for on event 2020-10-16 15:12:15 +08:00
yanyongyu
0a64959973 💡 add driver docstring 2020-10-16 01:10:46 +08:00
yanyongyu
1e4b058681 👽 update repo link 2020-10-11 14:51:37 +08:00
yanyongyu
3c5d06a2de 📝 add todo tag 2020-10-11 13:49:58 +08:00
273 changed files with 35497 additions and 6760 deletions

2
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,2 @@
open_collective: nonebot
custom: ["https://afdian.net/@nonebot"]

33
.github/ISSUE_TEMPLATE/bug-report.md vendored Normal file
View File

@@ -0,0 +1,33 @@
---
name: Bug report
about: Create a bug report to help us improve
title: 'Bug: Something went wrong'
labels: bug
assignees: ''
---
**描述问题:**
A clear and concise description of what the bug is.
**如何复现?**
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**期望的结果**
A clear and concise description of what you expected to happen.
**环境信息:**
- OS: [e.g. Linux]
- Python Version: [e.g. 3.8]
- Nonebot Version: [e.g. 2.0.0]
**截图**
If applicable, add screenshots to help explain your problem.

View File

@@ -0,0 +1,16 @@
---
name: Feature request
about: Suggest an idea for this project
title: 'Feature: Something you want'
labels: enhancement
assignees: ''
---
**是否在使用中遇到某些问题而需要新的特性?请描述:**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**描述你所需要的特性:**
A clear and concise description of what you want to happen.

View File

@@ -0,0 +1,36 @@
---
name: Plugin Publish
about: Publish your plugin to nonebot homepage and nb-cli
title: "Plugin: blabla 的插件"
labels: Plugin
assignees: ""
---
**你的插件名称:**
例:复读机
**简短描述插件功能:**
例:复读群友的消息
**插件 import 使用的名称**
nonebot_plugin_example
**插件 install 使用的名称**
例 1nonebot-plugin-example
通过 pypi 安装
> 请事先发布插件到[pypi](https://pypi.org/)
例 2git+https://github.com/nonebot/nonebot-plugin-example
从 github 仓库安装
**插件项目仓库/主页链接**
nonebot/nonebot2默认 github )或其他链接

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

@@ -0,0 +1,38 @@
name-template: 'v$RESOLVED_VERSION 🌈'
tag-template: 'v$RESOLVED_VERSION'
categories:
- title: '💥 Breaking Changes'
labels:
- 'Breaking'
- title: '🚀 Features'
labels:
- 'feature'
- 'enhancement'
- title: '🐛 Bug Fixes'
labels:
- 'fix'
- 'bugfix'
- 'bug'
- title: '🍻 Plugin Publish'
label: 'Plugin'
change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks.
version-resolver:
major:
labels:
- 'major'
minor:
labels:
- 'minor'
patch:
labels:
- 'patch'
default: patch
template: |
## Documentation
See: https://v2.nonebot.dev
## 💫 Changes
$CHANGES

View File

@@ -19,10 +19,17 @@ jobs:
python-version: 3.8
architecture: "x64"
- name: Install Dependences
- uses: Gr1N/setup-poetry@v4
- uses: actions/cache@v1
with:
path: ~/.cache/pypoetry/virtualenvs
key: ${{ runner.os }}-poetry-${{ hashFiles('poetry.lock') }}
restore-keys: |
${{ runner.os }}-poetry-
- name: Set up dependencies
run: |
python -m pip install --upgrade pip
pip install poetry
poetry install
- name: Build Doc
@@ -31,11 +38,7 @@ jobs:
- name: Copy Files
run: cp -r ./build/markdown/* ./docs/api/
- run: |
git config user.name nonebot
git config user.email nonebot@nonebot.dev
git add .
git diff-index --quiet HEAD || git commit -m ":memo: update api docs"
git remote -vv
git remote add target ${{github.event.pull_request.head.repo.clone_url}}
git push target HEAD:${{github.event.pull_request.head.ref}}
- uses: actions/upload-artifact@v2
with:
name: docs
path: docs/

View File

@@ -0,0 +1,40 @@
name: Release Nonebot Plugin Docs
on:
release:
types: [ published ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node
uses: actions/setup-node@v1
with:
node-version: '12'
- run: npm ci
- name: Build Docs
env:
VUEPRESS_BASE: '/docs/'
run: npx vuepress build docs --dest packages/nonebot-plugin-docs/nonebot_plugin_docs/dist
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
architecture: "x64"
- name: Install Poetry
run: |
python -m pip install --upgrade pip
pip install poetry
- 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}}

25
.github/workflows/plugin_issue.yml vendored Normal file
View File

@@ -0,0 +1,25 @@
name: 'Plugin Issue Bot'
on:
push:
branches:
- master
issues:
types: [opened, reopened, edited]
pull_request:
types: [closed]
jobs:
issue_bot:
runs-on: ubuntu-latest
name: plugin issue bot
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: NoneBot2 Plugin Issue Bot
uses: he0119/nonebot2-plugin-issue-bot@v0.2
with:
token: ${{ secrets.GH_TOKEN }}
base: master
path: docs/.vuepress/public/plugins.json

14
.github/workflows/release-draft.yml vendored Normal file
View File

@@ -0,0 +1,14 @@
name: Release Drafter
on:
push:
branches:
- master
jobs:
update_release_draft:
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

35
.github/workflows/upload_docs.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Upload API Doc
on:
workflow_run:
workflows: ["Build API Doc"]
types:
- completed
jobs:
upload:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' }}
steps:
- uses: actions/checkout@v2
with:
ref: ${{ github.event.workflow_run.head_sha }}
token: ${{ secrets.GH_TOKEN }}
- uses: dawidd6/action-download-artifact@v2
with:
workflow: ${{ github.event.workflow_run.workflow_id }}
name: docs
path: docs/
- env:
REF: ${{ github.event.workflow_run.head_branch }}
PR_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
PR_USER: ${{ github.event.workflow_run.head_repository.owner.login }}
run: |
git config user.name $PR_USER
git config user.email $PR_USER@users.noreply.github.com
git add .
git diff-index --quiet HEAD || git commit -m ":memo: update api docs"
git remote add target https://github.com/$PR_REPO.git
git push target HEAD:$REF

1
.prettierignore Normal file
View File

@@ -0,0 +1 @@
.github/**/*.md

View File

@@ -1,5 +1,5 @@
The MIT License (MIT)
Copyright (c) 2018 Richard Chien
Copyright (c) 2020 NoneBot Team
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
@@ -16,4 +16,4 @@ 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.
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

119
README.md
View File

@@ -1,37 +1,122 @@
<div align=center>
<img src="./docs/.vuepress/public/logo.png" width="200" height="200">
<p align="center">
<a href="https://v2.nonebot.dev/"><img src="https://raw.githubusercontent.com/nonebot/nonebot2/master/docs/.vuepress/public/logo.png" width="200" height="200" alt="nonebot"></a>
</p>
<div align="center">
# NoneBot
[![License](https://img.shields.io/github/license/nonebot/nonebot2.svg)](LICENSE)
[![PyPI](https://img.shields.io/pypi/v/nonebot2.svg)](https://pypi.python.org/pypi/nonebot2)
![Python Version](https://img.shields.io/badge/python-3.7+-blue.svg)
![CQHTTP Version](https://img.shields.io/badge/cqhttp-11+-black.svg)
[![QQ 群](https://img.shields.io/badge/qq%E7%BE%A4-768887710-orange.svg)](https://jq.qq.com/?_wv=1027&k=5OFifDh)
[![Telegram](https://img.shields.io/badge/telegram-chat-blue.svg)](https://t.me/cqhttp)
[![QQ 版本发布群](https://img.shields.io/badge/%E7%89%88%E6%9C%AC%E5%8F%91%E5%B8%83%E7%BE%A4-218529254-green.svg)](https://jq.qq.com/?_wv=1027&k=5Nl0zhE)
[![Telegram 版本发布频道](https://img.shields.io/badge/%E7%89%88%E6%9C%AC%E5%8F%91%E5%B8%83%E9%A2%91%E9%81%93-join-green.svg)](https://t.me/cqhttp_release)
_✨ Python 异步机器人框架 ✨_
</div>
<p align="center">
<a href="https://raw.githubusercontent.com/nonebot/nonebot2/master/LICENSE">
<img src="https://img.shields.io/github/license/nonebot/nonebot2" alt="license">
</a>
<a href="https://pypi.python.org/pypi/nonebot2">
<img src="https://img.shields.io/pypi/v/nonebot2" alt="pypi">
</a>
<img src="https://img.shields.io/badge/python-3.7+-blue" alt="python"><br />
<a href="https://github.com/howmanybots/onebot/blob/master/README.md">
<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>
<a href="https://core.telegram.org/bots/api">
<img src="https://img.shields.io/badge/telegram-Bot-lightgrey?style=social&logo=telegram">
</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">
</a>
<a href="https://t.me/cqhttp">
<img src="https://img.shields.io/badge/telegram-chat-blue?style=flat-square" alt="Telegram Chat">
</a>
<a href="https://jq.qq.com/?_wv=1027&k=5Nl0zhE">
<img src="https://img.shields.io/badge/%E7%89%88%E6%9C%AC%E5%8F%91%E5%B8%83%E7%BE%A4-218529254-green?style=flat-square" alt="QQ Release">
</a>
<a href="https://t.me/cqhttp_release">
<img src="https://img.shields.io/badge/%E7%89%88%E6%9C%AC%E5%8F%91%E5%B8%83%E9%A2%91%E9%81%93-join-green?style=flat-square" alt="Telegram Release">
</a>
</p>
<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/guide/getting-started.html">开始使用</a>
·
<a href="#插件">文档打不开?</a>
</p>
## 简介
NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。
NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。
除了起到解析消息的作用NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。
除了起到解析事件的作用NoneBot 还为插件提供了大量实用的预设操作和权限控制机制对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。
目前 NoneBot2 在 [FastAPI](https://fastapi.tiangolo.com/) 的基础上封装了与 [CQHTTP(OneBot) 协议](http://cqhttp.cc/)插件的网络交互
得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制NoneBot 处理事件的吞吐量有了很大的保障,再配合 WebSocket 通信方式也是最建议的通信方式NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃
得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式也是最建议的通信方式NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。
## 特色
需要注意的是NoneBot 仅支持 Python 3.7+ 及 CQHTTP(OneBot) 插件 v11+。
NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**
## 文档
目前 NoneBot2 内置的驱动框架:
文档目前尚未完成「API」部分由 sphinx 自动生成,你可以在 [这里](https://v2.nonebot.dev/) 查看。
- [FastAPI](https://fastapi.tiangolo.com/)
目前 NoneBot2 内置的协议适配:
- [OneBot(CQHTTP) 协议](https://github.com/howmanybots/onebot/blob/master/README.md) (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://v2.nonebot.dev/) 查看。
懒得看文档?下面是快速安装指南:~~这是坏文明~~
1. (可选)使用你喜欢的 Python 环境管理工具创建新的虚拟环境。
2. 使用 `pip` (或其他) 安装 NoneBot 脚手架。
```bash
pip install nb-cli
```
3. 使用脚手架创建项目
```bash
nb create
```
## 插件
此外NoneBot2 还有丰富的官方以及第三方现成的插件供大家使用:
- [NoneBot-Plugin-Docs](https://github.com/nonebot/nonebot2/tree/master/packages/nonebot-plugin-docs):离线文档至本地使用(别再说文档打不开了!)
```bash
nb plugin install nonebot_plugin_docs
```
- 其他插件请查看 [插件商店](https://v2.nonebot.dev/plugin-store.html)
## 贡献
如果你在使用过程中发现任何问题,可以 [提交 issue](https://github.com/nonebot/nonebot2/issues/new) 或自行 fork 修改后提交 pull request。
如果你要提交 pull request请确保你的代码风格和项目已有的代码保持一致遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/),变量命名清晰,有适当的注释。
## 许可证
`NoneBot` 采用 `MIT` 协议开源,协议文件参考 [LICENSE](./LICENSE)。
特别的,由于 `mirai` 使用 `AGPLv3` 协议并要求使用 `mirai` 的软件同样以 `AGPLv3` 协议开源,本项目 `mirai` 适配器部分(即 [`nonebot/adapters/mirai/`](./nonebot/adapters/mirai/) 目录)以 `AGPLv3` 协议开源,协议文件参考 [LICENSE](./nonebot/adapters/mirai/LICENSE)。

View File

@@ -1,265 +0,0 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.config 模块
## 配置
NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-dotenv](https://saurabh-kumar.com/python-dotenv/) 来读取配置。
配置项需符合特殊格式或 json 序列化格式。详情见 [pydantic Field Type](https://pydantic-docs.helpmanual.io/usage/types/) 文档。
## _class_ `Env`
基类:`pydantic.env_settings.BaseSettings`
运行环境配置。大小写不敏感。
将会从 `nonebot.init 参数` > `环境变量` > `.env 环境配置文件` 的优先级读取配置。
### `environment`
* 类型: `str`
* 默认值: `"prod"`
* 说明:
当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。
## _class_ `Config`
基类:`nonebot.config.BaseConfig`
NoneBot 主要配置。大小写不敏感。
除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。
这些配置将会在 json 反序列化后一起带入 `Config` 类中。
### `driver`
* 类型: `str`
* 默认值: `"nonebot.drivers.fastapi"`
* 说明:
NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver`
### `host`
* 类型: `IPvAnyAddress`
* 默认值: `127.0.0.1`
* 说明:
NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。
### `port`
* 类型: `int`
* 默认值: `8080`
* 说明:
NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。
### `debug`
* 类型: `bool`
* 默认值: `False`
* 说明:
是否以调试模式运行 NoneBot。
### `api_root`
* 类型: `Dict[str, str]`
* 默认值: `{}`
* 说明:
以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。
* 示例:
```default
API_ROOT={"123456": "http://127.0.0.1:5700"}
```
### `api_timeout`
* 类型: `Optional[float]`
* 默认值: `30.`
* 说明:
API 请求超时时间,单位: 秒。
### `access_token`
* 类型: `Optional[str]`
* 默认值: `None`
* 说明:
API 请求以及上报所需密钥,在请求头中携带。
* 示例:
```http
POST /cqhttp/ HTTP/1.1
Authorization: Bearer kSLuTF2GC2Q4q4ugm3
```
### `secret`
* 类型: `Optional[str]`
* 默认值: `None`
* 说明:
HTTP POST 形式上报所需签名,在请求头中携带。
* 示例:
```http
POST /cqhttp/ HTTP/1.1
X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2
```
### `superusers`
* 类型: `Set[int]`
* 默认值: `set()`
* 说明:
机器人超级用户。
* 示例:
```default
SUPER_USERS=[12345789]
```
### `nickname`
* 类型: `Set[str]`
* 默认值: `set()`
* 说明:
机器人昵称。
### `command_start`
* 类型: `Set[str]`
* 默认值: `{"/"}`
* 说明:
命令的起始标记,用于判断一条消息是不是命令。
### `command_sep`
* 类型: `Set[str]`
* 默认值: `{"."}`
* 说明:
命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
### `session_expire_timeout`
* 类型: `timedelta`
* 默认值: `timedelta(minutes=2)`
* 说明:
等待用户回复的超时时间。
* 示例:
```default
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
```
### `apscheduler_config`
* 类型: `dict`
* 默认值: `{"apscheduler.timezone": "Asia/Shanghai"}`
* 说明:
APScheduler 的配置对象,见 [Configuring the Scheduler](https://apscheduler.readthedocs.io/en/latest/userguide.html#configuring-the-scheduler)

View File

@@ -1,37 +0,0 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.drivers 模块
## 后端驱动适配基类
各驱动请继承以下基类
## _class_ `BaseDriver`
基类:`abc.ABC`
Driver 基类。将后端框架封装,以满足适配器使用。
### `_adapters`
* **类型**
`Dict[str, Type[Bot]]`
* **说明**
已注册的适配器列表
### _abstract_ `__init__(env, config)`
Initialize self. See help(type(self)) for accurate signature.

View File

@@ -1,16 +0,0 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.drivers.fastapi 模块
## _class_ `Driver`
基类:[`nonebot.drivers.BaseDriver`](#None)
### `__init__(env, config)`
Initialize self. See help(type(self)) for accurate signature.

View File

@@ -1,41 +0,0 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.sched 模块
## 计划任务
计划任务使用第三方库 [APScheduler](https://github.com/agronholm/apscheduler) ,使用文档请参考 [APScheduler使用文档](https://apscheduler.readthedocs.io/en/latest/) 。
## `scheduler`
* **类型**
`Optional[apscheduler.schedulers.asyncio.AsyncIOScheduler]`
* **说明**
当可选依赖 `APScheduler` 未安装时,`scheduler` 为 None
使用 `pip install nonebot[scheduler]` 安装可选依赖
* **常用示例**
```python
from nonebot import scheduler
@scheduler.scheduled_job("cron", hour="*/2", id="xxx", args=[1], kwargs={arg2: 2})
async def run_every_2_hour(arg1, arg2):
pass
scheduler.add_job(run_every_day_from_program_start, "interval", days=1, id="xxx")
```

View File

@@ -1,73 +0,0 @@
# 安装
## NoneBot
:::warning 注意
请确保你的 Python 版本 >= 3.7。
:::
```bash
pip install nonebot2
```
如果你需要使用最新的(可能尚未发布的)特性,可以克隆 Git 仓库后手动安装:
```bash
git clone https://github.com/nonebot/nonebot2.git
cd nonebot2
poetry install --no-dev # 推荐
pip install . # 不推荐
```
## 额外依赖
### APScheduler
A task scheduling library for Python.
可用于计划任务,后台执行任务等
```bash
pip install nonebot2[scheduler]
poetry add nonebot2[scheduler]
```
[View On GitHub](https://github.com/agronholm/apscheduler)
### NoneBot-Test
A test frontend for nonebot2.
通过前端展示 nonebot 已加载的插件以及运行状态,同时可以用于模拟发送事件测试机器人
```bash
pip install nonebot2[test]
poetry add nonebot2[test]
```
[View On GitHub](https://github.com/nonebot/nonebot-test)
### CLI
CLI for nonebot2.
一个多功能脚手架
```bash
pip install nonebot2[cli]
poetry add nonebot2[cli]
```
[View On GitHub](https://github.com/yanyongyu/nb-cli)
### 我全都要
```bash
pip install nonebot2[full]
poetry add nonebot2[full]
```
```bash
pip install nonebot2[cli,scheduler]
poetry add nonebot2[cli,scheduler]
```

View File

@@ -1,290 +0,0 @@
# 编写插件
本章将以一个天气查询插件为例,教学如何编写自己的命令。
## 加载插件
在 [创建一个完整的项目](creating-a-project) 一章节中,我们已经创建了插件目录 `awesome_bot/plugins`,现在我们在机器人入口文件中加载它。当然,你也可以单独加载一个插件。
:::tip 提示
加载插件目录时,目录下以 `_` 下划线开头的插件将不会被加载!
:::
`bot.py` 文件中添加以下行:
```python{5,7}
import nonebot
nonebot.init()
# 加载单独的一个插件参数为合法的python包名
nonebot.load_plugin("nonebot.plugins.base")
# 加载插件目录,该目录下为各插件,以下划线开头的插件将不会被加载
nonebot.load_plugins("awesome_bot/plugins")
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
尝试运行 `nb run` 或者 `python bot.py`,可以看到日志输出了类似如下内容:
```plain
09-19 21:51:59 [INFO] nonebot | Succeeded to import "nonebot.plugins.base"
09-19 21:51:59 [INFO] nonebot | Succeeded to import "plugin_in_folder"
```
## 创建插件
现在我们已经有了一个空的插件目录,我们可以开始创建插件了!插件有两种形式
### 单文件形式
在插件目录下创建名为 `weather.py` 的 Python 文件,暂时留空,此时目录结构如下:
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── awesome_bot
│ └── plugins
│ └── `weather.py`
├── .env
├── .env.dev
├── .env.prod
├── .gitignore
├── bot.py
├── docker-compose.yml
├── Dockerfile
├── pyproject.toml
└── README.md
:::
<!-- prettier-ignore-end -->
这个时候它已经可以被称为一个插件了,尽管它还什么都没做。
### 包形式
在插件目录下创建文件夹 `weather`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下:
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── awesome_bot
│ └── plugins
│ └── `weather`
│ └── `__init__.py`
├── .env
├── .env.dev
├── .env.prod
├── .gitignore
├── bot.py
├── docker-compose.yml
├── Dockerfile
├── pyproject.toml
└── README.md
:::
<!-- prettier-ignore-end -->
这个时候 `weather` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。
## 编写真正的内容
好了,现在插件已经可以正确加载,我们可以开始编写命令的实际代码了。在 `weather.py` 中添加如下代码:
```python
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event
weather = on_command("天气", rule=to_me(), priority=5)
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海则args为上海
if args:
state["city"] = args # 如果用户发送了参数则直接赋值
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: dict):
city = state["city"]
if city not in ["上海", "北京"]:
await weather.reject("你想查询的城市暂不支持,请重新输入!")
city_weather = await get_weather(city)
await weather.finish(city_weather)
async def get_weather(city: str):
return f"{city}的天气是..."
```
为了简单起见,我们在这里的例子中没有接入真实的天气数据,但要接入也非常简单,你可以使用中国天气网、和风天气等网站提供的 API。
下面我们来说明这段代码是如何工作的。
:::tip 提示
从这里开始,你需要对 Python 的 asyncio 编程有所了解,因为 NoneBot 是完全基于 asyncio 的,具体可以参考 [廖雪峰的 Python 教程](https://www.liaoxuefeng.com/wiki/1016959663602400/1017959540289152)
:::
### 注册一个 [事件响应器](../api/matcher.md)
```python{4}
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.permission import Permission
weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5)
```
在上方代码中,我们注册了一个事件响应器 `Matcher`,它由几个部分组成:
1. `on_command` 注册一个消息类型的命令处理器
2. `"天气"` 指定 command 参数 - 命令名
3. `rule` 补充事件响应器的匹配规则
4. `priority` 事件响应器优先级
5. `block` 是否阻止事件传递
其他详细配置可以参考 API 文档,下面我们详细说明各个部分:
#### 事件响应器类型 type
事件响应器类型其实就是对应 `Event.type` NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些内置的事件响应器。
- `on("事件类型")`: 基础事件响应器,第一个参数为事件类型,空字符串表示不限
- `on_metaevent()` ~ `on("meta_event")`: 元事件响应器
- `on_message()` ~ `on("message")`: 消息事件响应器
- `on_request()` ~ `on("request")`: 请求事件响应器
- `on_notice()` ~ `on("notice")`: 通知事件响应器
- `on_startswith(str)` ~ `on("message", startswith(str))`: 消息开头匹配处理器
- `on_endswith(str)` ~ `on("message", endswith(str))`: 消息结尾匹配处理器
- `on_command(str|tuple)` ~ `on("message", command(str|tuple))`: 命令处理器
- `on_regex(pattern_str)` ~ `on("message", regex(pattern_str))`: 正则匹配处理器
#### 匹配规则 rule
事件响应器的匹配规则即 `Rule`,由非负个 `RuleChecker` 组成,当所有 `RuleChecker` 返回 `True` 时匹配成功。这些 `RuleChecker` 的形式如下:
```python
async def check(bot: Bot, event: Event, state: dict) -> bool:
return True
def check(bot: Bot, event: Event, state: dict) -> bool:
return True
```
`Rule` 和 `RuleChecker` 之间可以使用 `&` 互相组合:
```python
from nonebot.rule import Rule
Rule(async_checker1) & sync_checker & async_checker2
```
:::danger 警告
`Rule(*checkers)` 只接受 async function或使用 `nonebot.utils.run_sync` 自行包裹 sync function。在使用 `&` 时NoneBot 会自动包裹 sync function
:::
#### 优先级 priority
事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!**
:::tip 提示
使用 `nonebot-test` 可以看到当前所有事件响应器的执行流程,有助理解事件响应流程!
```bash
pip install nonebot2[test]
```
:::
#### 阻断 block
当有任意事件响应器发出了阻止事件传递信号时,该事件将不再会传递给下一优先级,直接结束处理。
NoneBot 内置的事件响应器中,所有 `message` 类的事件响应器默认会阻断事件传递,其他则不会。
### 编写事件处理函数 [Handler](../api/typing.md#handler)
```python{1,2,8,9}
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海则args为上海
if args:
state["city"] = args # 如果用户发送了参数则直接赋值
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: dict):
city = state["city"]
if city not in ["上海", "北京"]:
await weather.reject("你想查询的城市暂不支持,请重新输入!")
city_weather = await get_weather(city)
await weather.finish(city_weather)
```
在上面的代码中,我们给 `weather` 事件响应器添加了两个事件处理函数:`handle_first_receive`, `handle_city`
其中有几个要点,我们一一解释:
#### 添加一个事件处理函数
在事件响应器响应事件时,事件处理函数会依次顺序执行,也就是说,与添加顺序一致。
我们可以使用 `@matcher.handle()` 装饰器来简单地为该事件响应器添加一个处理函数。
同时NoneBot 内置了几种添加事件处理函数方式以方便处理:
- `@matcher.receive()`: 指示 NoneBot 接收一条新的用户消息以继续执行后续处理函数。
- `@matcher.got(key, [prompt="请输入key"], [args_parser=function])`: 指示 NoneBot 当 `state` 中不存在 `key` 时向用户发送 `prompt` 等待用户回复并赋值给 `state[key]`
这些装饰器可以套娃使用!例如:
```python
@matcher.got("key1")
@matcher.got("key2")
async def handle(bot: Bot, event: Event, state: dict):
pass
```
#### 事件处理函数参数
事件处理函数类型为 `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` 。
参数分别为:
1. [nonebot.typing.Bot](../api/typing.md#bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。
2. [nonebot.typing.Event](../api/typing.md#event): 即上报事件对象,可以获取到上报的所有信息。
3. `state`: 状态字典,可以存储任意的信息
#### 处理事件
在事件处理函数中,我们只需要对 `event` 做出相应的处理,存入状态字典 `state` 中,或者向用户发送消息、调用某个机器人 API 等等。
在 NoneBot 中,提供了几种特殊的处理函数:
##### `@matcher.args_parser`
这是一个装饰器,装饰一个函数来使它成为参数的默认解析函数,当使用 `matcher.got(xxx, [args_parser])` 获取到一条消息时,会运行 `matcher.got` 的 `args_parser` ,如果不存在则运行 `@matcher.args_parser`。
##### `matcher.pause`
这个函数用于结束当前事件处理函数,强制接收一条新的消息再运行**下一个消息处理函数**。
##### `matcher.reject`
这个函数用于结束当前事件处理函数,强制接收一条新的消息再**再次运行当前消息处理函数**。
##### `matcher.finish`
这个函数用于直接结束当前事件处理。
以上三个函数都拥有一个参数 `prompt`,用于向用户发送一条消息。
## 结语
至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示:
- 请千万注意事件处理器的优先级设定
- 在匹配规则中请勿使用耗时极长的函数
- 同一个用户可以跨群(私聊)继续他的事件处理(除非做出权限限制,将在后续介绍)

View File

@@ -3,7 +3,7 @@ home: true
heroImage: /logo.png
tagline: An asynchronous QQ bot framework.
actionText: 开始使用
actionLink: /guide/
actionLink: guide/
features:
- title: 简洁
details: 提供极其简洁易懂的 API使你可以毫无压力地开始验证你的绝佳创意只需编写最少量的代码即可实现丰富的功能。
@@ -11,5 +11,5 @@ features:
details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。
- title: 高性能
details: 采用异步 I/O利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。
footer: MIT Licensed | Copyright © 2020 NoneBot Team
footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team
---

View File

@@ -0,0 +1,7 @@
# 深入
## 它如何工作?
<!-- TODO: how to work -->
~~未填坑~~

View File

@@ -0,0 +1 @@
# 跨插件访问

View File

@@ -0,0 +1 @@
# 权限控制

View File

@@ -0,0 +1 @@
# 发布插件

View File

@@ -0,0 +1 @@
# 运行时插槽

View File

@@ -0,0 +1 @@
# 定时任务

View File

@@ -10,6 +10,12 @@
* [nonebot.config](config.html)
* [nonebot.plugin](plugin.html)
* [nonebot.message](message.html)
* [nonebot.matcher](matcher.html)
@@ -19,9 +25,6 @@
* [nonebot.permission](permission.html)
* [nonebot.sched](sched.html)
* [nonebot.log](log.html)
@@ -44,3 +47,6 @@
* [nonebot.adapters.cqhttp](adapters/cqhttp.html)
* [nonebot.adapters.ding](adapters/ding.html)

View File

@@ -69,6 +69,45 @@ Websocket 连接对象
Adapter 类型
### _abstract async classmethod_ `check_permission(driver, connection_type, headers, body)`
* **说明**
检查连接请求是否合法的函数,如果合法则返回当前连接 `唯一标识符`,通常为机器人 ID如果不合法则抛出 `RequestDenied` 异常。
* **参数**
* `driver: Driver`: Driver 对象
* `connection_type: str`: 连接类型
* `headers: dict`: 请求头
* `body: Optional[dict]`: 请求数据WebSocket 连接该部分为空
* **返回**
* `str`: 连接唯一标识符
* **异常**
* `RequestDenied`: 请求非法
### _abstract async_ `handle_message(message)`
@@ -108,7 +147,7 @@ Adapter 类型
```python
await bot.call_api("send_msg", data={"message": "hello world"})
await bot.call_api("send_msg", message="hello world"})
await bot.send_msg(message="hello world")
```
@@ -137,7 +176,7 @@ await bot.send_msg(message="hello world")
## _class_ `BaseEvent`
基类:`abc.ABC`
基类:`abc.ABC`, `typing.Generic`
Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。
@@ -148,7 +187,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上
* **参数**
* `raw_event: dict`: 原始上报消息
* `raw_event: Union[dict, T]`: 原始上报消息
@@ -270,7 +309,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上
* **参数**
* `message: Union[str, dict, list, MessageSegment, Message]`: 消息内容
* `message: Union[str, dict, list, BaseModel, MessageSegment, Message]`: 消息内容
@@ -311,7 +350,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上
* **说明**
缩减消息数组,即拼接相邻纯文本消息段
缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段

View File

@@ -5,29 +5,6 @@ sidebarDepth: 0
# NoneBot.adapters.cqhttp 模块
## CQHTTP (OneBot) v11 协议适配
协议详情请看: [CQHTTP](http://cqhttp.cc/) | [OneBot](https://github.com/howmanybots/onebot)
## `log(level, message)`
* **说明**
用于打印 CQHTTP 日志。
* **参数**
* `level: str`: 日志等级
* `message: str`: 日志信息
## `escape(s, *, escape_comma=True)`
@@ -64,9 +41,50 @@ sidebarDepth: 0
## `_b2s(b)`
## _exception_ `CQHTTPAdapterException`
转换布尔值为字符串。
基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException)
## _exception_ `ActionFailed`
基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException`
* **说明**
API 请求返回错误信息。
* **参数**
* `retcode: Optional[int]`: 错误码
## _exception_ `NetworkError`
基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException`
* **说明**
网络错误。
* **参数**
* `retcode: Optional[int]`: 错误码
## _exception_ `ApiNotAvailable`
基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException`
## _async_ `_check_reply(bot, event)`
@@ -158,7 +176,7 @@ sidebarDepth: 0
## _class_ `Bot`
基类:[`nonebot.adapters.BaseBot`](#None)
基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot)
CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。
@@ -169,6 +187,15 @@ CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。
* 返回: `"cqhttp"`
### _async classmethod_ `check_permission(driver, connection_type, headers, body)`
* **说明**
CQHTTP (OneBot) 协议鉴权。参考 [鉴权](https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md)
### _async_ `handle_message(message)`
@@ -261,7 +288,7 @@ CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。
## _class_ `Event`
基类:[`nonebot.adapters.BaseEvent`](#None)
基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent)
CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。
@@ -403,9 +430,13 @@ CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent)
## _class_ `MessageSegment`
基类:[`nonebot.adapters.BaseMessageSegment`](#None)
基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment)
CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。
## _class_ `Message`
基类:[`nonebot.adapters.BaseMessage`](#None)
基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage)
CQHTTP 协议 Message 适配。

View File

@@ -0,0 +1,380 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.adapters.ding 模块
## _exception_ `DingAdapterException`
基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException)
* **说明**
钉钉 Adapter 错误基类
## _exception_ `ActionFailed`
基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.ding.exception.DingAdapterException`
* **说明**
API 请求返回错误信息。
* **参数**
* `errcode: Optional[int]`: 错误码
* `errmsg: Optional[str]`: 错误信息
## _exception_ `ApiNotAvailable`
基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException`
## _exception_ `NetworkError`
基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException`
* **说明**
网络错误。
* **参数**
* `retcode: Optional[int]`: 错误码
## _exception_ `SessionExpired`
基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException`
* **说明**
发消息的 session 已经过期。
## _class_ `Bot`
基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot)
钉钉 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。
### _property_ `type`
* 返回: `"ding"`
### _async classmethod_ `check_permission(driver, connection_type, headers, body)`
* **说明**
钉钉协议鉴权。参考 [鉴权](https://ding-doc.dingtalk.com/doc#/serverapi2/elzz1p)
### _async_ `handle_message(body)`
* **说明**
处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。
* **参数**
* `message: dict`: 收到的上报消息
### _async_ `call_api(api, event=None, **data)`
* **说明**
调用 钉钉 协议 API
* **参数**
* `api: str`: API 名称
* `**data: Any`: API 参数
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `NetworkError`: 网络错误
* `ActionFailed`: API 调用失败
### _async_ `send(event, message, at_sender=False, **kwargs)`
* **说明**
根据 `event` 向触发事件的主体发送消息。
* **参数**
* `event: Event`: Event 对象
* `message: Union[str, Message, MessageSegment]`: 要发送的消息
* `at_sender: bool`: 是否 @ 事件主体
* `**kwargs`: 覆盖默认参数
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `ValueError`: 缺少 `user_id`, `group_id`
* `NetworkError`: 网络错误
* `ActionFailed`: API 调用失败
## _class_ `Event`
基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent)
钉钉 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。
### _property_ `raw_event`
原始上报消息
### _property_ `id`
* 类型: `Optional[str]`
* 说明: 消息 ID
### _property_ `name`
* 类型: `str`
* 说明: 事件名称,由 type.\`detail_type\` 组合而成
### _property_ `self_id`
* 类型: `str`
* 说明: 机器人自身 ID
### _property_ `time`
* 类型: `int`
* 说明: 消息的时间戳,单位 s
### _property_ `type`
* 类型: `str`
* 说明: 事件类型
### _property_ `detail_type`
* 类型: `str`
* 说明: 事件详细类型
### _property_ `sub_type`
* 类型: `None`
* 说明: 钉钉适配器无事件子类型
### _property_ `user_id`
* 类型: `Optional[str]`
* 说明: 发送者 ID
### _property_ `group_id`
* 类型: `Optional[str]`
* 说明: 事件主体群 ID
### _property_ `to_me`
* 类型: `Optional[bool]`
* 说明: 消息是否与机器人相关
### _property_ `message`
* 类型: `Optional[Message]`
* 说明: 消息内容
### _property_ `reply`
* 类型: `None`
* 说明: 回复消息详情
### _property_ `raw_message`
* 类型: `Optional[str]`
* 说明: 原始消息
### _property_ `plain_text`
* 类型: `Optional[str]`
* 说明: 纯文本消息内容
### _property_ `sender`
* 类型: `Optional[dict]`
* 说明: 消息发送者信息
## _class_ `MessageSegment`
基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment)
钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。
### _static_ `actionCardSingleMultiBtns(title, text, btns=[], hideAvatar=False, btnOrientation='1')`
* **参数**
* `btnOrientation`: 0按钮竖直排列 1按钮横向排列
* `btns`: [{ "title": title, "actionURL": actionURL }, ...]
### _static_ `feedCard(links=[])`
* **参数**
* `links`: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...]
### _static_ `empty()`
不想回复消息到群里
## _class_ `Message`
基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage)
钉钉 协议 Message 适配。

View File

@@ -0,0 +1,285 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.config 模块
## 配置
NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-dotenv](https://saurabh-kumar.com/python-dotenv/) 来读取配置。
配置项需符合特殊格式或 json 序列化格式。详情见 [pydantic Field Type](https://pydantic-docs.helpmanual.io/usage/types/) 文档。
## _class_ `Env`
基类:`pydantic.env_settings.BaseSettings`
运行环境配置。大小写不敏感。
将会从 `nonebot.init 参数` > `环境变量` > `.env 环境配置文件` 的优先级读取配置。
### `environment`
* **类型**: `str`
* **默认值**: `"prod"`
* **说明**
当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。
## _class_ `Config`
基类:`nonebot.config.BaseConfig`
NoneBot 主要配置。大小写不敏感。
除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。
这些配置将会在 json 反序列化后一起带入 `Config` 类中。
### `driver`
* **类型**: `str`
* **默认值**: `"nonebot.drivers.fastapi"`
* **说明**
NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver`
### `host`
* **类型**: `IPvAnyAddress`
* **默认值**: `127.0.0.1`
* **说明**
NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。
### `port`
* **类型**: `int`
* **默认值**: `8080`
* **说明**
NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。
### `debug`
* **类型**: `bool`
* **默认值**: `False`
* **说明**
是否以调试模式运行 NoneBot。
### `api_root`
* **类型**: `Dict[str, str]`
* **默认值**: `{}`
* **说明**
以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。
* **示例**
```default
API_ROOT={"123456": "http://127.0.0.1:5700"}
```
### `api_timeout`
* **类型**: `Optional[float]`
* **默认值**: `30.`
* **说明**
API 请求超时时间,单位: 秒。
### `access_token`
* **类型**: `Optional[str]`
* **默认值**: `None`
* **说明**
API 请求以及上报所需密钥,在请求头中携带。
* **示例**
```http
POST /cqhttp/ HTTP/1.1
Authorization: Bearer kSLuTF2GC2Q4q4ugm3
```
### `secret`
* **类型**: `Optional[str]`
* **默认值**: `None`
* **说明**
HTTP POST 形式上报所需签名,在请求头中携带。
* **示例**
```http
POST /cqhttp/ HTTP/1.1
X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2
```
### `superusers`
* **类型**: `Set[int]`
* **默认值**: `set()`
* **说明**
机器人超级用户。
* **示例**
```default
SUPER_USERS=[12345789]
```
### `nickname`
* **类型**: `Set[str]`
* **默认值**: `set()`
* **说明**
机器人昵称。
### `command_start`
* **类型**: `Set[str]`
* **默认值**: `{"/"}`
* **说明**
命令的起始标记,用于判断一条消息是不是命令。
### `command_sep`
* **类型**: `Set[str]`
* **默认值**: `{"."}`
* **说明**
命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
### `session_expire_timeout`
* **类型**: `timedelta`
* **默认值**: `timedelta(minutes=2)`
* **说明**
等待用户回复的超时时间。
* **示例**
```default
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
```

View File

@@ -0,0 +1,246 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.drivers 模块
## 后端驱动适配基类
各驱动请继承以下基类
## _class_ `BaseDriver`
基类:`abc.ABC`
Driver 基类。将后端框架封装,以满足适配器使用。
### `_adapters`
* **类型**
`Dict[str, Type[Bot]]`
* **说明**
已注册的适配器列表
### _abstract_ `__init__(env, config)`
* **参数**
* `env: Env`: 包含环境信息的 Env 对象
* `config: Config`: 包含配置信息的 Config 对象
### `env`
* **类型**
`str`
* **说明**
环境名称
### `config`
* **类型**
`Config`
* **说明**
配置对象
### `_clients`
* **类型**
`Dict[str, Bot]`
* **说明**
已连接的 Bot
### _classmethod_ `register_adapter(name, adapter)`
* **说明**
注册一个协议适配器
* **参数**
* `name: str`: 适配器名称,用于在连接时进行识别
* `adapter: Type[Bot]`: 适配器 Class
### _abstract property_ `type`
驱动类型名称
### _abstract property_ `server_app`
驱动 APP 对象
### _abstract property_ `asgi`
驱动 ASGI 对象
### _abstract property_ `logger`
驱动专属 logger 日志记录器
### _property_ `bots`
* **类型**
`Dict[str, Bot]`
* **说明**
获取当前所有已连接的 Bot
### _abstract_ `on_startup(func)`
注册一个在驱动启动时运行的函数
### _abstract_ `on_shutdown(func)`
注册一个在驱动停止时运行的函数
### _abstract_ `run(host=None, port=None, *args, **kwargs)`
* **说明**
启动驱动框架
* **参数**
* `host: Optional[str]`: 驱动绑定 IP
* `post: Optional[int]`: 驱动绑定端口
* `*args`
* `**kwargs`
### _abstract async_ `_handle_http()`
用于处理 HTTP 类型请求的函数
### _abstract async_ `_handle_ws_reverse()`
用于处理 WebSocket 类型请求的函数
## _class_ `BaseWebSocket`
基类:`object`
WebSocket 连接封装,统一接口方便外部调用。
### _abstract_ `__init__(websocket)`
* **参数**
* `websocket: Any`: WebSocket 连接对象
### _property_ `websocket`
WebSocket 连接对象
### _abstract property_ `closed`
* **类型**
`bool`
* **说明**
连接是否已经关闭
### _abstract async_ `accept()`
接受 WebSocket 连接请求
### _abstract async_ `close(code)`
关闭 WebSocket 连接请求
### _abstract async_ `receive()`
接收一条 WebSocket 信息
### _abstract async_ `send(data)`
发送一条 WebSocket 信息

View File

@@ -0,0 +1,118 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.drivers.fastapi 模块
## FastAPI 驱动适配
后端使用方法请参考: [FastAPI 文档](https://fastapi.tiangolo.com/)
## _class_ `Driver`
基类:[`nonebot.drivers.BaseDriver`](README.md#nonebot.drivers.BaseDriver)
FastAPI 驱动框架
* **上报地址**
* `/{adapter name}/`: HTTP POST 上报
* `/{adapter name}/http/`: HTTP POST 上报
* `/{adapter name}/ws`: WebSocket 上报
* `/{adapter name}/ws/`: WebSocket 上报
### _property_ `type`
驱动名称: `fastapi`
### _property_ `server_app`
`FastAPI APP` 对象
### _property_ `asgi`
`FastAPI APP` 对象
### _property_ `logger`
fastapi 使用的 logger
### `on_startup(func)`
参考文档: [Events](https://fastapi.tiangolo.com/advanced/events/#startup-event)
### `on_shutdown(func)`
参考文档: [Events](https://fastapi.tiangolo.com/advanced/events/#startup-event)
### `run(host=None, port=None, *, app=None, **kwargs)`
使用 `uvicorn` 启动 FastAPI
### _async_ `_handle_http(adapter, request, data=Body(Ellipsis))`
用于处理 HTTP 类型请求的函数
### _async_ `_handle_ws_reverse(adapter, websocket)`
用于处理 WebSocket 类型请求的函数
## _class_ `WebSocket`
基类:[`nonebot.drivers.BaseWebSocket`](README.md#nonebot.drivers.BaseWebSocket)
### _property_ `closed`
* **类型**
`bool`
* **说明**
连接是否已经关闭
### _async_ `accept()`
接受 WebSocket 连接请求
### _async_ `close(code=1000)`
关闭 WebSocket 连接请求
### _async_ `receive()`
接收一条 WebSocket 信息
### _async_ `send(data)`
发送一条 WebSocket 信息

View File

@@ -11,11 +11,22 @@ sidebarDepth: 0
这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。
## _exception_ `IgnoredException`
## _exception_ `NoneBotException`
基类:`Exception`
* **说明**
所有 NoneBot 发生的异常基类。
## _exception_ `IgnoredException`
基类:`nonebot.exception.NoneBotException`
* **说明**
指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。
@@ -31,7 +42,7 @@ sidebarDepth: 0
## _exception_ `PausedException`
基类:`Exception`
基类:`nonebot.exception.NoneBotException`
* **说明**
@@ -49,7 +60,7 @@ sidebarDepth: 0
## _exception_ `RejectedException`
基类:`Exception`
基类:`nonebot.exception.NoneBotException`
* **说明**
@@ -67,7 +78,7 @@ sidebarDepth: 0
## _exception_ `FinishedException`
基类:`Exception`
基类:`nonebot.exception.NoneBotException`
* **说明**
@@ -83,26 +94,9 @@ sidebarDepth: 0
## _exception_ `ExpiredException`
基类:`Exception`
* **说明**
指示 NoneBot 当前 `Matcher` 已失效。
* **用法**
`Matcher` 运行前检查时抛出。
## _exception_ `StopPropagation`
基类:`Exception`
基类:`nonebot.exception.NoneBotException`
* **说明**
@@ -117,9 +111,48 @@ sidebarDepth: 0
## _exception_ `RequestDenied`
基类:`nonebot.exception.NoneBotException`
* **说明**
Bot 连接请求不合法。
* **参数**
* `status_code: int`: HTTP 状态码
* `reason: str`: 拒绝原因
## _exception_ `AdapterException`
基类:`nonebot.exception.NoneBotException`
* **说明**
代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception`
* **参数**
* `adapter_name: str`: 标识 adapter
## _exception_ `ApiNotAvailable`
基类:`Exception`
基类:`nonebot.exception.AdapterException`
* **说明**
@@ -130,7 +163,7 @@ sidebarDepth: 0
## _exception_ `NetworkError`
基类:`Exception`
基类:`nonebot.exception.AdapterException`
* **说明**
@@ -141,16 +174,9 @@ sidebarDepth: 0
## _exception_ `ActionFailed`
基类:`Exception`
基类:`nonebot.exception.AdapterException`
* **说明**
API 请求成功返回数据,但 API 操作失败。
* **参数**
* `retcode`: 错误代码

View File

@@ -377,7 +377,7 @@ sidebarDepth: 0
### _async classmethod_ `send(message)`
### _async classmethod_ `send(message, **kwargs)`
* **说明**
@@ -392,8 +392,11 @@ sidebarDepth: 0
* `message: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
### _async classmethod_ `finish(message=None)`
### _async classmethod_ `finish(message=None, **kwargs)`
* **说明**
@@ -408,8 +411,11 @@ sidebarDepth: 0
* `message: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
### _async classmethod_ `pause(prompt=None)`
### _async classmethod_ `pause(prompt=None, **kwargs)`
* **说明**
@@ -424,8 +430,11 @@ sidebarDepth: 0
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
### _async classmethod_ `reject(prompt=None)`
### _async classmethod_ `reject(prompt=None, **kwargs)`
* **说明**
@@ -440,46 +449,4 @@ sidebarDepth: 0
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
## _class_ `MatcherGroup`
基类:`object`
事件响应器组合,统一管理。用法同 `Matcher`
### `__init__(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
* **说明**
创建一个事件响应器组合,参数为默认值,与 `Matcher.new` 一致
### `matchers`
* **类型**
`List[Type[Matcher]]`
* **说明**
组内事件响应器列表
### `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
* **说明**
在组中创建一个新的事件响应器,参数留空则使用组合默认值
:::danger 警告
如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数
:::
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api

View File

@@ -0,0 +1,143 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.message 模块
## 事件处理
NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供了多个插槽以进行事件的预处理等。
## `event_preprocessor(func)`
* **说明**
事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。
* **参数**
事件预处理函数接收三个参数。
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: dict`: 当前 State
## `event_postprocessor(func)`
* **说明**
事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。
* **参数**
事件后处理函数接收三个参数。
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: dict`: 当前事件运行前 State
## `run_preprocessor(func)`
* **说明**
运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。
* **参数**
运行预处理函数接收四个参数。
* `matcher: Matcher`: 当前要运行的事件响应器
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: dict`: 当前 State
## `run_postprocessor(func)`
* **说明**
运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。
* **参数**
运行后处理函数接收五个参数。
* `matcher: Matcher`: 运行完毕的事件响应器
* `exception: Optional[Exception]`: 事件响应器运行错误(如果存在)
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: dict`: 当前 State
## _async_ `handle_event(bot, event)`
* **说明**
处理一个事件。调用该函数以实现分发事件。
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* **示例**
```python
import asyncio
asyncio.create_task(handle_event(bot, event))
```

View File

@@ -28,21 +28,21 @@ sidebarDepth: 0
* `on_endswith` => `nonebot.plugin.on_endswith`
* `on_keyword` => `nonebot.plugin.on_keyword`
* `on_command` => `nonebot.plugin.on_command`
* `on_regex` => `nonebot.plugin.on_regex`
* `on_regex` => `nonebot.plugin.on_regex`
* `on_regex` => `nonebot.plugin.on_regex`
* `CommandGroup` => `nonebot.plugin.CommandGroup`
* `MatcherGroup` => `nonebot.plugin.MatcherGroup`
* `load_plugin` => `nonebot.plugin.load_plugin`
@@ -52,9 +52,18 @@ sidebarDepth: 0
* `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`
## `get_driver()`

File diff suppressed because it is too large Load Diff

View File

@@ -123,7 +123,7 @@ Rule(async_function, run_sync(sync_function))
## `keyword(msg)`
## `keyword(*keywords)`
* **说明**
@@ -135,23 +135,25 @@ Rule(async_function, run_sync(sync_function))
* **参数**
* `msg: str`: 关键词
* `*keywords: str`: 关键词
## `command(command)`
## `command(*cmds)`
* **说明**
命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。
可以通过 `state["_prefix"]["command"]` 获取匹配成功的命令(例:`("test",)`),通过 `state["_prefix"]["raw_command"]` 获取匹配成功的原始命令文本(例:`"/test"`)。
* **参数**
* `command: Tuples[str, ...]`: 命令内容
* `*cmds: Union[str, Tuple[str, ...]]`: 命令内容
@@ -173,7 +175,9 @@ Rule(async_function, run_sync(sync_function))
* **说明**
根据正则表达式进行匹配
根据正则表达式进行匹配
可以通过 `state["_matched"]` 获取正则表达式匹配成功的文本。
@@ -186,6 +190,10 @@ Rule(async_function, run_sync(sync_function))
* `flags: Union[int, re.RegexFlag]`: 正则标志
:::tip 提示
正则表达式匹配使用 search 而非 match如需从头匹配请使用 `r"^xxx"` 来确保匹配开头
:::
## `to_me()`

View File

@@ -110,7 +110,7 @@ sidebarDepth: 0
## `PreProcessor`
## `EventPreProcessor`
* **类型**
@@ -121,7 +121,55 @@ sidebarDepth: 0
* **说明**
消息预处理函数 PreProcessor 类型
事件预处理函数 EventPreProcessor 类型
## `EventPostProcessor`
* **类型**
`Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`
* **说明**
事件预处理函数 EventPostProcessor 类型
## `RunPreProcessor`
* **类型**
`Callable[[Matcher, Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`
* **说明**
事件响应器运行前预处理函数 RunPreProcessor 类型
## `RunPostProcessor`
* **类型**
`Callable[[Matcher, Optional[Exception], Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`
* **说明**
事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在)

View File

@@ -54,8 +54,6 @@ sidebarDepth: 0
## _class_ `DataclassEncoder`
基类:`json.encoder.JSONEncoder`
* **说明**

View File

@@ -1,31 +1,30 @@
# 概览
:::tip 提示
<!-- :::tip 提示
如果在阅读本文档时遇到难以理解的词汇,请随时查阅 [术语表](../glossary.md) 或使用 [Google 搜索](https://www.google.com/)。
:::
::: -->
:::tip 提示
初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。
:::
NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。
## 简介
除了起到解析消息的作用NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理器,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求
NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能
目前 NoneBot2 在 [FastAPI](https://fastapi.tiangolo.com/) 的基础上封装了与 [CQHTTP(OneBot) 协议](http://cqhttp.cc/)插件的网络交互
除了起到解析事件的作用NoneBot 还为插件提供了大量实用的预设操作和权限控制机制。对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求
得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式也是最建议的通信方式NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。
得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制NoneBot 处理事件的吞吐量有了很大的保障,再配合 WebSocket 通信方式也是最建议的通信方式NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。
需要注意的是NoneBot 仅支持 Python 3.7+ 及 CQHTTP(OneBot) 插件 v11+。
## 它如何工作?
~~未填坑~~
需要注意的是NoneBot 仅支持 **Python 3.7+**
## 特色
- 提供直观的测试前端
NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**
- 提供使用简易的脚手架
- 提供丰富的官方插件
- 提供可添加/替换的驱动以及协议选项
- 基于异步 I/O
- 同时支持 HTTP 和反向 WebSocket 通信方式
- 支持多个机器人账号负载均衡

View File

@@ -0,0 +1,159 @@
# 事件处理
在上一章中,我们已经注册了事件响应器,现在我们可以正式编写事件处理逻辑了!
## [事件处理函数](../api/typing.md#handler)
```python{1,2,8,9}
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海则args为上海
if args:
state["city"] = args # 如果用户发送了参数则直接赋值
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: dict):
city = state["city"]
if city not in ["上海", "北京"]:
await weather.reject("你想查询的城市暂不支持,请重新输入!")
city_weather = await get_weather(city)
await weather.finish(city_weather)
```
在之前的样例中,我们定义了两个函数 `handle_first_receive`, `handle_city`,他们被事件响应器的装饰器装饰从而成为事件响应器的事件处理函数。
:::tip 提示
在事件响应器中,事件处理函数是**顺序**执行的!
:::
### 添加一个事件处理函数
事件响应器提供了三种装饰事件处理函数的装饰器,分别是:
1. [handle()](../api/matcher.md#classmethod-handle)
2. [receive()](../api/matcher.md#classmethod-receive)
3. [got(key, prompt, args_parser)](../api/matcher.md#classmethod-got-key-prompt-none-args-parser-none)
#### handle()
简单的为事件响应器添加一个事件处理函数,这个函数将会在上一个处理函数正常返回执行完毕后立即执行。
#### receive()
指示 NoneBot 接收一条新的用户消息后继续执行该处理函数。此时函数将会接收到新的消息而非前一条消息,之前相关信息可以存储在 state 中。
特别的,当装饰的函数前没有其他事件处理函数,那么 `receive()` 不会接收一条新的消息而是直接使用第一条接收到的消息。
#### got(key, prompt, args_parser)
指示 NoneBot 当 `state` 中不存在 `key` 时向用户发送 `prompt` 等待用户回复并赋值给 `state[key]`。
`prompt` 可以为 `str`, `Message`, `MessageSegment`,若为空则不会向用户发送,若不为空则会在 format 之后发送,即 `prompt.format(**state)`,注意对 `{}` 进行转义。示例:
```python
@matcher.receive()
async def handle(bot: Bot, event: Event, state: dict):
state["key"] = "hello"
@matcher.got("key2", prompt="{key}!")
async def handle2(bot: Bot, event: Event, state: dict):
pass
```
`args_parser` 为参数处理函数,在这里传入一个新的函数以覆盖默认的参数处理。详情参照 [args_parser](#参数处理函数-args-parser)
特别的,这些装饰器都可以套娃使用:
```python
@matcher.got("key1")
@matcher.got("key2")
async def handle(bot: Bot, event: Event, state: dict):
pass
```
### 事件处理函数参数
事件处理函数类型为 `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` 。
参数分别为:
1. [nonebot.typing.Bot](../api/typing.md#bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。
2. [nonebot.typing.Event](../api/typing.md#event): 即上报事件对象,可以获取到上报的所有信息。
3. `state`: 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如:
- `state["_current_key"]`: 存储当前 `got` 获取的参数名
- `state["_prefix"]`, `state["_suffix"]`: 存储当前 TRIE 匹配的前缀/后缀,可以通过该值获取用户命令的原始命令
### 参数处理函数 args_parser
在使用 `got` 获取用户输入参数时需要对用户的消息进行处理以转换为我们所需要的信息。在默认情况下NoneBot 会把用户的消息字符串原封不动的赋值给 `state[key]` 。可以通过以下两种方式修改默认处理逻辑:
- `@matcher.args_parser` 装饰器:直接装饰一个函数作为参数处理器
- `got(key, prompt, args_parser)`:直接把函数作为参数传入
参数处理函数类型为:`Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`,即:
```python
async def parser(bot: Bot, event: Event, state: dict):
state[state["_current_key"]] = str(event.message)
```
特别的,`state["_current_key"]` 中存储了当前获取的参数名
### 逻辑控制
NoneBot 也为事件处理函数提供了一些便捷的逻辑控制函数:
#### `matcher.send`
这个函数用于发送一条消息给当前交互的用户。~~其实这并不是一个逻辑控制函数,只是不知道放在哪里……~~
#### `matcher.pause`
这个函数用于结束当前事件处理函数,强制接收一条新的消息再运行**下一个消息处理函数**。
#### `matcher.reject`
这个函数用于结束当前事件处理函数,强制接收一条新的消息再**再次运行当前消息处理函数**。常用于用户输入信息不符合预期。
#### `matcher.finish`
这个函数用于直接结束当前事件处理。
以上三个函数都拥有一个参数 `message` / `prompt`,用于向用户发送一条消息。以及 `**kwargs` 直接传递给 `bot.send` 的额外参数。
## 常用事件处理结构
```python
matcher = on_command("test")
# 修改默认参数处理
@matcher.args_parser
async def parse(bot: Bot, event: Event, state: dict):
print(state["_current_key"], ":", str(event.message))
state[state["_current_key"]] = str(event.message)
@matcher.handle()
async def first_receive(bot: Bot, event: Event, state: dict):
# 获取用户原始命令,如:/test
print(state["_prefix"]["raw_command"])
# 处理用户输入参数,如:/test arg1 arg2
raw_args = str(event.message).strip()
if raw_args:
arg_list = raw_args.split()
# 将参数存入state以阻止后续再向用户询问参数
state["arg1"] = arg_list[0]
@matcher.got("arg1", prompt="参数?")
async def arg_handle(bot: Bot, event: Event, state: dict):
# 在这里对参数进行验证
if state["arg1"] not in ["allow", "list"]:
await matcher.reject("参数不正确!请重新输入")
# 发送一些信息
await bot.send(event, "message")
await matcher.send("message")
await matcher.finish("message")
```

View File

@@ -0,0 +1,144 @@
# 注册事件响应器
好了,现在插件已经创建完毕,我们可以开始编写实际代码了,下面将以一个简易单文件天气查询插件为例。
在插件目录下 `weather.py` 中添加如下代码:
```python
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event
weather = on_command("天气", rule=to_me(), priority=5)
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海则args为上海
if args:
state["city"] = args # 如果用户发送了参数则直接赋值
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: dict):
city = state["city"]
if city not in ["上海", "北京"]:
await weather.reject("你想查询的城市暂不支持,请重新输入!")
city_weather = await get_weather(city)
await weather.finish(city_weather)
async def get_weather(city: str):
return f"{city}的天气是..."
```
为了简单起见,我们在这里的例子中没有接入真实的天气数据,但要接入也非常简单,你可以使用中国天气网、和风天气等网站提供的 API。
接下来我们来说明这段代码是如何工作的。
:::tip 提示
从这里开始,你需要对 Python 的 asyncio 编程有所了解,因为 NoneBot 是完全基于 asyncio 的,具体可以参考 [廖雪峰的 Python 教程](https://www.liaoxuefeng.com/wiki/1016959663602400/1017959540289152)
:::
## [事件响应器](../api/matcher.md)
```python{4}
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.permission import Permission
weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5)
```
在上方代码中,我们注册了一个事件响应器 `Matcher`,它由几个部分组成:
1. `on_command` 注册一个消息类型的命令处理器
2. `"天气"` 指定 command 参数 - 命令名
3. `rule` 补充事件响应器的匹配规则
4. `priority` 事件响应器优先级
5. `block` 是否阻止事件传递
其他详细配置可以参考 API 文档,下面我们详细说明各个部分:
### 事件响应器类型 type
事件响应器类型其实就是对应事件的类型 `Event.type` NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。
以下所有类型的事件响应器都是由 `on(type, rule)` 的形式进行了简化封装。
- `on("事件类型")`: 基础事件响应器,第一个参数为事件类型,空字符串表示不限
- `on_metaevent()` ~ `on("meta_event")`: 元事件响应器
- `on_message()` ~ `on("message")`: 消息事件响应器
- `on_request()` ~ `on("request")`: 请求事件响应器
- `on_notice()` ~ `on("notice")`: 通知事件响应器
- `on_startswith(str)` ~ `on("message", startswith(str))`: 消息开头匹配响应器,参考 [startswith](../api/rule.md#startswith-msg)
- `on_endswith(str)` ~ `on("message", endswith(str))`: 消息结尾匹配响应器,参考 [endswith](../api/rule.md#endswith-msg)
- `on_keyword(set)` ~ `on("message", keyword(str))`: 消息关键词匹配响应器,参考 [keyword](../api/rule.md#keyword-keywords)
- `on_command(str|tuple)` ~ `on("message", command(str|tuple))`: 命令响应器,参考 [command](../api/rule.md#command-cmds)
- `on_regex(pattern_str)` ~ `on("message", regex(pattern_str))`: 正则匹配处理器,参考 [regex](../api/rule.md#regex-regex-flags-0)
### 匹配规则 rule
事件响应器的匹配规则即 `Rule`,详细内容在下方介绍。[直达](#自定义-rule)
### 优先级 priority
事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!**,优先级数字**越小**越先响应!优先级请从 `1` 开始排序!
:::tip 提示
使用 `nonebot-test` 可以看到当前所有事件响应器的执行流程,有助理解事件响应流程!
```bash
pip install nonebot2[test]
```
:::
### 阻断 block
当有任意事件响应器发出了阻止事件传递信号时,该事件将不再会传递给下一优先级,直接结束处理。
NoneBot 内置的事件响应器中,所有 `message` 类的事件响应器默认会阻断事件传递,其他则不会。
## 自定义 rule
rule 的出现使得 nonebot 对事件的响应可以非常自由nonebot 内置了一些规则:
- [startswith(msg)](../api/rule.md#startswith-msg)
- [endswith(msg)](../api/rule.md#endswith-msg)
- [keyword(\*keywords)](../api/rule.md#keyword-keywords)
- [command(\*cmds)](../api/rule.md#command-cmds)
- [regex(regex, flag)](../api/rule.md#regex-regex-flags-0)
以上规则都是返回类型为 `Rule` 的函数,`Rule` 由非负个 `RuleChecker` 组成,当所有 `RuleChecker` 返回 `True` 时匹配成功。这些 `Rule`, `RuleChecker` 的形式如下:
```python
from nonebot.rule import Rule
async def async_checker(bot: Bot, event: Event, state: dict) -> bool:
return True
def sync_checker(bot: Bot, event: Event, state: dict) -> bool:
return True
def check(arg1, args2):
async def _checker(bot: Bot, event: Event, state: dict) -> bool:
return bool(arg1 + arg2)
return Rule(_check)
```
`Rule` 和 `RuleChecker` 之间可以使用 `&` 互相组合:
```python
from nonebot.rule import Rule
Rule(async_checker1) & sync_checker & async_checker2
```
**_请勿将事件处理的逻辑写入 `rule` 中这会使得事件处理返回奇怪的响应。_**
:::danger 警告
`Rule(*checkers)` 只接受 async function或使用 `nonebot.utils.run_sync` 自行包裹 sync function。在使用 `&` 时NoneBot 会自动包裹 sync function
:::

View File

@@ -0,0 +1,119 @@
# 创建插件
如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了!
使用 `nb-cli` 创建包形式插件,或自行创建文件(夹)
```bash
nb plugin new
```
插件通常有两种形式,下面分别介绍
## 单文件形式
在插件目录下创建名为 `foo.py` 的 Python 文件,暂时留空,此时目录结构如下:
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── awesome_bot
│ └── plugins
│ └── `foo.py`
├── .env
├── .env.dev
├── .env.prod
├── .gitignore
├── bot.py
├── docker-compose.yml
├── Dockerfile
├── pyproject.toml
└── README.md
:::
<!-- prettier-ignore-end -->
这个时候它已经可以被称为一个插件了,尽管它还什么都没做。
## 包形式(推荐)
在插件目录下创建文件夹 `foo`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下:
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── awesome_bot
│ └── plugins
│ └── `foo`
│ └── `__init__.py`
├── .env
├── .env.dev
├── .env.prod
├── .gitignore
├── bot.py
├── docker-compose.yml
├── Dockerfile
├── pyproject.toml
└── README.md
:::
<!-- prettier-ignore-end -->
这个时候 `foo` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。
### 推荐结构(仅供参考)
<!-- prettier-ignore-start -->
:::vue
foo
├── `__init__.py`
├── `config.py`
├── `data_source.py`
└── `model.py`
:::
<!-- prettier-ignore-end -->
#### \_\_init\_\_.py
在该文件中编写各类事件响应及处理逻辑。
#### config.py
在该文件中使用 `pydantic` 定义插件所需要的配置项以及类型。
示例:
```python
from pydantic import BaseSetting
class Config(BaseSetting):
# plugin custom config
plugin_setting: str = "default"
class Config:
extra = "ignore"
```
并在 `__init__.py` 文件中添加以下行
```python
import nonebot
from .config import Config
global_config = nonebot.get_driver().config
plugin_config = Config(**global_config.dict())
```
此时就可以通过 `plugin_config.plugin_setting` 获取到插件所需要的配置项了。
#### data_source.py
在该文件中编写数据获取函数。
:::warning 警告
数据获取应尽量使用**异步**处理!例如使用 [httpx](https://www.python-httpx.org/) 而非 [requests](https://requests.readthedocs.io/en/master/)
:::
#### model.py
在该文件中编写数据库模型。

View File

@@ -4,16 +4,12 @@
## 目录结构
首先,我们可以使用 `nb-cli` 或者自行创建项目目录:
首先,我们可以使用 `nb-cli` 或者自行创建完整的项目目录:
```bash
pip install nonebot2[cli]
# pip install nb-cli
nb create
```
这将创建默认的目录结构
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot

View File

@@ -0,0 +1,9 @@
# 结语
至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示:
- 请千万注意事件处理器的优先级设定
- 在匹配规则中请勿使用耗时极长的函数
- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍)
如果你还不能满足,前往 [进阶](../advanced/README.md) 获得更多的功能信息。

View File

@@ -4,38 +4,53 @@
## 最小实例
使用你最熟悉的编辑器或 IDE创建一个名为 `bot.py` 的文件,内容如下
如果你已经按照推荐方式安装了 `nb-cli`,使用脚手架创建一个空项目
```bash
nb create
```
根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`
如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE创建一个名为 `bot.py` 的文件,内容如下:
```python{3,4,7}
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter("cqhttp", CQHTTPBot)
nonebot.load_builtin_plugins()
if __name__ == "__main__":
nonebot.run()
```
这几行高亮代码将依次:
## 解读
1. 使用默认配置初始化 NoneBot 包
在上方 `bot.py` 中,这几行高亮代码将依次:
1. 使用默认配置初始化 NoneBot
2. 加载 NoneBot 内置的插件
3. 在地址 `127.0.0.1:8080` 运行 NoneBot
在命令行使用如下命令即可运行这个 NoneBot 实例:
```bash
# nb-cli
nb run
# 其他
python bot.py
```
运行后会产生如下日志:
```default
```plain
09-14 21:02:00 [INFO] nonebot | Succeeded to import "nonebot.plugins.base"
09-14 21:02:00 [INFO] nonebot | Running NoneBot...
09-14 21:02:00 [INFO] uvicorn | Started server process [1234]
09-14 21:02:00 [INFO] uvicorn | Waiting for application startup.
09-14 21:02:00 [INFO] nonebot | Scheduler Started
09-14 21:02:00 [INFO] uvicorn | Application startup complete.
09-14 21:02:00 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)
```
@@ -46,23 +61,23 @@ python bot.py
目前支持的协议有:
- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot)
- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot/blob/master/README.md)
QQ 协议端举例:
- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai)
- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded)
- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api)
- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo))
- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded)
- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai)
- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api)
- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq))
这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例
1. 下载 go-cqhttp 对应平台的 release 文件
2. 双击 exe 文件或者使用 `./go-cqhttp` 启动
1. 下载 go-cqhttp 对应平台的 release 文件[点此前往](https://github.com/Mrs4s/go-cqhttp/releases)
2. 运行 exe 文件或者使用 `./go-cqhttp` 启动
3. 生成默认配置文件并修改默认配置
```json{2,3,30-31}
```json{2,3,35-36,42}
{
"uin": 你的QQ号,
"password": "你的密码",
@@ -75,6 +90,11 @@ QQ 协议端举例:
"relogin_delay": 3,
"max_relogin_times": 0
},
"_rate_limit": {
"enabled": false,
"frequency": 0,
"bucket_size": 0
},
"ignore_invalid_cqcode": false,
"force_fragmented": true,
"heartbeat_interval": 0,
@@ -99,9 +119,16 @@ QQ 协议端举例:
"reverse_reconnect_interval": 3000
}
],
"post_message_format": "string",
"post_message_format": "array",
"use_sso_address": false,
"debug": false,
"log_level": ""
"log_level": "",
"web_ui": {
"enabled": true,
"host": "0.0.0.0",
"web_ui_port": 9999,
"web_input": false
}
}
```
@@ -136,11 +163,11 @@ QQ 协议端举例:
现在,尝试向你的 QQ 机器人账号发送如下内容:
```default
/say 你好,世界
/echo 你好,世界
```
到这里如果一切 OK你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅!
<ClientOnly>
<Messenger :messages="[{ position: 'right', msg: '/say 你好,世界' }, { position: 'left', msg: '你好,世界' }]"/>
<Messenger :messages="[{ position: 'right', msg: '/echo 你好,世界' }, { position: 'left', msg: '你好,世界' }]"/>
</ClientOnly>

View File

@@ -0,0 +1,87 @@
# 安装
## NoneBot
:::warning 注意
请确保你的 Python 版本 >= 3.7。
:::
:::warning 注意
请在安装 nonebot2 之前卸载 nonebot 1.x
```bash
pip uninstall nonebot
```
:::
### 通过脚手架安装(推荐安装方式)
1. (可选)使用你喜欢的 Python 环境管理工具创建新的虚拟环境。
2. 使用 `pip` (或其他) 安装 NoneBot 脚手架。
```bash
pip install nb-cli
```
3. 点个 star 吧
nonebot2: [![nb-cli](https://img.shields.io/github/stars/nonebot/nonebot2?style=social)](https://github.com/nonebot/nonebot2)
nb-cli: [![nb-cli](https://img.shields.io/github/stars/nonebot/nb-cli?style=social)](https://github.com/nonebot/nb-cli)
### 不使用脚手架(纯净安装)
```bash
# poetry
poetry add nonebot2
# pip
pip install nonebot2
```
如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装:
```bash
# master
poetry add git+https://github.com/nonebot/nonebot2.git#master
# dev
poetry add git+https://github.com/nonebot/nonebot2.git#dev
```
或者克隆 Git 仓库后手动安装:
```bash
git clone https://github.com/nonebot/nonebot2.git
cd nonebot2
poetry install --no-dev # 推荐
pip install . # 不推荐
```
## 安装插件
插件可以通过 `nb-cli` 进行安装,也可以自行安装并加载插件。
```bash
# 列出所有的插件
nb plugin list
# 搜索插件
nb plugin search xxx
# 安装插件
nb plugin install xxx
```
如果急于上线 Bot 或想要使用现成的插件,以下插件可作为参考:
### 官方插件
~~自用插件~~ ~~确信~~
- [NoneBot-Plugin-Docs](https://github.com/nonebot/nonebot2/tree/master/packages/nonebot-plugin-docs) 离线文档插件
- [NoneBot-Plugin-Test](https://github.com/nonebot/plugin-test) 本地机器人测试前端插件
- [NoneBot-Plugin-APScheduler](https://github.com/nonebot/plugin-apscheduler) 定时任务插件
- [NoneBot-Plugin-Sentry](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_sentry) Sentry 在线日志分析插件
- [NoneBot-Plugin-Status](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_status) 服务器状态查看插件
### 其他插件
还有更多的插件在 [这里](/plugin-store.md) 等着你发现~

View File

@@ -0,0 +1,116 @@
# 加载插件
在 [创建一个完整的项目](creating-a-project) 一章节中,我们已经创建了插件目录 `awesome_bot/plugins`,现在我们在机器人入口文件中加载它。当然,你也可以单独加载一个插件。
## 加载内置插件
`bot.py` 文件中添加以下行:
```python{5}
import nonebot
nonebot.init()
# 加载 nonebot 内置插件
nonebot.load_builtin_plugins()
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
这将会加载 nonebot 内置的插件,它包含:
- 命令 `say`:可由**superuser**使用,可以将消息内容由特殊纯文本转为富文本
- 命令 `echo`:可由任何人使用,将消息原样返回
以上命令均需要指定机器人,即私聊、群聊内@机器人、群聊内称呼机器人昵称。参考 [Rule: to_me](../api/rule.md#to-me)
## 加载插件目录
在 `bot.py` 文件中添加以下行:
```python{5}
import nonebot
nonebot.init()
# 加载插件目录,该目录下为各插件,以下划线开头的插件将不会被加载
nonebot.load_plugins("awesome_bot/plugins")
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
:::tip 提示
加载插件目录时,目录下以 `_` 下划线开头的插件将不会被加载!
:::
:::warning 提示
**插件不能存在相同名称!**
:::
:::danger 警告
插件间不应该存在过多的耦合,如果确实需要导入某个插件内的数据,可以参考 [进阶-跨插件访问](../advanced/export-and-require.md)
:::
## 加载单个插件
在 `bot.py` 文件中添加以下行:
```python{5,7}
import nonebot
nonebot.init()
# 加载一个 pip 安装的插件
nonebot.load_plugin("nonebot_plugin_status")
# 加载本地的单独插件
nonebot.load_plugin("awesome_bot.plugins.xxx")
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
## 子插件(嵌套插件)
在插件中同样可以加载子插件,例如如下插件目录结构:
<!-- prettier-ignore-start -->
:::vue
foo_plugin
├── `plugins`
│ ├── `sub_plugin1`
│ │ └── \_\_init\_\_.py
│ └── `sub_plugin2.py`
├── `__init__.py`
└── config.py
:::
<!-- prettier-ignore-end -->
在插件目录下的 `__init__.py` 中添加如下代码:
```python
from pathlib import Path
import nonebot
# store all subplugins
_sub_plugins = set()
# load sub plugins
_sub_plugins |= nonebot.load_plugins(
str((Path(__file__).parent / "plugins").resolve()))
```
插件将会被加载并存储于 `_sub_plugins` 中。
## 运行结果
尝试运行 `nb run` 或者 `python bot.py`,可以看到日志输出了类似如下内容:
```plain
09-19 21:51:59 [INFO] nonebot | Succeeded to import "nonebot.plugins.base"
09-19 21:51:59 [INFO] nonebot | Succeeded to import "plugin_in_folder"
```

View File

@@ -1,4 +1,5 @@
{
"sidebar": {},
"locales": {
"/": {
"label": "简体中文",
@@ -14,17 +15,28 @@
"text": "指南",
"link": "/guide/"
},
{
"text": "进阶",
"link": "/advanced/"
},
{
"text": "API",
"link": "/api/"
},
{
"text": "插件广场",
"link": "/plugin-store"
},
{
"text": "更新日志",
"link": "/changelog"
}
],
"sidebarDepth": 2,
"sidebar": {
"/guide/": [
{
"title": "指南",
"path": "",
"title": "开始",
"collapsable": false,
"sidebar": "auto",
"children": [
@@ -32,8 +44,41 @@
"installation",
"getting-started",
"creating-a-project",
"basic-configuration",
"writing-a-plugin"
"basic-configuration"
]
},
{
"title": "编写插件",
"collapsable": false,
"sidebar": "auto",
"children": [
"loading-a-plugin",
"creating-a-plugin",
"creating-a-matcher",
"creating-a-handler",
"end-or-start"
]
}
],
"/advanced/": [
{
"title": "进阶",
"collapsable": false,
"sidebar": "auto",
"children": [
"",
"scheduler",
"permission",
"runtime-hook",
"export-and-require"
]
},
{
"title": "发布",
"collapsable": false,
"sidebar": "auto",
"children": [
"publish-plugin"
]
}
],
@@ -51,6 +96,14 @@
"title": "nonebot.config 模块",
"path": "config"
},
{
"title": "nonebot.plugin 模块",
"path": "plugin"
},
{
"title": "nonebot.message 模块",
"path": "message"
},
{
"title": "nonebot.matcher 模块",
"path": "matcher"
@@ -63,10 +116,6 @@
"title": "nonebot.permission 模块",
"path": "permission"
},
{
"title": "nonebot.sched 模块",
"path": "sched"
},
{
"title": "nonebot.log 模块",
"path": "log"
@@ -98,6 +147,10 @@
{
"title": "nonebot.adapters.cqhttp 模块",
"path": "adapters/cqhttp"
},
{
"title": "nonebot.adapters.ding 模块",
"path": "adapters/ding"
}
]
}

View File

@@ -0,0 +1,15 @@
---
home: true
heroImage: /logo.png
tagline: An asynchronous bot framework.
actionText: 开始使用
actionLink: guide/
features:
- title: 简洁
details: 提供极其简洁易懂的 API使你可以毫无压力地开始验证你的绝佳创意只需编写最少量的代码即可实现丰富的功能。
- title: 易于扩展
details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。
- title: 高性能
details: 采用异步 I/O利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。
footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team
---

View File

@@ -0,0 +1,7 @@
# 深入
## 它如何工作?
<!-- TODO: how to work -->
~~未填坑~~

View File

@@ -0,0 +1 @@
# 跨插件访问

View File

@@ -0,0 +1 @@
# 事件处理函数重载

View File

@@ -0,0 +1 @@
# 权限控制

View File

@@ -0,0 +1 @@
# 发布插件

View File

@@ -0,0 +1 @@
# 运行时插槽

View File

@@ -0,0 +1,135 @@
# 定时任务
[`APScheduler`](https://apscheduler.readthedocs.io/en/latest/index.html) —— Advanced Python Scheduler
> Advanced Python Scheduler (APScheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. You can add new jobs or remove old ones on the fly as you please. If you store your jobs in a database, they will also survive scheduler restarts and maintain their state. When the scheduler is restarted, it will then run all the jobs it should have run while it was offline.
## 从 v1 迁移
`APScheduler` 作为 `nonebot` v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。`nonebot2` 已将 `APScheduler` 独立为 `nonebot_plugin_apscheduler` 插件,你可以在 [插件广场](https://v2.nonebot.dev/plugin-store.html) 中找到它。
相比于 `nonebot` v1 ,只需要安装插件并修改 `scheduler` 的导入方式即可完成迁移。
## 安装插件
### 通过 nb-cli
如正在使用 `nb-cli` 构建项目,你可以从插件市场复制安装命令或手动输入以下命令以添加 `nonebot_plugin_apscheduler`
```bash
nb plugin install nonebot_plugin_apscheduler
```
:::tip 提示
`nb-cli` 默认通过 `pypi` 安装,你可以使用 `-i [mirror]``--index [mirror]` 来使用镜像源安装。
:::
### 通过 poetry
执行以下命令以添加 `nonebot_plugin_apscheduler`
```bash
poetry add nonebot-plugin-apscheduler
```
:::tip 提示
由于稍后我们将使用 `nonebot.require()` 方法进行导入,所以无需额外的 `nonebot.load_plugin()`
:::
## 快速上手
1. 在需要设置定时任务的插件中,通过 `nonebot.require``nonebot_plugin_apscheduler` 导入 `scheduler` 对象
2. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务
将上述步骤归纳为最小实现的代码如下:
```python
from nonebot import require
scheduler = require('nonebot_plugin_apscheduler').scheduler
@scheduler.scheduled_job('cron', hour='*/2', id='xxx', args=[1], kwargs={arg2: 2})
async def run_every_2_hour(arg1, arg2):
pass
scheduler.add_job(run_every_day_from_program_start, "interval", days=1, id="xxx")
```
## 分步进行
### 导入 scheduler 对象
为了使插件能够实现定时任务,需要先将 `scheduler` 对象导入插件。
`nonebot2` 提供了 `nonebot.require` 方法来实现导入其他插件的内容,此处我们使用这个方法来导入 `scheduler` 对象。
`nonebot` 使用的 `scheduler` 对象为 `AsyncScheduler`
> 使用该方法传入的插件本身也需要有对应实现,关于该方法的更多介绍可以参阅 [这里](./export-and-require.md)
```python
from nonebot import require
scheduler = require('nonebot_plugin_apscheduler').scheduler
```
### 编写定时任务
由于本部分为标准的通过 `APScheduler` 配置定时任务,有关指南请参阅 [APScheduler 官方文档](https://apscheduler.readthedocs.io/en/latest/userguide.html#adding-jobs)。
### 配置插件选项
根据项目的 `.env` 文件设置,向 `.env.*``bot.py` 文件添加 `nonebot_plugin_apscheduler` 的可选配置项
:::warning 注意
`.env.*` 文件的编写应遵循 nonebot2 对 `.env.*` 文件的编写要求
:::
#### `apscheduler_autostart`
类型:`bool`
默认值:`True`
是否自动启动 `APScheduler`
对于大多数情况,我们需要在 `nonebot2` 项目被启动时启动定时任务,则此处设为 `true`
### 在 `.env` 中添加
```bash
APSCHEDULER_AUTOSTART=true
```
### 在 `bot.py` 中添加
```python
nonebot.init(apscheduler_autostart=True)
```
#### `apscheduler_config`
类型:`dict`
默认值:`{"apscheduler.timezone": "Asia/Shanghai"}`
`APScheduler` 相关配置。修改/增加其中配置项需要确保 `prefix: apscheduler`
对于 `APScheduler` 的相关配置,请参阅 [scheduler-config](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-config) 和 [BaseScheduler](https://apscheduler.readthedocs.io/en/latest/modules/schedulers/base.html#apscheduler.schedulers.base.BaseScheduler)
> 官方文档在绝大多数时候能提供最准确和最具时效性的指南
### 在 `.env` 中添加
```bash
APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"}
```
### 在 `bot.py` 中添加
```python
nonebot.init(apscheduler_config={
"apscheduler.timezone": "Asia/Shanghai"
})
```

View File

@@ -0,0 +1,52 @@
# NoneBot Api Reference
* **模块索引**
* [nonebot](nonebot.html)
* [nonebot.config](config.html)
* [nonebot.plugin](plugin.html)
* [nonebot.message](message.html)
* [nonebot.matcher](matcher.html)
* [nonebot.rule](rule.html)
* [nonebot.permission](permission.html)
* [nonebot.log](log.html)
* [nonebot.utils](utils.html)
* [nonebot.typing](typing.html)
* [nonebot.exception](exception.html)
* [nonebot.drivers](drivers/)
* [nonebot.drivers.fastapi](drivers/fastapi.html)
* [nonebot.adapters](adapters/)
* [nonebot.adapters.cqhttp](adapters/cqhttp.html)
* [nonebot.adapters.ding](adapters/ding.html)

View File

@@ -0,0 +1,423 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.adapters 模块
## 协议适配基类
各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器
## _class_ `Bot`
基类:`abc.ABC`
Bot 基类。用于处理上报消息,并提供 API 调用接口。
### _abstract_ `__init__(driver, connection_type, config, self_id, *, websocket=None)`
* **参数**
* `driver: Driver`: Driver 对象
* `connection_type: str`: http 或者 websocket
* `config: Config`: Config 对象
* `self_id: str`: 机器人 ID
* `websocket: Optional[WebSocket]`: Websocket 连接对象
### `driver`
Driver 对象
### `connection_type`
连接类型
### `config`
Config 配置对象
### `self_id`
机器人 ID
### `websocket`
Websocket 连接对象
### _abstract property_ `type`
Adapter 类型
### _abstract async classmethod_ `check_permission(driver, connection_type, headers, body)`
* **说明**
检查连接请求是否合法的函数,如果合法则返回当前连接 `唯一标识符`,通常为机器人 ID如果不合法则抛出 `RequestDenied` 异常。
* **参数**
* `driver: Driver`: Driver 对象
* `connection_type: str`: 连接类型
* `headers: dict`: 请求头
* `body: Optional[dict]`: 请求数据WebSocket 连接该部分为空
* **返回**
* `str`: 连接唯一标识符
* **异常**
* `RequestDenied`: 请求非法
### _abstract async_ `handle_message(message)`
* **说明**
处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。
* **参数**
* `message: dict`: 收到的上报消息
### _abstract async_ `call_api(api, **data)`
* **说明**
调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
* **参数**
* `api: str`: API 名称
* `**data`: API 数据
* **示例**
```python
await bot.call_api("send_msg", message="hello world")
await bot.send_msg(message="hello world")
```
### _abstract async_ `send(event, message, **kwargs)`
* **说明**
调用机器人基础发送消息接口
* **参数**
* `event: Event`: 上报事件
* `message: Union[str, Message, MessageSegment]`: 要发送的消息
* `**kwargs`
## _class_ `MessageSegment`
基类:`abc.ABC`
消息段基类
### `type`
* 类型: `str`
* 说明: 消息段类型
### `data`
* 类型: `Dict[str, Union[str, list]]`
* 说明: 消息段数据
## _class_ `Message`
基类:`list`, `abc.ABC`
消息数组
### `__init__(message=None, *args, **kwargs)`
* **参数**
* `message: Union[str, list, dict, MessageSegment, Message, Any]`: 消息内容
### `append(obj)`
* **说明**
添加一个消息段到消息数组末尾
* **参数**
* `obj: Union[str, MessageSegment]`: 要添加的消息段
### `extend(obj)`
* **说明**
拼接一个消息数组或多个消息段到消息数组末尾
* **参数**
* `obj: Union[Message, Iterable[MessageSegment]]`: 要添加的消息数组
### `reduce()`
* **说明**
缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段
### `extract_plain_text()`
* **说明**
提取消息内纯文本消息
## _class_ `Event`
基类:`abc.ABC`, `pydantic.main.BaseModel`
Event 基类。提供获取关键信息的方法,其余信息可直接获取。
### _abstract_ `get_type()`
* **说明**
获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。
* **返回**
* `Literal["message", "notice", "request", "meta_event"]`
### _abstract_ `get_event_name()`
* **说明**
获取事件名称的方法。
* **返回**
* `str`
### _abstract_ `get_event_description()`
* **说明**
获取事件描述的方法,通常为事件具体内容。
* **返回**
* `str`
### `get_log_string()`
* **说明**
获取事件日志信息的方法,通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 `NoLogException` 异常。
* **返回**
* `str`
* **异常**
* `NoLogException`
### _abstract_ `get_user_id()`
* **说明**
获取事件主体 id 的方法,通常是用户 id 。
* **返回**
* `str`
### _abstract_ `get_session_id()`
* **说明**
获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。
* **返回**
* `str`
### _abstract_ `get_message()`
* **说明**
获取事件消息内容的方法。
* **返回**
* `Message`
### `get_plaintext()`
* **说明**
获取消息纯文本的方法,通常不需要修改,默认通过 `get_message().extract_plain_text` 获取。
* **返回**
* `str`
### _abstract_ `is_tome()`
* **说明**
获取事件是否与机器人有关的方法。
* **返回**
* `bool`

View File

@@ -0,0 +1,564 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.adapters.cqhttp 模块
## CQHTTP (OneBot) v11 协议适配
协议详情请看: [CQHTTP](https://github.com/howmanybots/onebot/blob/master/README.md) | [OneBot](https://github.com/howmanybots/onebot/blob/master/README.md)
# NoneBot.adapters.cqhttp.utils 模块
## `escape(s, *, escape_comma=True)`
* **说明**
对字符串进行 CQ 码转义。
* **参数**
* `s: str`: 需要转义的字符串
* `escape_comma: bool`: 是否转义逗号(`,`)。
## `unescape(s)`
* **说明**
对字符串进行 CQ 码去转义。
* **参数**
* `s: str`: 需要转义的字符串
# NoneBot.adapters.cqhttp.exception 模块
## _exception_ `ActionFailed`
基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException`
* **说明**
API 请求返回错误信息。
* **参数**
* `retcode: Optional[int]`: 错误码
## _exception_ `NetworkError`
基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException`
* **说明**
网络错误。
* **参数**
* `retcode: Optional[int]`: 错误码
# NoneBot.adapters.cqhttp.bot 模块
## _async_ `_check_reply(bot, event)`
* **说明**
检查消息中存在的回复,去除并赋值 `event.reply`, `event.to_me`
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
## `_check_at_me(bot, event)`
* **说明**
检查消息开头或结尾是否存在 @机器人,去除并赋值 `event.to_me`
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
## `_check_nickname(bot, event)`
* **说明**
检查消息开头是否存在,去除并赋值 `event.to_me`
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
## `_handle_api_result(result)`
* **说明**
处理 API 请求返回值。
* **参数**
* `result: Optional[Dict[str, Any]]`: API 返回数据
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `ActionFailed`: API 调用失败
## _class_ `Bot`
基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot)
CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。
### _property_ `type`
* 返回: `"cqhttp"`
### _async classmethod_ `check_permission(driver, connection_type, headers, body)`
* **说明**
CQHTTP (OneBot) 协议鉴权。参考 [鉴权](https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md)
### _async_ `handle_message(message)`
* **说明**
调用 [_check_reply](#async-check-reply-bot-event), [_check_at_me](#check-at-me-bot-event), [_check_nickname](#check-nickname-bot-event) 处理事件并转换为 [Event](#class-event)
### _async_ `call_api(api, **data)`
* **说明**
调用 CQHTTP 协议 API
* **参数**
* `api: str`: API 名称
* `**data: Any`: API 参数
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `NetworkError`: 网络错误
* `ActionFailed`: API 调用失败
### _async_ `send(event, message, at_sender=False, **kwargs)`
* **说明**
根据 `event` 向触发事件的主体发送消息。
* **参数**
* `event: Event`: Event 对象
* `message: Union[str, Message, MessageSegment]`: 要发送的消息
* `at_sender: bool`: 是否 @ 事件主体
* `**kwargs`: 覆盖默认参数
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `ValueError`: 缺少 `user_id`, `group_id`
* `NetworkError`: 网络错误
* `ActionFailed`: API 调用失败
# NoneBot.adapters.cqhttp.message 模块
## _class_ `MessageSegment`
基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment)
CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。
## _class_ `Message`
基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message)
CQHTTP 协议 Message 适配。
# NoneBot.adapters.cqhttp.permission 模块
## `PRIVATE`
* **说明**: 匹配任意私聊消息类型事件
## `PRIVATE_FRIEND`
* **说明**: 匹配任意好友私聊消息类型事件
## `PRIVATE_GROUP`
* **说明**: 匹配任意群临时私聊消息类型事件
## `PRIVATE_OTHER`
* **说明**: 匹配任意其他私聊消息类型事件
## `GROUP`
* **说明**: 匹配任意群聊消息类型事件
## `GROUP_MEMBER`
* **说明**: 匹配任意群员群聊消息类型事件
:::warning 警告
该权限通过 event.sender 进行判断且不包含管理员以及群主!
:::
## `GROUP_ADMIN`
* **说明**: 匹配任意群管理员群聊消息类型事件
## `GROUP_OWNER`
* **说明**: 匹配任意群主群聊消息类型事件
# NoneBot.adapters.cqhttp.event 模块
## _class_ `Event`
基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event)
CQHTTP 协议事件,字段与 CQHTTP 一致。各事件字段参考 [CQHTTP 文档](https://github.com/howmanybots/onebot/blob/master/README.md)
## _class_ `MessageEvent`
基类:`nonebot.adapters.cqhttp.event.Event`
消息事件
### `to_me`
* **说明**
消息是否与机器人有关
* **类型**
`bool`
### `reply`
* **说明**
消息中提取的回复消息,内容为 `get_msg` API 返回结果
* **类型**
`Optional[Reply]`
## _class_ `PrivateMessageEvent`
基类:`nonebot.adapters.cqhttp.event.MessageEvent`
私聊消息
## _class_ `GroupMessageEvent`
基类:`nonebot.adapters.cqhttp.event.MessageEvent`
群消息
## _class_ `NoticeEvent`
基类:`nonebot.adapters.cqhttp.event.Event`
通知事件
## _class_ `GroupUploadNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
群文件上传事件
## _class_ `GroupAdminNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
群管理员变动
## _class_ `GroupDecreaseNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
群成员减少事件
## _class_ `GroupIncreaseNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
群成员增加事件
## _class_ `GroupBanNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
群禁言事件
## _class_ `FriendAddNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
好友添加事件
## _class_ `GroupRecallNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
群消息撤回事件
## _class_ `FriendRecallNoticeEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
好友消息撤回事件
## _class_ `NotifyEvent`
基类:`nonebot.adapters.cqhttp.event.NoticeEvent`
提醒事件
## _class_ `PokeNotifyEvent`
基类:`nonebot.adapters.cqhttp.event.NotifyEvent`
戳一戳提醒事件
## _class_ `LuckyKingNotifyEvent`
基类:`nonebot.adapters.cqhttp.event.NotifyEvent`
群红包运气王提醒事件
## _class_ `HonorNotifyEvent`
基类:`nonebot.adapters.cqhttp.event.NotifyEvent`
群荣誉变更提醒事件
## _class_ `RequestEvent`
基类:`nonebot.adapters.cqhttp.event.Event`
请求事件
## _class_ `FriendRequestEvent`
基类:`nonebot.adapters.cqhttp.event.RequestEvent`
加好友请求事件
## _class_ `GroupRequestEvent`
基类:`nonebot.adapters.cqhttp.event.RequestEvent`
加群请求/邀请事件
## _class_ `MetaEvent`
基类:`nonebot.adapters.cqhttp.event.Event`
元事件
## _class_ `LifecycleMetaEvent`
基类:`nonebot.adapters.cqhttp.event.MetaEvent`
生命周期元事件
## _class_ `HeartbeatMetaEvent`
基类:`nonebot.adapters.cqhttp.event.MetaEvent`
心跳元事件
## `get_event_model(event_name)`
* **说明**
根据事件名获取对应 `Event Model``FallBack Event Model` 列表
* **返回**
* `List[Type[Event]]`

View File

@@ -0,0 +1,293 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.adapters.ding 模块
## 钉钉群机器人 协议适配
协议详情请看: [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p)
# NoneBot.adapters.ding.exception 模块
## _exception_ `DingAdapterException`
基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException)
* **说明**
钉钉 Adapter 错误基类
## _exception_ `ActionFailed`
基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.ding.exception.DingAdapterException`
* **说明**
API 请求返回错误信息。
* **参数**
* `errcode: Optional[int]`: 错误码
* `errmsg: Optional[str]`: 错误信息
## _exception_ `NetworkError`
基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException`
* **说明**
网络错误。
* **参数**
* `retcode: Optional[int]`: 错误码
## _exception_ `SessionExpired`
基类:`nonebot.adapters.ding.exception.ApiNotAvailable`, `nonebot.adapters.ding.exception.DingAdapterException`
* **说明**
发消息的 session 已经过期。
# NoneBot.adapters.ding.bot 模块
## _class_ `Bot`
基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot)
钉钉 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。
### _property_ `type`
* 返回: `"ding"`
### _async classmethod_ `check_permission(driver, connection_type, headers, body)`
* **说明**
钉钉协议鉴权。参考 [鉴权](https://ding-doc.dingtalk.com/doc#/serverapi2/elzz1p)
### _async_ `call_api(api, event=None, **data)`
* **说明**
调用 钉钉 协议 API
* **参数**
* `api: str`: API 名称
* `**data: Any`: API 参数
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `NetworkError`: 网络错误
* `ActionFailed`: API 调用失败
### _async_ `send(event, message, at_sender=False, **kwargs)`
* **说明**
根据 `event` 向触发事件的主体发送消息。
* **参数**
* `event: Event`: Event 对象
* `message: Union[str, Message, MessageSegment]`: 要发送的消息
* `at_sender: bool`: 是否 @ 事件主体
* `**kwargs`: 覆盖默认参数
* **返回**
* `Any`: API 调用返回数据
* **异常**
* `ValueError`: 缺少 `user_id`, `group_id`
* `NetworkError`: 网络错误
* `ActionFailed`: API 调用失败
# NoneBot.adapters.ding.message 模块
## _class_ `MessageSegment`
基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment)
钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。
### _static_ `atAll()`
@全体
### _static_ `atMobiles(*mobileNumber)`
@指定手机号人员
### _static_ `text(text)`
发送 `text` 类型消息
### _static_ `image(picURL)`
发送 `image` 类型消息
### _static_ `extension(dict_)`
"标记 text 文本的 extension 属性,需要与 text 消息段相加。
### _static_ `markdown(title, text)`
发送 `markdown` 类型消息
### _static_ `actionCardSingleBtn(title, text, singleTitle, singleURL)`
发送 `actionCardSingleBtn` 类型消息
### _static_ `actionCardMultiBtns(title, text, btns, hideAvatar=False, btnOrientation='1')`
发送 `actionCardMultiBtn` 类型消息
* **参数**
* `btnOrientation`: 0按钮竖直排列 1按钮横向排列
* `btns`: [{ "title": title, "actionURL": actionURL }, ...]
### _static_ `feedCard(links)`
发送 `feedCard` 类型消息
* **参数**
* `links`: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...]
## _class_ `Message`
基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message)
钉钉 协议 Message 适配。
# NoneBot.adapters.ding.event 模块
## _class_ `Event`
基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event)
钉钉协议事件。各事件字段参考 [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p)
## _class_ `ConversationType`
基类:`str`, `enum.Enum`
An enumeration.
## _class_ `MessageEvent`
基类:`nonebot.adapters.ding.event.Event`
消息事件
## _class_ `PrivateMessageEvent`
基类:`nonebot.adapters.ding.event.MessageEvent`
私聊消息事件
## _class_ `GroupMessageEvent`
基类:`nonebot.adapters.ding.event.MessageEvent`
群消息事件

View File

@@ -0,0 +1,285 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.config 模块
## 配置
NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-dotenv](https://saurabh-kumar.com/python-dotenv/) 来读取配置。
配置项需符合特殊格式或 json 序列化格式。详情见 [pydantic Field Type](https://pydantic-docs.helpmanual.io/usage/types/) 文档。
## _class_ `Env`
基类:`pydantic.env_settings.BaseSettings`
运行环境配置。大小写不敏感。
将会从 `nonebot.init 参数` > `环境变量` > `.env 环境配置文件` 的优先级读取配置。
### `environment`
* **类型**: `str`
* **默认值**: `"prod"`
* **说明**
当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。
## _class_ `Config`
基类:`nonebot.config.BaseConfig`
NoneBot 主要配置。大小写不敏感。
除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。
这些配置将会在 json 反序列化后一起带入 `Config` 类中。
### `driver`
* **类型**: `str`
* **默认值**: `"nonebot.drivers.fastapi"`
* **说明**
NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver`
### `host`
* **类型**: `IPvAnyAddress`
* **默认值**: `127.0.0.1`
* **说明**
NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。
### `port`
* **类型**: `int`
* **默认值**: `8080`
* **说明**
NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。
### `debug`
* **类型**: `bool`
* **默认值**: `False`
* **说明**
是否以调试模式运行 NoneBot。
### `api_root`
* **类型**: `Dict[str, str]`
* **默认值**: `{}`
* **说明**
以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。
* **示例**
```default
API_ROOT={"123456": "http://127.0.0.1:5700"}
```
### `api_timeout`
* **类型**: `Optional[float]`
* **默认值**: `30.`
* **说明**
API 请求超时时间,单位: 秒。
### `access_token`
* **类型**: `Optional[str]`
* **默认值**: `None`
* **说明**
API 请求以及上报所需密钥,在请求头中携带。
* **示例**
```http
POST /cqhttp/ HTTP/1.1
Authorization: Bearer kSLuTF2GC2Q4q4ugm3
```
### `secret`
* **类型**: `Optional[str]`
* **默认值**: `None`
* **说明**
HTTP POST 形式上报所需签名,在请求头中携带。
* **示例**
```http
POST /cqhttp/ HTTP/1.1
X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2
```
### `superusers`
* **类型**: `Set[str]`
* **默认值**: `set()`
* **说明**
机器人超级用户。
* **示例**
```default
SUPER_USERS=["12345789"]
```
### `nickname`
* **类型**: `Set[str]`
* **默认值**: `set()`
* **说明**
机器人昵称。
### `command_start`
* **类型**: `Set[str]`
* **默认值**: `{"/"}`
* **说明**
命令的起始标记,用于判断一条消息是不是命令。
### `command_sep`
* **类型**: `Set[str]`
* **默认值**: `{"."}`
* **说明**
命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
### `session_expire_timeout`
* **类型**: `timedelta`
* **默认值**: `timedelta(minutes=2)`
* **说明**
等待用户回复的超时时间。
* **示例**
```default
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
```

View File

@@ -0,0 +1,318 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.drivers 模块
## 后端驱动适配基类
各驱动请继承以下基类
## _class_ `Driver`
基类:`abc.ABC`
Driver 基类。将后端框架封装,以满足适配器使用。
### `_adapters`
* **类型**
`Dict[str, Type[Bot]]`
* **说明**
已注册的适配器列表
### `_ws_connection_hook`
* **类型**
`Set[T_WebSocketConnectionHook]`
* **说明**
WebSocket 连接建立时执行的函数
### `_ws_disconnection_hook`
* **类型**
`Set[T_WebSocketDisconnectionHook]`
* **说明**
WebSocket 连接断开时执行的函数
### _abstract_ `__init__(env, config)`
* **参数**
* `env: Env`: 包含环境信息的 Env 对象
* `config: Config`: 包含配置信息的 Config 对象
### `env`
* **类型**
`str`
* **说明**
环境名称
### `config`
* **类型**
`Config`
* **说明**
配置对象
### `_clients`
* **类型**
`Dict[str, Bot]`
* **说明**
已连接的 Bot
### _classmethod_ `register_adapter(name, adapter)`
* **说明**
注册一个协议适配器
* **参数**
* `name: str`: 适配器名称,用于在连接时进行识别
* `adapter: Type[Bot]`: 适配器 Class
### _abstract property_ `type`
驱动类型名称
### _abstract property_ `server_app`
驱动 APP 对象
### _abstract property_ `asgi`
驱动 ASGI 对象
### _abstract property_ `logger`
驱动专属 logger 日志记录器
### _property_ `bots`
* **类型**
`Dict[str, Bot]`
* **说明**
获取当前所有已连接的 Bot
### _abstract_ `on_startup(func)`
注册一个在驱动启动时运行的函数
### _abstract_ `on_shutdown(func)`
注册一个在驱动停止时运行的函数
### `on_bot_connect(func)`
* **说明**
装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行。
* **函数参数**
* `bot: Bot`: 当前连接上的 Bot 对象
### `on_bot_disconnect(func)`
* **说明**
装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行。
* **函数参数**
* `bot: Bot`: 当前连接上的 Bot 对象
### `_bot_connect(bot)`
在 WebSocket 连接成功后,调用该函数来注册 bot 对象
### `_bot_disconnect(bot)`
在 WebSocket 连接断开后,调用该函数来注销 bot 对象
### _abstract_ `run(host=None, port=None, *args, **kwargs)`
* **说明**
启动驱动框架
* **参数**
* `host: Optional[str]`: 驱动绑定 IP
* `post: Optional[int]`: 驱动绑定端口
* `*args`
* `**kwargs`
### _abstract async_ `_handle_http()`
用于处理 HTTP 类型请求的函数
### _abstract async_ `_handle_ws_reverse()`
用于处理 WebSocket 类型请求的函数
## _class_ `WebSocket`
基类:`object`
WebSocket 连接封装,统一接口方便外部调用。
### _abstract_ `__init__(websocket)`
* **参数**
* `websocket: Any`: WebSocket 连接对象
### _property_ `websocket`
WebSocket 连接对象
### _abstract property_ `closed`
* **类型**
`bool`
* **说明**
连接是否已经关闭
### _abstract async_ `accept()`
接受 WebSocket 连接请求
### _abstract async_ `close(code)`
关闭 WebSocket 连接请求
### _abstract async_ `receive()`
接收一条 WebSocket 信息
### _abstract async_ `send(data)`
发送一条 WebSocket 信息

View File

@@ -0,0 +1,68 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.drivers.fastapi 模块
## FastAPI 驱动适配
后端使用方法请参考: [FastAPI 文档](https://fastapi.tiangolo.com/)
## _class_ `Driver`
基类:[`nonebot.drivers.Driver`](README.md#nonebot.drivers.Driver)
FastAPI 驱动框架
* **上报地址**
* `/{adapter name}/`: HTTP POST 上报
* `/{adapter name}/http/`: HTTP POST 上报
* `/{adapter name}/ws`: WebSocket 上报
* `/{adapter name}/ws/`: WebSocket 上报
### _property_ `type`
驱动名称: `fastapi`
### _property_ `server_app`
`FastAPI APP` 对象
### _property_ `asgi`
`FastAPI APP` 对象
### _property_ `logger`
fastapi 使用的 logger
### `on_startup(func)`
参考文档: [Events](https://fastapi.tiangolo.com/advanced/events/#startup-event)
### `on_shutdown(func)`
参考文档: [Events](https://fastapi.tiangolo.com/advanced/events/#startup-event)
### `run(host=None, port=None, *, app=None, **kwargs)`
使用 `uvicorn` 启动 FastAPI

View File

@@ -0,0 +1,193 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.exception 模块
## 异常
下列文档中的异常是所有 NoneBot 运行时可能会抛出的。
这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。
## _exception_ `NoneBotException`
基类:`Exception`
* **说明**
所有 NoneBot 发生的异常基类。
## _exception_ `IgnoredException`
基类:`nonebot.exception.NoneBotException`
* **说明**
指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。
* **参数**
* `reason`: 忽略事件的原因
## _exception_ `PausedException`
基类:`nonebot.exception.NoneBotException`
* **说明**
指示 NoneBot 结束当前 `Handler` 并等待下一条消息后继续下一个 `Handler`
可用于用户输入新信息。
* **用法**
可以在 `Handler` 中通过 `Matcher.pause()` 抛出。
## _exception_ `RejectedException`
基类:`nonebot.exception.NoneBotException`
* **说明**
指示 NoneBot 结束当前 `Handler` 并等待下一条消息后重新运行当前 `Handler`
可用于用户重新输入。
* **用法**
可以在 `Handler` 中通过 `Matcher.reject()` 抛出。
## _exception_ `FinishedException`
基类:`nonebot.exception.NoneBotException`
* **说明**
指示 NoneBot 结束当前 `Handler` 且后续 `Handler` 不再被运行。
可用于结束用户会话。
* **用法**
可以在 `Handler` 中通过 `Matcher.finish()` 抛出。
## _exception_ `StopPropagation`
基类:`nonebot.exception.NoneBotException`
* **说明**
指示 NoneBot 终止事件向下层传播。
* **用法**
`Matcher.block == True` 时抛出。
## _exception_ `RequestDenied`
基类:`nonebot.exception.NoneBotException`
* **说明**
Bot 连接请求不合法。
* **参数**
* `status_code: int`: HTTP 状态码
* `reason: str`: 拒绝原因
## _exception_ `AdapterException`
基类:`nonebot.exception.NoneBotException`
* **说明**
代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception`
* **参数**
* `adapter_name: str`: 标识 adapter
## _exception_ `NoLogException`
基类:`Exception`
* **说明**
指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息,可在 `get_log_string` 时抛出
## _exception_ `ApiNotAvailable`
基类:`nonebot.exception.AdapterException`
* **说明**
在 API 连接不可用时抛出。
## _exception_ `NetworkError`
基类:`nonebot.exception.AdapterException`
* **说明**
在网络出现问题时抛出,如: API 请求地址不正确, API 请求无返回或返回状态非正常等。
## _exception_ `ActionFailed`
基类:`nonebot.exception.AdapterException`
* **说明**
API 请求成功返回数据,但 API 操作失败。

View File

@@ -0,0 +1,42 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.log 模块
## 日志
NoneBot 使用 [loguru](https://github.com/Delgan/loguru) 来记录日志信息。
自定义 logger 请参考 [loguru](https://github.com/Delgan/loguru) 文档。
## `logger`
* **说明**
NoneBot 日志记录器对象。
* **默认信息**
* 格式: `[%(asctime)s %(name)s] %(levelname)s: %(message)s`
* 等级: `DEBUG` / `INFO` ,根据 config 配置改变
* 输出: 输出至 stdout
* **用法**
```python
from nonebot.log import logger
```

View File

@@ -0,0 +1,470 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.matcher 模块
## 事件响应器
该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行 对话 。
## `matchers`
* **类型**
`Dict[int, List[Type[Matcher]]]`
* **说明**
用于存储当前所有的事件响应器
## _class_ `Matcher`
基类:`object`
事件响应器类
### `module`
* **类型**
`Optional[str]`
* **说明**
事件响应器所在模块名称
### `type`
* **类型**
`str`
* **说明**
事件响应器类型
### `rule`
* **类型**
`Rule`
* **说明**
事件响应器匹配规则
### `permission`
* **类型**
`Permission`
* **说明**
事件响应器触发权限
### `priority`
* **类型**
`int`
* **说明**
事件响应器优先级
### `block`
* **类型**
`bool`
* **说明**
事件响应器是否阻止事件传播
### `temp`
* **类型**
`bool`
* **说明**
事件响应器是否为临时
### `expire_time`
* **类型**
`Optional[datetime]`
* **说明**
事件响应器过期时间点
### `_default_state`
* **类型**
`T_State`
* **说明**
事件响应器默认状态
### `_default_state_factory`
* **类型**
`Optional[T_State]`
* **说明**
事件响应器默认工厂函数
### `_default_parser`
* **类型**
`Optional[T_ArgsParser]`
* **说明**
事件响应器默认参数解析函数
### `__init__()`
实例化 Matcher 以便运行
### `handlers`
* **类型**
`List[T_Handler]`
* **说明**
事件响应器拥有的事件处理函数列表
### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, default_state_factory=None, expire_time=None)`
* **说明**
创建一个新的事件响应器,并存储至 [matchers](#matchers)
* **参数**
* `type_: str`: 事件响应器类型,与 `event.get_type()` 一致时触发,空字符串表示任意
* `rule: Optional[Rule]`: 匹配规则
* `permission: Optional[Permission]`: 权限
* `handlers: Optional[List[T_Handler]]`: 事件处理函数列表
* `temp: bool`: 是否为临时事件响应器,即触发一次后删除
* `priority: int`: 响应优先级
* `block: bool`: 是否阻止事件向更低优先级的响应器传播
* `module: Optional[str]`: 事件响应器所在模块名称
* `default_state: Optional[T_State]`: 默认状态 `state`
* `default_state_factory: Optional[T_StateFactory]`: 默认状态 `state` 的工厂函数
* `expire_time: Optional[datetime]`: 事件响应器最终有效时间点,过时即被删除
* **返回**
* `Type[Matcher]`: 新的事件响应器类
### _async classmethod_ `check_perm(bot, event)`
* **说明**
检查是否满足触发权限
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: 上报事件
* **返回**
* `bool`: 是否满足权限
### _async classmethod_ `check_rule(bot, event, state)`
* **说明**
检查是否满足匹配规则
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: 上报事件
* `state: T_State`: 当前状态
* **返回**
* `bool`: 是否满足匹配规则
### _classmethod_ `args_parser(func)`
* **说明**
装饰一个函数来更改当前事件响应器的默认参数解析函数
* **参数**
* `func: T_ArgsParser`: 参数解析函数
### _classmethod_ `handle()`
* **说明**
装饰一个函数来向事件响应器直接添加一个处理函数
* **参数**
*
### _classmethod_ `receive()`
* **说明**
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
* **参数**
*
### _classmethod_ `got(key, prompt=None, args_parser=None)`
* **说明**
装饰一个函数来指示 NoneBot 当要获取的 `key` 不存在时接收用户新的一条消息并经过 `ArgsParser` 处理后再运行该函数,如果 `key` 已存在则直接继续运行
* **参数**
* `key: str`: 参数名
* `prompt: Optional[Union[str, Message, MessageSegment]]`: 在参数不存在时向用户发送的消息
* `args_parser: Optional[T_ArgsParser]`: 可选参数解析函数,空则使用默认解析函数
### _async classmethod_ `send(message, **kwargs)`
* **说明**
发送一条消息给当前交互用户
* **参数**
* `message: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
### _async classmethod_ `finish(message=None, **kwargs)`
* **说明**
发送一条消息给当前交互用户并结束当前事件响应器
* **参数**
* `message: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
### _async classmethod_ `pause(prompt=None, **kwargs)`
* **说明**
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
* **参数**
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api
### _async classmethod_ `reject(prompt=None, **kwargs)`
* **说明**
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后重新运行当前处理函数
* **参数**
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
* `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api

View File

@@ -0,0 +1,143 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.message 模块
## 事件处理
NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供了多个插槽以进行事件的预处理等。
## `event_preprocessor(func)`
* **说明**
事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。
* **参数**
事件预处理函数接收三个参数。
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: T_State`: 当前 State
## `event_postprocessor(func)`
* **说明**
事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。
* **参数**
事件后处理函数接收三个参数。
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: T_State`: 当前事件运行前 State
## `run_preprocessor(func)`
* **说明**
运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。
* **参数**
运行预处理函数接收四个参数。
* `matcher: Matcher`: 当前要运行的事件响应器
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: T_State`: 当前 State
## `run_postprocessor(func)`
* **说明**
运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。
* **参数**
运行后处理函数接收五个参数。
* `matcher: Matcher`: 运行完毕的事件响应器
* `exception: Optional[Exception]`: 事件响应器运行错误(如果存在)
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: T_State`: 当前 State
## _async_ `handle_event(bot, event)`
* **说明**
处理一个事件。调用该函数以实现分发事件。
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* **示例**
```python
import asyncio
asyncio.create_task(handle_event(bot, event))
```

View File

@@ -0,0 +1,266 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot 模块
## 快捷导入
为方便使用,`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_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_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`
## `get_driver()`
* **说明**
获取全局 Driver 对象。可用于在计划任务的回调中获取当前 Driver 对象。
* **返回**
* `Driver`: 全局 Driver 对象
* **异常**
* `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
* **用法**
```python
driver = nonebot.get_driver()
```
## `get_app()`
* **说明**
获取全局 Driver 对应 Server App 对象。
* **返回**
* `Any`: Server App 对象
* **异常**
* `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
* **用法**
```python
app = nonebot.get_app()
```
## `get_asgi()`
* **说明**
获取全局 Driver 对应 Asgi 对象。
* **返回**
* `Any`: Asgi 对象
* **异常**
* `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
* **用法**
```python
asgi = nonebot.get_asgi()
```
## `get_bots()`
* **说明**
获取所有通过 ws 连接 NoneBot 的 Bot 对象。
* **返回**
* `Dict[str, Bot]`: 一个以字符串 ID 为键Bot 对象为值的字典
* **异常**
* `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用)
* **用法**
```python
bots = nonebot.get_bots()
```
## `init(*, _env_file=None, **kwargs)`
* **说明**
初始化 NoneBot 以及 全局 Driver 对象。
NoneBot 将会从 .env 文件中读取环境信息,并使用相应的 env 文件配置。
你也可以传入自定义的 _env_file 来指定 NoneBot 从该文件读取配置。
* **参数**
* `_env_file: Optional[str]`: 配置文件名,默认从 .env.{env_name} 中读取配置
* `**kwargs`: 任意变量,将会存储到 Config 对象里
* **返回**
* `None`
* **用法**
```python
nonebot.init(database=Database(...))
```
## `run(host=None, port=None, *args, **kwargs)`
* **说明**
启动 NoneBot即运行全局 Driver 对象。
* **参数**
* `host: Optional[str]`: 主机名IP若不传入则使用配置文件中指定的值
* `port: Optional[int]`: 端口,若不传入则使用配置文件中指定的值
* `*args`: 传入 Driver.run 的位置参数
* `**kwargs`: 传入 Driver.run 的命名参数
* **返回**
* `None`
* **用法**
```python
nonebot.run(host="127.0.0.1", port=8080)
```

View File

@@ -0,0 +1,63 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.permission 模块
## 权限
每个 `Matcher` 拥有一个 `Permission` ,其中是 **异步** `PermissionChecker` 的集合,只要有一个 `PermissionChecker` 检查结果为 `True` 时就会继续运行。
:::tip 提示
`PermissionChecker` 既可以是 async function 也可以是 sync function
:::
## `MESSAGE`
* **说明**: 匹配任意 `message` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 message type 的 Matcher。
## `NOTICE`
* **说明**: 匹配任意 `notice` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 notice type 的 Matcher。
## `REQUEST`
* **说明**: 匹配任意 `request` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 request type 的 Matcher。
## `METAEVENT`
* **说明**: 匹配任意 `meta_event` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 meta_event type 的 Matcher。
## `USER(*user, perm=<nonebot.permission.Permission object>)`
* **说明**
在白名单内且满足 perm
* **参数**
* `*user: str`: 白名单
* `perm: Permission`: 需要同时满足的权限
## `SUPERUSER`
* **说明**: 匹配任意超级用户消息类型事件

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,210 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.rule 模块
## 规则
每个事件响应器 `Matcher` 拥有一个匹配规则 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
:::tip 提示
`RuleChecker` 既可以是 async function 也可以是 sync function但在最终会被 `nonebot.utils.run_sync` 转换为 async function
:::
## _class_ `Rule`
基类:`object`
* **说明**
`Matcher` 规则类,当事件传递时,在 `Matcher` 运行前进行检查。
* **示例**
```python
Rule(async_function) & sync_function
# 等价于
from nonebot.utils import run_sync
Rule(async_function, run_sync(sync_function))
```
### `__init__(*checkers)`
* **参数**
* `*checkers: Callable[[Bot, Event, T_State], Awaitable[bool]]`: **异步** RuleChecker
### `checkers`
* **说明**
存储 `RuleChecker`
* **类型**
* `Set[Callable[[Bot, Event, T_State], Awaitable[bool]]]`
### _async_ `__call__(bot, event, state)`
* **说明**
检查是否符合所有规则
* **参数**
* `bot: Bot`: Bot 对象
* `event: Event`: Event 对象
* `state: T_State`: 当前 State
* **返回**
* `bool`
## `startswith(msg)`
* **说明**
匹配消息开头
* **参数**
* `msg: str`: 消息开头字符串
## `endswith(msg)`
* **说明**
匹配消息结尾
* **参数**
* `msg: str`: 消息结尾字符串
## `keyword(*keywords)`
* **说明**
匹配消息关键词
* **参数**
* `*keywords: str`: 关键词
## `command(*cmds)`
* **说明**
命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。
可以通过 `state["_prefix"]["command"]` 获取匹配成功的命令(例:`("test",)`),通过 `state["_prefix"]["raw_command"]` 获取匹配成功的原始命令文本(例:`"/test"`)。
* **参数**
* `*cmds: Union[str, Tuple[str, ...]]`: 命令内容
* **示例**
使用默认 `command_start`, `command_sep` 配置
命令 `("test",)` 可以匹配:`/test` 开头的消息
命令 `("test", "sub")` 可以匹配”`/test.sub` 开头的消息
:::tip 提示
命令内容与后续消息间无需空格!
:::
## `regex(regex, flags=0)`
* **说明**
根据正则表达式进行匹配。
可以通过 `state["_matched"]` 获取正则表达式匹配成功的文本。
* **参数**
* `regex: str`: 正则表达式
* `flags: Union[int, re.RegexFlag]`: 正则标志
:::tip 提示
正则表达式匹配使用 search 而非 match如需从头匹配请使用 `r"^xxx"` 来确保匹配开头
:::
## `to_me()`
* **说明**
通过 `event.is_tome()` 判断事件是否与机器人有关
* **参数**
*

View File

@@ -0,0 +1,214 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.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 模块导入。
## `T_State`
* **类型**
`Dict[Any, Any]`
* **说明**
事件处理状态 State 类型
## `T_StateFactory`
* **类型**
`Callable[[Bot, Event], Awaitable[T_State]]`
* **说明**
事件处理状态 State 类工厂函数
## `T_WebSocketConnectionHook`
* **类型**
`Callable[[Bot], Awaitable[None]]`
* **说明**
WebSocket 连接建立时执行的函数
## `T_WebSocketDisconnectionHook`
* **类型**
`Callable[[Bot], Awaitable[None]]`
* **说明**
WebSocket 连接断开时执行的函数
## `T_EventPreProcessor`
* **类型**
`Callable[[Bot, Event, T_State], Awaitable[None]]`
* **说明**
事件预处理函数 EventPreProcessor 类型
## `T_EventPostProcessor`
* **类型**
`Callable[[Bot, Event, T_State], Awaitable[None]]`
* **说明**
事件预处理函数 EventPostProcessor 类型
## `T_RunPreProcessor`
* **类型**
`Callable[[Matcher, Bot, Event, T_State], Awaitable[None]]`
* **说明**
事件响应器运行前预处理函数 RunPreProcessor 类型
## `T_RunPostProcessor`
* **类型**
`Callable[[Matcher, Optional[Exception], Bot, Event, T_State], Awaitable[None]]`
* **说明**
事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在)
## `T_RuleChecker`
* **类型**
`Callable[[Bot, Event, T_State], Union[bool, Awaitable[bool]]]`
* **说明**
RuleChecker 即判断是否响应事件的处理函数。
## `T_PermissionChecker`
* **类型**
`Callable[[Bot, Event], Union[bool, Awaitable[bool]]]`
* **说明**
RuleChecker 即判断是否响应消息的处理函数。
## `T_Handler`
* **类型**
* `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`
* `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]`
* `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`
* `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]`
* **说明**
Handler 即事件的处理函数。
## `T_ArgsParser`
* **类型**
`Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`
* **说明**
ArgsParser 即消息参数解析函数,在 Matcher.got 获取参数时被运行。

View File

@@ -0,0 +1,84 @@
---
contentSidebar: true
sidebarDepth: 0
---
# NoneBot.utils 模块
## `escape_tag(s)`
* **说明**
用于记录带颜色日志时转义 `<tag>` 类型特殊标签
* **参数**
* `s: str`: 需要转义的字符串
* **返回**
* `str`
## `run_sync(func)`
* **说明**
一个用于包装 sync function 为 async function 的装饰器
* **参数**
* `func: Callable[..., Any]`: 被装饰的同步函数
* **返回**
* `Callable[..., Awaitable[Any]]`
## `logger_wrapper`
* **说明**
用于打印 adapter 的日志。
* **Log 参数**
* `level: Literal['WARNING', 'DEBUG', 'INFO']`: 日志等级
* `message: str`: 日志信息
* `exception: Optional[Exception]`: 异常信息
## _class_ `DataclassEncoder`
基类:`json.encoder.JSONEncoder`
* **说明**
在JSON序列化 `Message` (List[Dataclass]) 时使用的 `JSONEncoder`

View File

@@ -0,0 +1,33 @@
# 概览
<!-- :::tip 提示
如果在阅读本文档时遇到难以理解的词汇,请随时查阅 [术语表](../glossary.md) 或使用 [Google 搜索](https://www.google.com/)
::: -->
:::tip 提示
初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。
:::
## 简介
NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。
除了起到解析事件的作用NoneBot 还为插件提供了大量实用的预设操作和权限控制机制。对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。
得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制NoneBot 处理事件的吞吐量有了很大的保障,再配合 WebSocket 通信方式也是最建议的通信方式NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。
需要注意的是NoneBot 仅支持 **Python 3.7+**
## 特色
NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**
- 提供使用简易的脚手架
- 提供丰富的官方插件
- 提供可添加/替换的驱动以及协议选项
- 基于异步 I/O
- 同时支持 HTTP 和反向 WebSocket 通信方式
- 支持多个机器人账号负载均衡
- 提供直观的交互式会话接口
- 提供可自定义的权限控制机制
- 多种方式渲染要发送的消息内容,使对话足够自然

View File

@@ -0,0 +1,83 @@
# 基本配置
到目前为止我们还在使用 NoneBot 的默认行为,在开始编写自己的插件之前,我们先尝试在配置文件上动动手脚,让 NoneBot 表现出不同的行为。
在上一章节中,我们创建了默认的项目结构,其中 `.env`, `.env.*` 均为项目的配置文件,下面将介绍几种 NoneBot 配置方式。
:::danger 警告
请勿将敏感信息写入配置文件并提交至开源仓库!
:::
## .env 文件
NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT` (大小写不敏感),默认值为 `prod`
这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。
现在,我们在 `.env` 文件中写入当前环境信息:
```bash
# .env
ENVIRONMENT=dev
```
如你所想,之后 NoneBot 就会从 `.env.dev` 文件中加载环境变量。
## .env.\* 文件
NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 进行配置管理,会从 `.env.{ENVIRONMENT}` 文件中获悉环境配置。
可以在 NoneBot 初始化时指定加载某个环境配置文件: `nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的环境信息。
:::warning 提示
由于 `pydantic` 使用 JSON 解析配置项,请确保配置项值为 JSON 格式的数据。如:
```bash
list=["123456789", "987654321", 1]
test={"hello": "world"}
```
如果配置项值解析失败将作为字符串处理。
:::
示例及说明:
```bash
HOST=0.0.0.0 # 配置 NoneBot 监听的 IP/主机名
PORT=8080 # 配置 NoneBot 监听的端口
DEBUG=true # 开启 debug 模式 **请勿在生产环境开启**
SUPERUSERS=["123456789", "987654321"] # 配置 NoneBot 超级用户
NICKNAME=["awesome", "bot"] # 配置机器人的昵称
COMMAND_START=["/", ""] # 配置命令起始字符
COMMAND_SEP=["."] # 配置命令分割字符
# Custom Configs
CUSTOM_CONFIG1="config in env file"
CUSTOM_CONFIG2= # 留空则从系统环境变量读取,如不存在则为空字符串
```
详细的配置项参考 [Config Reference](../api/config.md) 。
## 系统环境变量
如果在系统环境变量中定义了配置,则一样会被读取。
## bot.py 文件
配置项也可以在 NoneBot 初始化时传入。此处可以传入任意合法 Python 变量。当然也可以在初始化完成后修改或新增。
示例:
```python
# bot.py
import nonebot
nonebot.init(custom_config3="config on init")
config = nonebot.get_driver().config
config.custom_config3 = "changed after init"
config.custom_config4 = "new config after init"
```
## 优先级
`bot.py init` > `system env` > `env file`

View File

@@ -0,0 +1,101 @@
# CQHTTP 协议使用指南
## 配置 CQHTTP 协议端(以 QQ 为例)
单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。
QQ 协议端举例:
- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo))
- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded)
- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai)
- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api)
- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq))
这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例
1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases)
2. 运行 exe 文件或者使用 `./go-cqhttp` 启动
3. 生成默认配置文件并修改默认配置
```hjson{2,3,35-36,42}
{
uin: 机器人QQ号
password: 机器人密码
encrypt_password: false
password_encrypted: ""
enable_db: true
access_token: ""
relogin: {
enabled: true
relogin_delay: 3
max_relogin_times: 0
}
_rate_limit: {
enabled: false
frequency: 1
bucket_size: 1
}
ignore_invalid_cqcode: false
force_fragmented: false
heartbeat_interval: 0
http_config: {
enabled: false
host: "0.0.0.0"
port: 5700
timeout: 0
post_urls: {}
}
ws_config: {
enabled: false
host: "0.0.0.0"
port: 6700
}
ws_reverse_servers: [
{
enabled: true
reverse_url: ws://127.0.0.1:8080/cqhttp/ws
reverse_api_url: ws://you_websocket_api.server
reverse_event_url: ws://you_websocket_event.server
reverse_reconnect_interval: 3000
}
]
post_message_format: array
use_sso_address: false
debug: false
log_level: ""
web_ui: {
enabled: false
host: 127.0.0.1
web_ui_port: 9999
web_input: false
}
}
```
其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT。
`cqhttp` 是前述 `register_adapter` 时传入的第一个参数,代表设置的 `CQHTTPBot` 适配器的路径,你可以对不同的适配器设置不同路径以作区别。
## 历史性的第一次对话
一旦新的配置文件正确生效之后NoneBot 所在的控制台(如果正在运行的话)应该会输出类似下面的内容(两条访问日志):
```default
09-14 21:31:16 [INFO] uvicorn | ('127.0.0.1', 12345) - "WebSocket /cqhttp/ws" [accepted]
09-14 21:31:16 [INFO] nonebot | WebSocket Connection from CQHTTP Bot 你的QQ号 Accepted!
```
这表示 CQHTTP 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。
现在,尝试向你的机器人账号发送如下内容:
```default
/echo 你好,世界
```
到这里如果一切 OK你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅!
<ClientOnly>
<Messenger :messages="[{ position: 'right', msg: '/echo 你好,世界' }, { position: 'left', msg: '你好,世界' }]"/>
</ClientOnly>

View File

@@ -0,0 +1,197 @@
# 事件处理
在上一章中,我们已经注册了事件响应器,现在我们可以正式编写事件处理逻辑了!
## [事件处理函数](../api/typing.md#handler)
```python{1,2,8,9}
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海则args为上海
if args:
state["city"] = args # 如果用户发送了参数则直接赋值
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: T_State):
city = state["city"]
if city not in ["上海", "北京"]:
await weather.reject("你想查询的城市暂不支持,请重新输入!")
city_weather = await get_weather(city)
await weather.finish(city_weather)
```
在之前的样例中,我们定义了两个函数 `handle_first_receive`, `handle_city`,他们被事件响应器的装饰器装饰从而成为事件响应器的事件处理函数。
:::tip 提示
在事件响应器中,事件处理函数是**顺序**执行的!
:::
### 添加一个事件处理函数
事件响应器提供了三种装饰事件处理函数的装饰器,分别是:
1. [handle()](../api/matcher.md#classmethod-handle)
2. [receive()](../api/matcher.md#classmethod-receive)
3. [got(key, prompt, args_parser)](../api/matcher.md#classmethod-got-key-prompt-none-args-parser-none)
#### handle()
简单的为事件响应器添加一个事件处理函数,这个函数将会在上一个处理函数正常返回执行完毕后立即执行。
#### receive()
指示 NoneBot 接收一条新的用户消息后继续执行该处理函数。此时函数将会接收到新的消息而非前一条消息,之前相关信息可以存储在 state 中。
特别的,当装饰的函数前没有其他事件处理函数,那么 `receive()` 不会接收一条新的消息而是直接使用第一条接收到的消息。
#### got(key, prompt, args_parser)
指示 NoneBot 当 `state` 中不存在 `key` 时向用户发送 `prompt` 等待用户回复并赋值给 `state[key]`。
`prompt` 可以为 `str`, `Message`, `MessageSegment`,若为空则不会向用户发送,若不为空则会在 format 之后发送,即 `prompt.format(**state)`,注意对 `{}` 进行转义。示例:
```python
@matcher.receive()
async def handle(bot: Bot, event: Event, state: T_State):
state["key"] = "hello"
@matcher.got("key2", prompt="{key}!")
async def handle2(bot: Bot, event: Event, state: T_State):
pass
```
`args_parser` 为参数处理函数,在这里传入一个新的函数以覆盖默认的参数处理。详情参照 [args_parser](#参数处理函数-args-parser)
特别的,这些装饰器都可以套娃使用:
```python
@matcher.got("key1")
@matcher.got("key2")
async def handle(bot: Bot, event: Event, state: T_State):
pass
```
### 事件处理函数参数
事件处理函数类型为:
- `Callable[[Bot, Event, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot, Event, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]`
- `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]`
简单说就是:除了 `bot` 参数,其他都是可选的。
以下函数都是合法的事件处理函数(仅列举常用的):
```python
async def handle(bot: Bot, event: Event, state: T_State):
pass
async def handle(bot: Bot, event: Event, state: T_State, matcher: Matcher):
pass
async def handle(bot: Bot, event: Event):
pass
async def handle(bot: Bot, state: T_State):
pass
async def handle(bot: Bot):
pass
```
:::danger 警告
函数的参数名固定不能修改!
:::
参数分别为:
1. [nonebot.adapters.Bot](../api/adapters/#class-bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。
2. [nonebot.adapters.Event](../api/adapters/#class-event): 即上报事件对象,可以获取到上报的所有信息。
3. [state](../api/typing.md#t-state): 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如:
- `state["_current_key"]`: 存储当前 `got` 获取的参数名
- `state["_prefix"]`, `state["_suffix"]`: 存储当前 TRIE 匹配的前缀/后缀,可以通过该值获取用户命令的原始命令
:::tip 提示
NoneBot 会对不同类型的参数进行不同的操作,详情查看 [事件处理函数重载](../advanced/overloaded-handlers.md)
:::
### 参数处理函数 args_parser
在使用 `got` 获取用户输入参数时需要对用户的消息进行处理以转换为我们所需要的信息。在默认情况下NoneBot 会把用户的消息字符串原封不动的赋值给 `state[key]` 。可以通过以下两种方式修改默认处理逻辑:
- `@matcher.args_parser` 装饰器:直接装饰一个函数作为参数处理器
- `got(key, prompt, args_parser)`:直接把函数作为参数传入
参数处理函数类型为:`Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`,即:
```python
async def parser(bot: Bot, event: Event, state: T_State):
state[state["_current_key"]] = str(event.get_message())
```
特别的,`state["_current_key"]` 中存储了当前获取的参数名
### 逻辑控制
NoneBot 也为事件处理函数提供了一些便捷的逻辑控制函数:
#### `matcher.send`
这个函数用于发送一条消息给当前交互的用户。~~其实这并不是一个逻辑控制函数,只是不知道放在哪里……~~
#### `matcher.pause`
这个函数用于结束当前事件处理函数,强制接收一条新的消息再运行**下一个消息处理函数**。
#### `matcher.reject`
这个函数用于结束当前事件处理函数,强制接收一条新的消息再**再次运行当前消息处理函数**。常用于用户输入信息不符合预期。
#### `matcher.finish`
这个函数用于直接结束当前事件处理。
以上三个函数都拥有一个参数 `message` / `prompt`,用于向用户发送一条消息。以及 `**kwargs` 直接传递给 `bot.send` 的额外参数。
## 常用事件处理结构
```python
matcher = on_command("test")
# 修改默认参数处理
@matcher.args_parser
async def parse(bot: Bot, event: Event, state: T_State):
print(state["_current_key"], ":", str(event.get_message()))
state[state["_current_key"]] = str(event.get_message())
@matcher.handle()
async def first_receive(bot: Bot, event: Event, state: T_State):
# 获取用户原始命令,如:/test
print(state["_prefix"]["raw_command"])
# 处理用户输入参数,如:/test arg1 arg2
raw_args = str(event.get_message()).strip()
if raw_args:
arg_list = raw_args.split()
# 将参数存入state以阻止后续再向用户询问参数
state["arg1"] = arg_list[0]
@matcher.got("arg1", prompt="参数?")
async def arg_handle(bot: Bot, event: Event, state: T_State):
# 在这里对参数进行验证
if state["arg1"] not in ["allow", "list"]:
await matcher.reject("参数不正确!请重新输入")
# 发送一些信息
await bot.send(event, "message")
await matcher.send("message")
await matcher.finish("message")
```

View File

@@ -0,0 +1,146 @@
# 注册事件响应器
好了,现在插件已经创建完毕,我们可以开始编写实际代码了,下面将以一个简易单文件天气查询插件为例。
在插件目录下 `weather.py` 中添加如下代码:
```python
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
weather = on_command("天气", rule=to_me(), priority=5)
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海则args为上海
if args:
state["city"] = args # 如果用户发送了参数则直接赋值
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: T_State):
city = state["city"]
if city not in ["上海", "北京"]:
await weather.reject("你想查询的城市暂不支持,请重新输入!")
city_weather = await get_weather(city)
await weather.finish(city_weather)
async def get_weather(city: str):
return f"{city}的天气是..."
```
为了简单起见,我们在这里的例子中没有接入真实的天气数据,但要接入也非常简单,你可以使用中国天气网、和风天气等网站提供的 API。
接下来我们来说明这段代码是如何工作的。
:::tip 提示
从这里开始,你需要对 Python 的 asyncio 编程有所了解,因为 NoneBot 是完全基于 asyncio 的,具体可以参考 [廖雪峰的 Python 教程](https://www.liaoxuefeng.com/wiki/1016959663602400/1017959540289152)
:::
## [事件响应器](../api/matcher.md)
```python{5}
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.permission import Permission
weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5)
```
在上方代码中,我们注册了一个事件响应器 `Matcher`,它由几个部分组成:
1. `on_command` 注册一个消息类型的命令处理器
2. `"天气"` 指定 command 参数 - 命令名
3. `rule` 补充事件响应器的匹配规则
4. `priority` 事件响应器优先级
5. `block` 是否阻止事件传递
其他详细配置可以参考 API 文档,下面我们详细说明各个部分:
### 事件响应器类型 type
事件响应器类型其实就是对应事件的类型 `Event.get_type()` NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。
以下所有类型的事件响应器都是由 `on(type, rule)` 的形式进行了简化封装。
- `on("事件类型")`: 基础事件响应器,第一个参数为事件类型,空字符串表示不限
- `on_metaevent()` ~ `on("meta_event")`: 元事件响应器
- `on_message()` ~ `on("message")`: 消息事件响应器
- `on_request()` ~ `on("request")`: 请求事件响应器
- `on_notice()` ~ `on("notice")`: 通知事件响应器
- `on_startswith(str)` ~ `on("message", startswith(str))`: 消息开头匹配响应器,参考 [startswith](../api/rule.md#startswith-msg)
- `on_endswith(str)` ~ `on("message", endswith(str))`: 消息结尾匹配响应器,参考 [endswith](../api/rule.md#endswith-msg)
- `on_keyword(set)` ~ `on("message", keyword(str))`: 消息关键词匹配响应器,参考 [keyword](../api/rule.md#keyword-keywords)
- `on_command(str|tuple)` ~ `on("message", command(str|tuple))`: 命令响应器,参考 [command](../api/rule.md#command-cmds)
- `on_regex(pattern_str)` ~ `on("message", regex(pattern_str))`: 正则匹配处理器,参考 [regex](../api/rule.md#regex-regex-flags-0)
### 匹配规则 rule
事件响应器的匹配规则即 `Rule`,详细内容在下方介绍。[直达](#自定义-rule)
### 优先级 priority
事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!**,优先级数字**越小**越先响应!优先级请从 `1` 开始排序!
:::tip 提示
使用 `nonebot-plugin-test` 可以在网页端查看当前所有事件响应器的执行流程,有助理解事件响应流程!
```bash
nb plugin install nonebot_plugin_test
```
:::
### 阻断 block
当有任意事件响应器发出了阻止事件传递信号时,该事件将不再会传递给下一优先级,直接结束处理。
NoneBot 内置的事件响应器中,所有 `message` 类的事件响应器默认会阻断事件传递,其他则不会。
## 自定义 rule
rule 的出现使得 nonebot 对事件的响应可以非常自由nonebot 内置了一些规则:
- [startswith(msg)](../api/rule.md#startswith-msg)
- [endswith(msg)](../api/rule.md#endswith-msg)
- [keyword(\*keywords)](../api/rule.md#keyword-keywords)
- [command(\*cmds)](../api/rule.md#command-cmds)
- [regex(regex, flag)](../api/rule.md#regex-regex-flags-0)
以上规则都是返回类型为 `Rule` 的函数,`Rule` 由非负个 `RuleChecker` 组成,当所有 `RuleChecker` 返回 `True` 时匹配成功。这些 `Rule`, `RuleChecker` 的形式如下:
```python
from nonebot.rule import Rule
from nonebot.typing import T_State
async def async_checker(bot: Bot, event: Event, state: T_State) -> bool:
return True
def sync_checker(bot: Bot, event: Event, state: T_State) -> bool:
return True
def check(arg1, args2):
async def _checker(bot: Bot, event: Event, state: T_State) -> bool:
return bool(arg1 + arg2)
return Rule(_checker)
```
`Rule` 和 `RuleChecker` 之间可以使用 `&` 互相组合:
```python
from nonebot.rule import Rule
Rule(async_checker1) & sync_checker & async_checker2
```
**_请勿将事件处理的逻辑写入 `rule` 中这会使得事件处理返回奇怪的响应。_**
:::danger 警告
`Rule(*checkers)` 只接受 async function或使用 `nonebot.utils.run_sync` 自行包裹 sync function。在使用 `&` 时NoneBot 会自动包裹 sync function
:::

View File

@@ -0,0 +1,119 @@
# 创建插件
如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了!
使用 `nb-cli` 创建包形式插件,或自行创建文件(夹)
```bash
nb plugin new
```
插件通常有两种形式,下面分别介绍
## 单文件形式
在插件目录下创建名为 `foo.py` 的 Python 文件,暂时留空,此时目录结构如下:
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── awesome_bot
│ └── plugins
│ └── `foo.py`
├── .env
├── .env.dev
├── .env.prod
├── .gitignore
├── bot.py
├── docker-compose.yml
├── Dockerfile
├── pyproject.toml
└── README.md
:::
<!-- prettier-ignore-end -->
这个时候它已经可以被称为一个插件了,尽管它还什么都没做。
## 包形式(推荐)
在插件目录下创建文件夹 `foo`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下:
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── awesome_bot
│ └── plugins
│ └── `foo`
│ └── `__init__.py`
├── .env
├── .env.dev
├── .env.prod
├── .gitignore
├── bot.py
├── docker-compose.yml
├── Dockerfile
├── pyproject.toml
└── README.md
:::
<!-- prettier-ignore-end -->
这个时候 `foo` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。
### 推荐结构(仅供参考)
<!-- prettier-ignore-start -->
:::vue
foo
├── `__init__.py`
├── `config.py`
├── `data_source.py`
└── `model.py`
:::
<!-- prettier-ignore-end -->
#### \_\_init\_\_.py
在该文件中编写各类事件响应及处理逻辑。
#### config.py
在该文件中使用 `pydantic` 定义插件所需要的配置项以及类型。
示例:
```python
from pydantic import BaseSettings
class Config(BaseSettings):
# plugin custom config
plugin_setting: str = "default"
class Config:
extra = "ignore"
```
并在 `__init__.py` 文件中添加以下行
```python
import nonebot
from .config import Config
global_config = nonebot.get_driver().config
plugin_config = Config(**global_config.dict())
```
此时就可以通过 `plugin_config.plugin_setting` 获取到插件所需要的配置项了。
#### data_source.py
在该文件中编写数据获取函数。
:::warning 警告
数据获取应尽量使用**异步**处理!例如使用 [httpx](https://www.python-httpx.org/) 而非 [requests](https://requests.readthedocs.io/en/master/)
:::
#### model.py
在该文件中编写数据库模型。

View File

@@ -0,0 +1,51 @@
# 创建一个完整的项目
上一章中我们已经运行了一个简单的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。
## 目录结构
可以使用 `nb-cli` 或者自行创建完整的项目目录:
```bash
nb create
```
<!-- prettier-ignore-start -->
:::vue
AweSome-Bot
├── `awesome_bot` _(**或是 src**)_
│ └── `plugins`
├── `.env` _(**可选的**)_
├── `.env.dev` _(**可选的**)_
├── `.env.prod` _(**可选的**)_
├── .gitignore
├── `bot.py`
├── docker-compose.yml
├── Dockerfile
├── `pyproject.toml`
└── README.md
:::
<!-- prettier-ignore-end -->
- `awesome_bot/plugins``src/plugins`: 用于存放编写的 bot 插件
- `.env`, `.env.dev`, `.env.prod`: 各环境配置文件
- `bot.py`: bot 入口文件
- `pyproject.toml`: 项目依赖管理文件,默认使用 [poetry](https://python-poetry.org/)
## 启动 Bot
如果你使用 `nb-cli`
```bash
nb run [--file=bot.py] [--app=app]
```
或者使用
```bash
python bot.py
```
:::tip 提示
如果在 bot 入口文件内定义了 asgi server `nb-cli` 将会为你启动**冷重载模式**
:::

View File

@@ -0,0 +1,3 @@
# 钉钉机器人使用指南
~~TODO~~

View File

@@ -0,0 +1,9 @@
# 结语
至此,相信你已经能够写出一个基础的插件了。这里给出几个小提示:
- 请千万注意事件处理器的优先级设定
- 在匹配规则中请勿使用耗时极长的函数
- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍)
如果「指南」还不能满足你,前往 [进阶](../advanced/README.md) 查看更多的功能信息。

View File

@@ -0,0 +1,86 @@
# 开始使用
一切都安装成功后,你就已经做好了进行简单配置以运行一个最小的 NoneBot 实例的准备。
## 最小实例
如果你已经按照推荐方式安装了 `nb-cli`,使用脚手架创建一个空项目:
```bash
nb create
```
根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`
如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE创建一个名为 `bot.py` 的文件,内容如下(这里以 CQHTTP 为例):
```python{4,6,7,10}
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter("cqhttp", CQHTTPBot)
nonebot.load_builtin_plugins()
if __name__ == "__main__":
nonebot.run()
```
## 解读
在上方 `bot.py` 中,这几行高亮代码将依次:
1. 使用默认配置初始化 NoneBot
2. 加载 NoneBot 内置的 CQHTTP 协议适配组件
`register_adapter` 的第一个参数我们传入了一个字符串,该字符串将会在后文 [配置 CQHTTP 协议端](#配置-cqhttp-协议端-以-qq-为例) 时使用。
3. 加载 NoneBot 内置的插件
4. 在地址 `127.0.0.1:8080` 运行 NoneBot
在命令行使用如下命令即可运行这个 NoneBot 实例:
```bash
# nb-cli
nb run
# 其他
python bot.py
```
运行后会产生如下日志:
```plain
09-14 21:02:00 [INFO] nonebot | Succeeded to import "nonebot.plugins.base"
09-14 21:02:00 [INFO] nonebot | Running NoneBot...
09-14 21:02:00 [INFO] uvicorn | Started server process [1234]
09-14 21:02:00 [INFO] uvicorn | Waiting for application startup.
09-14 21:02:00 [INFO] uvicorn | Application startup complete.
09-14 21:02:00 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)
```
## 配置协议端上报
在 `bot.py` 文件中使用 `register_adapter` 注册协议适配之后即可配置协议端来完成与 NoneBot 的通信,详细配置方法参考:
- [配置 CQHTTP](./cqhttp-guide.md)
- [配置钉钉](./ding-guide.md)
NoneBot 接受的上报地址与 `Driver` 有关,默认使用的 `FastAPI Driver` 所接受的上报地址有:
- `/{adapter name}/`: HTTP POST 上报
- `/{adapter name}/http/`: HTTP POST 上报
- `/{adapter name}/ws`: WebSocket 上报
- `/{adapter name}/ws/`: WebSocket 上报
:::warning 注意
如果到这一步你没有在 NoneBot 看到连接成功日志,比较常见的出错点包括:
- NoneBot 监听 `0.0.0.0`,然后在协议端上报配置中填了 `ws://0.0.0.0:8080/***/ws`
- 在 Docker 容器内运行协议端,并通过 `127.0.0.1` 访问宿主机上的 NoneBot
- 想从公网访问,但没有修改云服务商的安全组策略或系统防火墙
- NoneBot 所监听的端口存在冲突,已被其它程序占用
- 弄混了 NoneBot 的 `host`、`port` 参数与协议端上报配置中的 `host`、`port` 参数
- `ws://` 错填为 `http://`
- 协议端或 NoneBot 启动时遭到外星武器干扰
请尝试重启协议端 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新协议端 和 NoneBot 到最新版本等方式来解决。
:::

View File

@@ -0,0 +1,91 @@
# 安装
## NoneBot
:::warning 注意
请确保你的 Python 版本 >= 3.7。
:::
:::warning 注意
请在安装 nonebot2 之前卸载 nonebot 1.x
```bash
pip uninstall nonebot
```
:::
### 通过脚手架安装(推荐安装方式)
1. (推荐)使用你喜欢的 Python 环境管理工具(如 `poetry`)创建新的虚拟环境。
2. 使用 `pip` (或其他包管理工具) 安装 nb-clinonebot2 作为其依赖会一起被安装。
```bash
pip install nb-cli
```
3. 点个 star 吧
nonebot2: [![nb-cli](https://img.shields.io/github/stars/nonebot/nonebot2?style=social)](https://github.com/nonebot/nonebot2)
nb-cli: [![nb-cli](https://img.shields.io/github/stars/nonebot/nb-cli?style=social)](https://github.com/nonebot/nb-cli)
### 不使用脚手架(纯净安装)
```bash
pip install nonebot2
# 也可以通过 poetry 安装
poetry add nonebot2
```
如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装:
:::warning 注意
直接从 Github 仓库中安装意味着你将使用最新提交的代码,它们并没有进行充分的稳定性测试
在任何情况下请不要将其应用于生产环境!
:::
```bash
# master分支
poetry add git+https://github.com/nonebot/nonebot2.git#master
# dev分支
poetry add git+https://github.com/nonebot/nonebot2.git#dev
```
或者在克隆 Git 仓库后手动安装:
```bash
git clone https://github.com/nonebot/nonebot2.git
cd nonebot2
poetry install --no-dev # 推荐
pip install . # 不推荐
```
## 安装插件
插件可以通过 `nb-cli` 进行安装,也可以自行安装并加载插件。
```bash
# 列出所有的插件
nb plugin list
# 搜索插件
nb plugin search xxx
# 安装插件
nb plugin install xxx
```
如果急于上线 Bot 或想要使用现成的插件,以下插件可作为参考:
### 官方插件
~~自用插件~~ ~~确信~~
- [NoneBot-Plugin-Docs](https://github.com/nonebot/nonebot2/tree/master/packages/nonebot-plugin-docs) 离线文档插件
- [NoneBot-Plugin-Test](https://github.com/nonebot/plugin-test) 本地机器人测试前端插件
- [NoneBot-Plugin-APScheduler](https://github.com/nonebot/plugin-apscheduler) 定时任务插件
- [NoneBot-Plugin-Sentry](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_sentry) Sentry 在线日志分析插件
- [NoneBot-Plugin-Status](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_status) 服务器状态查看插件
### 其他插件
还有更多的插件在 [这里](/plugin-store.md) 等着你发现~

View File

@@ -0,0 +1,116 @@
# 加载插件
在 [创建一个完整的项目](creating-a-project) 一章节中,我们已经创建了插件目录 `awesome_bot/plugins`,现在我们在机器人入口文件中加载它。当然,你也可以单独加载一个插件。
## 加载内置插件
`bot.py` 文件中添加以下行:
```python{5}
import nonebot
nonebot.init()
# 加载 nonebot 内置插件
nonebot.load_builtin_plugins()
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
这将会加载 nonebot 内置的插件,它包含:
- 命令 `say`:可由**superuser**使用,可以将消息内容由特殊纯文本转为富文本
- 命令 `echo`:可由任何人使用,将消息原样返回
以上命令均需要指定机器人,即私聊、群聊内@机器人、群聊内称呼机器人昵称。参考 [Rule: to_me](../api/rule.md#to-me)
## 加载插件目录
在 `bot.py` 文件中添加以下行:
```python{5}
import nonebot
nonebot.init()
# 加载插件目录,该目录下为各插件,以下划线开头的插件将不会被加载
nonebot.load_plugins("awesome_bot/plugins")
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
:::tip 提示
加载插件目录时,目录下以 `_` 下划线开头的插件将不会被加载!
:::
:::warning 提示
**不能存在相同名称的插件!**
:::
:::danger 警告
插件间不应该存在过多的耦合,如果确实需要导入某个插件内的数据,可以参考 [进阶-跨插件访问](../advanced/export-and-require.md)
:::
## 加载单个插件
在 `bot.py` 文件中添加以下行:
```python{5,7}
import nonebot
nonebot.init()
# 加载一个 pip 安装的插件
nonebot.load_plugin("nonebot_plugin_status")
# 加载本地的单独插件
nonebot.load_plugin("awesome_bot.plugins.xxx")
app = nonebot.get_asgi()
if __name__ == "__main__":
nonebot.run()
```
## 子插件(嵌套插件)
在插件中同样可以加载子插件,例如如下插件目录结构:
<!-- prettier-ignore-start -->
:::vue
foo_plugin
├── `plugins`
│ ├── `sub_plugin1`
│ │ └── \_\_init\_\_.py
│ └── `sub_plugin2.py`
├── `__init__.py`
└── config.py
:::
<!-- prettier-ignore-end -->
在插件目录下的 `__init__.py` 中添加如下代码:
```python
from pathlib import Path
import nonebot
# store all subplugins
_sub_plugins = set()
# load sub plugins
_sub_plugins |= nonebot.load_plugins(
str((Path(__file__).parent / "plugins").resolve()))
```
插件将会被加载并存储于 `_sub_plugins` 中。
## 运行结果
尝试运行 `nb run` 或者 `python bot.py`,可以看到日志输出了类似如下内容:
```plain
09-19 21:51:59 [INFO] nonebot | Succeeded to import "nonebot.plugins.base"
09-19 21:51:59 [INFO] nonebot | Succeeded to import "plugin_in_folder"
```

View File

@@ -0,0 +1,171 @@
{
"sidebar": {},
"locales": {
"/": {
"label": "简体中文",
"selectText": "Languages",
"editLinkText": "在 GitHub 上编辑此页",
"lastUpdated": "上次更新",
"nav": [
{
"text": "主页",
"link": "/"
},
{
"text": "指南",
"link": "/guide/"
},
{
"text": "进阶",
"link": "/advanced/"
},
{
"text": "API",
"link": "/api/"
},
{
"text": "插件广场",
"link": "/plugin-store"
},
{
"text": "更新日志",
"link": "/changelog"
}
],
"sidebarDepth": 2,
"sidebar": {
"/guide/": [
{
"title": "开始",
"collapsable": false,
"sidebar": "auto",
"children": [
"",
"installation",
"getting-started",
"creating-a-project",
"basic-configuration"
]
},
{
"title": "编写插件",
"collapsable": false,
"sidebar": "auto",
"children": [
"loading-a-plugin",
"creating-a-plugin",
"creating-a-matcher",
"creating-a-handler",
"end-or-start"
]
},
{
"title": "协议适配",
"collapsable": false,
"sidebar": "auto",
"children": [
"cqhttp-guide",
"ding-guide"
]
}
],
"/advanced/": [
{
"title": "进阶",
"collapsable": false,
"sidebar": "auto",
"children": [
"",
"scheduler",
"permission",
"runtime-hook",
"export-and-require",
"overloaded-handlers"
]
},
{
"title": "发布",
"collapsable": false,
"sidebar": "auto",
"children": [
"publish-plugin"
]
}
],
"/api/": [
{
"title": "NoneBot Api Reference",
"path": "",
"collapsable": false,
"children": [
{
"title": "nonebot 模块",
"path": "nonebot"
},
{
"title": "nonebot.config 模块",
"path": "config"
},
{
"title": "nonebot.plugin 模块",
"path": "plugin"
},
{
"title": "nonebot.message 模块",
"path": "message"
},
{
"title": "nonebot.matcher 模块",
"path": "matcher"
},
{
"title": "nonebot.rule 模块",
"path": "rule"
},
{
"title": "nonebot.permission 模块",
"path": "permission"
},
{
"title": "nonebot.log 模块",
"path": "log"
},
{
"title": "nonebot.utils 模块",
"path": "utils"
},
{
"title": "nonebot.typing 模块",
"path": "typing"
},
{
"title": "nonebot.exception 模块",
"path": "exception"
},
{
"title": "nonebot.drivers 模块",
"path": "drivers/"
},
{
"title": "nonebot.drivers.fastapi 模块",
"path": "drivers/fastapi"
},
{
"title": "nonebot.adapters 模块",
"path": "adapters/"
},
{
"title": "nonebot.adapters.cqhttp 模块",
"path": "adapters/cqhttp"
},
{
"title": "nonebot.adapters.ding 模块",
"path": "adapters/ding"
}
]
}
]
}
}
}
}

View File

@@ -0,0 +1,15 @@
---
home: true
heroImage: /logo.png
tagline: 跨平台 Python 异步 QQ 机器人框架
actionText: 开始使用
actionLink: guide/
features:
- title: 简洁
details: 提供极其简洁易懂的 API使你可以毫无压力地开始验证你的绝佳创意只需编写最少量的代码即可实现丰富的功能。
- title: 易于扩展
details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。
- title: 高性能
details: 采用异步 I/O利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。
footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team
---

View File

@@ -0,0 +1,7 @@
# 深入
## 它如何工作?
<!-- TODO: how to work -->
~~未填坑~~

View File

@@ -0,0 +1 @@
# 跨插件访问

View File

@@ -0,0 +1 @@
# 事件处理函数重载

View File

@@ -0,0 +1 @@
# 权限控制

View File

@@ -0,0 +1 @@
# 发布插件

View File

@@ -0,0 +1 @@
# 钩子函数

View File

@@ -0,0 +1,135 @@
# 定时任务
[`APScheduler`](https://apscheduler.readthedocs.io/en/latest/index.html) —— Advanced Python Scheduler
> Advanced Python Scheduler (APScheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. You can add new jobs or remove old ones on the fly as you please. If you store your jobs in a database, they will also survive scheduler restarts and maintain their state. When the scheduler is restarted, it will then run all the jobs it should have run while it was offline.
## 从 NoneBot v1 迁移
`APScheduler` 作为 `nonebot` v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。`nonebot2` 已将 `APScheduler` 独立为 `nonebot_plugin_apscheduler` 插件,你可以在 [插件广场](https://v2.nonebot.dev/plugin-store.html) 中找到它。
相比于 `nonebot` v1 ,只需要安装插件并修改 `scheduler` 的导入方式即可完成迁移。
## 安装插件
### 通过 nb-cli
如正在使用 `nb-cli` 构建项目,你可以从插件市场复制安装命令或手动输入以下命令以添加 `nonebot_plugin_apscheduler`
```bash
nb plugin install nonebot_plugin_apscheduler
```
:::tip 提示
`nb-cli` 默认通过 `pypi` 安装,你可以添加命令参数 `-i [mirror]``--index [mirror]` 以使用镜像源安装。
:::
### 通过 poetry
执行以下命令以添加 `nonebot_plugin_apscheduler`
```bash
poetry add nonebot-plugin-apscheduler
```
:::tip 提示
由于稍后我们将使用 `nonebot.require()` 方法进行导入,所以无需额外的 `nonebot.load_plugin()`
:::
## 快速上手
1. 在需要设置定时任务的插件中,通过 `nonebot.require``nonebot_plugin_apscheduler` 导入 `scheduler` 对象
2. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务
将上述步骤归纳为最小实现的代码如下:
```python
from nonebot import require
scheduler = require('nonebot_plugin_apscheduler').scheduler
@scheduler.scheduled_job('cron', hour='*/2', id='xxx', args=[1], kwargs={arg2: 2})
async def run_every_2_hour(arg1, arg2):
pass
scheduler.add_job(run_every_day_from_program_start, "interval", days=1, id="xxx")
```
## 分步进行
### 导入 scheduler 对象
为了使插件能够实现定时任务,需要先将 `scheduler` 对象导入插件。
`nonebot2` 提供了 `nonebot.require` 方法来实现导入其他插件的内容,此处我们使用这个方法来导入 `scheduler` 对象。
`nonebot` 使用的 `scheduler` 对象为 `AsyncScheduler`
> 使用该方法传入的插件本身也需要有对应实现,关于该方法的更多介绍可以参阅 [这里](./export-and-require.md)
```python
from nonebot import require
scheduler = require('nonebot_plugin_apscheduler').scheduler
```
### 编写定时任务
由于本部分为标准的通过 `APScheduler` 配置定时任务,有关指南请参阅 [APScheduler 官方文档](https://apscheduler.readthedocs.io/en/latest/userguide.html#adding-jobs)。
### 配置插件选项
根据项目的 `.env` 文件设置,向 `.env.*``bot.py` 文件添加 `nonebot_plugin_apscheduler` 的可选配置项
:::warning 注意
`.env.*` 文件的编写应遵循 nonebot2 对 `.env.*` 文件的编写要求
:::
#### `apscheduler_autostart`
类型:`bool`
默认值:`True`
是否自动启动 `APScheduler`
对于大多数情况,我们需要在 `nonebot2` 项目被启动时启动定时任务,则此处设为 `true`
##### 在 `.env` 中添加
```bash
APSCHEDULER_AUTOSTART=true
```
##### 在 `bot.py` 中添加
```python
nonebot.init(apscheduler_autostart=True)
```
#### `apscheduler_config`
类型:`dict`
默认值:`{"apscheduler.timezone": "Asia/Shanghai"}`
`APScheduler` 相关配置。修改/增加其中配置项需要确保 `prefix: apscheduler`
对于 `APScheduler` 的相关配置,请参阅 [scheduler-config](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-config) 和 [BaseScheduler](https://apscheduler.readthedocs.io/en/latest/modules/schedulers/base.html#apscheduler.schedulers.base.BaseScheduler)
> 官方文档在绝大多数时候能提供最准确和最具时效性的指南
##### 在 `.env` 中添加
```bash
APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"}
```
##### 在 `bot.py` 中添加
```python
nonebot.init(apscheduler_config={
"apscheduler.timezone": "Asia/Shanghai"
})
```

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