默认与最小示例插件
默认与最小示例插件
创建插件
$ nb plugin create
[?] 插件名称: my_study_plugin
[?] 使用嵌套插件? (y/N) N
[?] 输出目录: awesome_bot/plugins
默认插件解析
src | |
plugin/ | 插件存放的位置,你可以自己设置在不同的位置 |
my_plugin/ | 插件名 |
| 缓存,不用管 |
| 必须,在python中这表示这是一个模块文件夹,在插件系统中表示这是一个插件文件夹 |
config.py | 配置 |
部分文件的默认内容:
__init__.py
from nonebot import get_plugin_config
from nonebot.plugin import PluginMetadata
from .config import Config
__plugin_meta__ = PluginMetadata( # 一些注册信息
name="my_study_plugin", # 插件名
description="", # 插件描述
usage="", # 插件用例
config=Config,
)
config = get_plugin_config(Config)
config.py
from pydantic import BaseModel
class Config(BaseModel):
"""Plugin Config Here"""
## 默认最小插件
根据指南中的 事件响应器+处理消息 两篇文档,就可以构建出一个最小可用的插件:
```python
from nonebot import get_plugin_config # 配置获取
from nonebot.plugin import PluginMetadata # 插件 - 配置元信息
from .config import Config
__plugin_meta__ = PluginMetadata( # 一些注册信息
name="my_study_plugin", # 插件名
description="", # 插件描述
usage="", # 插件用例
config=Config,
)
config = get_plugin_config(Config)
# 上面的默认的东西
from nonebot import on_command # 信息响应器
from nonebot.rule import to_me # 规则 - 艾特自己
from nonebot.adapters import Message # 适配器 - 信息
from nonebot.params import CommandArg # 参数 - 依赖注入
# 信息响应器
weather = on_command(
"天气", # id、响应名
aliases={"weather", "查天气"}, # 其他响应名
rule=to_me(), # 需要私聊或艾特
priority=10, # 优先级10 (越小越优先)
block=True # 向后阻断传播
)
# 事件处理函数 (装饰器)
@weather.handle()
async def handle_function(args: Message = CommandArg()): # args消息命令后跟随的内容
# 事件响应器
# await weather.send("天气是...")
await weather.finish("天气是...")
ALC最小插件
天气+询问用户,旧版 (非ALC版):
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.matcher import Matcher
from nonebot.adapters import Message
from nonebot.params import CommandArg, ArgPlainText
weather = on_command("天气", rule=to_me(), aliases={"weather", "天气预报"})
@weather.handle()
async def handle_function(matcher: Matcher, args: Message = CommandArg()):
if args.extract_plain_text():
matcher.set_arg("location", args)
@weather.got("location", prompt="请输入地名")
async def got_location(location: str = ArgPlainText()):
if location not in ["北京", "上海", "广州", "深圳"]:
await weather.reject(f"你想查询的城市 {location} 暂不支持,请重新输入!")
await weather.finish(f"今天{location}的天气是...")
天气+询问用户,新版 (ALC版):
from nonebot.rule import to_me
from arclet.alconna import Alconna, Args
from nonebot_plugin_alconna import Match, on_alconna
weather = on_alconna( # [!code]
Alconna("/天气", Args["location?", str]),
aliases={"/weather", "/天气预报"},
# rule=to_me(),
)
@weather.handle()
async def handle_function(location: Match[str]):
if location.available:
weather.set_path_arg("location", location.result)
@weather.got_path("location", prompt="请输入地名")
async def got_location(location: str):
if location not in ["北京", "上海", "广州", "深圳"]:
await weather.reject(f"你想查询的城市 {location} 暂不支持,请重新输入!")
await weather.finish(f"今天{location}的天气是...")
链接到当前文件 0
没有文件链接到当前文件