Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
NoneBot
https://nonebot.dev/docs/
Admin
NoneBot 是一个现代、跨平台、可扩展的 Python 聊天机器人框架,它基于 Python 的类型注解和异步优先特性,提供便捷灵活的支持,并拥有丰富的插件生态。
Tokens:
42,564
Snippets:
484
Trust Score:
7.9
Update:
3 months ago
Context
Chat
Benchmark
49.2
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### 配置 Command Start 和 Command Separator Source: https://nonebot.dev/docs/appendices/config 设置命令消息的起始符和分隔符。 ```text COMMAND_START=["/", ""] COMMAND_SEP=[".", " "] ``` ```bash # windows cmd set COMMAND_START '["/", ""]' set COMMAND_SEP '[".", " "]' # windows powershell $Env:COMMAND_START='["/", ""]' $Env:COMMAND_SEP='[".", " "]' # linux/macOS export COMMAND_START='["/", ""]' export COMMAND_SEP='[".", " "]' ``` ```python import nonebot nonebot.init(command_start={"/", ""}, command_sep={".", " "}) ``` -------------------------------- ### Initialize and Update Configuration Source: https://nonebot.dev/docs/appendices/config Configure settings during the initial setup or update them dynamically after the driver is initialized. ```python import nonebot # 初始化时 nonebot.init(custom_config1="config on init") # 初始化后 config = nonebot.get_driver().config config.custom_config1 = "changed after init" config.custom_config2 = "new config after init" ``` -------------------------------- ### run(*args, **kwargs) Source: https://nonebot.dev/docs/api Starts NoneBot by running the global Driver object. ```APIDOC ## run(*args, **kwargs) ### Description Starts the NoneBot instance. ### Parameters - ***args** (Any): Positional arguments for Driver.run. - ****kwargs** (Any): Keyword arguments for Driver.run. ``` -------------------------------- ### Define scoped environment variables Source: https://nonebot.dev/docs/appendices/config Example of environment variable formatting when using nested configuration scopes. ```text WEATHER__API_KEY=123456 WEATHER__COMMAND_PRIORITY=10 ``` -------------------------------- ### Run NoneBot Source: https://nonebot.dev/docs/api Starts the NoneBot instance by running the global Driver object. ```python nonebot.run(host="127.0.0.1", port=8080) ``` -------------------------------- ### Get All Registered Adapters Source: https://nonebot.dev/docs/api Retrieves a dictionary of all currently registered Adapter instances. ```python adapters = nonebot.get_adapters() ``` -------------------------------- ### Parse Dotenv Configuration Source: https://nonebot.dev/docs/appendices/config Examples of how various data types in a dotenv file are parsed into Python objects. ```text STRING_CONFIG=some string LIST_CONFIG=[1, 2, 3] DICT_CONFIG={"key": "value"} MULTILINE_CONFIG=' [ { "item_key": "item_value" } ] ' EMPTY_CONFIG= NULL_CONFIG ``` ```python dotenv_config = { "string_config": "some string", "list_config": [1, 2, 3], "dict_config": {"key": "value"}, "multiline_config": [{"item_key": "item_value"}], "empty_config": "", "null_config": None } ``` -------------------------------- ### Get Server App Object Source: https://nonebot.dev/docs/api Retrieves the global ASGIMixin server application object. ```python app = nonebot.get_app() ``` -------------------------------- ### 消息序列的 get 方法 Source: https://nonebot.dev/docs/tutorial/message 使用 get 方法获取指定类型和数量的消息段。 ```python # 获取指定类型指定个数的消息段 message.get("markdown", 1) == Message([MessageSegment.markdown("test2")]) ``` -------------------------------- ### 本地构建与发布到 PyPI Source: https://nonebot.dev/docs/developer/plugin-publishing 使用 Poetry、PDM 或 Setuptools 进行本地构建与发布。 ```bash poetry publish --build # 构建并发布 # 等效于以下两个命令 poetry build # 只构建 poetry publish # 只发布先前的构建 ``` ```bash pdm publish # 构建并发布 # 等效于以下两个命令 pdm build # 只构建 pdm publish --no-build # 只发布先前的构建 ``` ```bash pip install build twine # 安装通用构建与发布工具 python -m build --sdist --wheel . # 只构建 twine upload dist/* # 只发布先前的构建 ``` -------------------------------- ### init(*, _env_file=None, **kwargs) Source: https://nonebot.dev/docs/api Initializes NoneBot and the global Driver object using environment configurations. ```APIDOC ## init(*, _env_file=None, **kwargs) ### Description Initializes NoneBot and the global Driver object. ### Parameters - **_env_file** (DOTENV_TYPE | None): Optional configuration file path. - ****kwargs** (Any): Arbitrary variables stored in Driver.config. ``` -------------------------------- ### Get ASGI Object Source: https://nonebot.dev/docs/api Retrieves the global ASGIMixin ASGI object. ```python asgi = nonebot.get_asgi() ``` -------------------------------- ### Retrieve ArgPromptResult Source: https://nonebot.dev/docs/advanced/dependency Get the result of a prompt message sent during a got operation. ```python from typing import Any, Annotated from nonebot.params import ArgPromptResult @matcher.got("key", prompt="prompt") async def _(result: Annotated[Any, ArgPromptResult()]): ... async def _(result: Annotated[Any, ArgPromptResult("key")]): ... ``` ```python from typing import Any from nonebot.params import ArgPromptResult @matcher.got("key", prompt="prompt") async def _(result: Any = ArgPromptResult()): ... async def _(result: Any = ArgPromptResult("key")): ... ``` -------------------------------- ### CommandStart Source: https://nonebot.dev/docs/advanced/dependency Retrieves the command prefix. ```APIDOC ## CommandStart ### Description Retrieves the command prefix. Note: Only available when triggered by a command-type event responder. ### Usage ```python from typing import Annotated from nonebot.params import CommandStart # Using Annotated async def _(foo: Annotated[str, CommandStart()]): ... # Using default value async def _(foo: str = CommandStart()): ... ``` ``` -------------------------------- ### Retrieve ReceivePromptResult Source: https://nonebot.dev/docs/advanced/dependency Get the result of a prompt message sent during a receive operation. ```python from typing import Any, Annotated from nonebot.params import ReceivePromptResult @matcher.receive("id", prompt="prompt") async def _(result: Annotated[Any, ReceivePromptResult("id")]): ... ``` ```python from typing import Any from nonebot.params import ReceivePromptResult @matcher.receive("id", prompt="prompt") async def _(result: Any = ReceivePromptResult("id")): ... ``` -------------------------------- ### 在现有插件中加载子插件 Source: https://nonebot.dev/docs/advanced/plugin-nesting 在插件的 __init__.py 文件中使用 nonebot.load_plugins 加载指定目录下的子插件。 ```python import nonebot from pathlib import Path sub_plugins = nonebot.load_plugins( str(Path(__file__).parent.joinpath("plugins").resolve()) ) ``` -------------------------------- ### 获取 ASGI 应用实例 Source: https://nonebot.dev/docs/advanced/routing 使用 get_app 或 get_asgi 获取底层驱动框架应用。 ```python import nonebot app = nonebot.get_app() asgi = nonebot.get_asgi() ``` -------------------------------- ### 使用 load_all_plugins 加载 Source: https://nonebot.dev/docs/tutorial/create-plugin 混合加载插件模块和插件目录。 ```python nonebot.load_all_plugins(["path.to.your.plugin"], ["path/to/your/plugins"]) ``` -------------------------------- ### Retrieve PausePromptResult Source: https://nonebot.dev/docs/advanced/dependency Get the result of the most recent prompt message sent via pause. ```python from typing import Any, Annotated from nonebot.params import PausePromptResult @matcher.handle() async def _(): await matcher.pause(prompt="prompt") @matcher.handle() async def _(result: Annotated[Any, PausePromptResult()]): ... ``` ```python from typing import Any from nonebot.params import PausePromptResult @matcher.handle() async def _(): await matcher.pause(prompt="prompt") @matcher.handle() async def _(result: Any = PausePromptResult()): ... ``` -------------------------------- ### 创建基础命令响应器 Source: https://nonebot.dev/docs/tutorial/matcher 使用 on_command 辅助函数创建一个响应特定命令的事件响应器。 ```python from nonebot import on_command weather = on_command("天气") ``` -------------------------------- ### Get All Bot Instances Source: https://nonebot.dev/docs/api Retrieves a dictionary of all connected Bot objects keyed by their self_id. ```python bots = nonebot.get_bots() ``` -------------------------------- ### 升级与卸载驱动器命令 Source: https://nonebot.dev/docs/tutorial/store 使用 nb-cli 或 pip 对已安装的驱动器进行升级或卸载。卸载后需手动移除适配器加载配置。 ```bash nb driver update <驱动器名称> nb driver uninstall <驱动器名称> ``` ```bash $ nb driver update [?] 想要安装的驱动器名称: <驱动器名称> $ nb driver uninstall [?] 想要卸载的驱动器名称: <驱动器名称> ``` ```bash pip install --upgrade <驱动器包名> pip uninstall <驱动器包名> ``` -------------------------------- ### VS Code 项目配置 Source: https://nonebot.dev/docs/editor-support 通过 .vscode/settings.json 配置 Pylance 语言服务器及类型检查模式。 ```json { "python.languageServer": "Pylance", "python.analysis.typeCheckingMode": "basic" } ``` -------------------------------- ### Get Registered Adapter Source: https://nonebot.dev/docs/api Retrieves a specific registered Adapter instance by name or type. ```python from nonebot.adapters.console import Adapter adapter = nonebot.get_adapter(Adapter) ``` -------------------------------- ### 通过模块路径获取插件 Source: https://nonebot.dev/docs/advanced/plugin-info 使用 get_plugin_by_module_name 根据完整的模块路径获取插件对象。 ```python import nonebot plugin: Plugin | None = nonebot.get_plugin_by_module_name("awesome_bot.plugins.example") ``` -------------------------------- ### 插件升级与卸载 Source: https://nonebot.dev/docs/tutorial/store 提供通过命令行、交互式界面或 pip 升级和卸载插件的方法。 ```bash nb plugin update <插件名称> nb plugin uninstall <插件名称> ``` ```bash $ nb plugin update [?] 想要安装的插件名称: <插件名称> $ nb plugin uninstall [?] 想要卸载的插件名称: <插件名称> ``` ```bash pip install --upgrade <插件包名> pip uninstall <插件包名> ``` -------------------------------- ### 使用 bump-my-version 更新版本 Source: https://nonebot.dev/docs/developer/plugin-publishing 通过 bump-my-version 工具管理项目版本并触发发布。 ```bash # 安装 bump-my-version pdm add --dev bump-my-version # 更新 patch 版本 pdm run bump patch # 推送 tag 触发发布 git push origin --tags ``` ```bash # 更新 patch 版本 uv run poe bump patch # 推送 tag 触发发布 git push origin --tags ``` ```bash # 安装 bump-my-version poetry add --dev bump-my-version # 更新 patch 版本 poetry run bump patch # 推送 tag 触发发布 git push origin --tags ``` -------------------------------- ### Get Received Event Source: https://nonebot.dev/docs/appendices/session-control Retrieves an event received via 'receive'. Returns the default value or None if the ID does not exist. ```python from nonebot.matcher import Matcher @matcher.handle() async def _(matcher: Matcher): event = matcher.get_receive("id", default=None) ``` -------------------------------- ### 通过索引名称获取插件 Source: https://nonebot.dev/docs/advanced/plugin-info 使用 get_plugin 根据插件的索引名称获取对应的插件对象。 ```python import nonebot plugin: Plugin | None = nonebot.get_plugin("example") ``` -------------------------------- ### 查询驱动器列表与搜索 Source: https://nonebot.dev/docs/tutorial/store 列出商店中所有可用的驱动器或根据关键词进行搜索。 ```bash # 列出商店所有驱动器 nb driver list # 搜索商店驱动器 nb driver search [可选关键词] ``` -------------------------------- ### Get Session Argument Source: https://nonebot.dev/docs/appendices/session-control Retrieves an argument received via 'got'. Returns the default value or None if the key does not exist. ```python from nonebot.matcher import Matcher @matcher.handle() async def _(matcher: Matcher): key = matcher.get_arg("key", default=None) ``` -------------------------------- ### Get Global Driver Instance Source: https://nonebot.dev/docs/api Retrieves the global Driver instance. Useful in contexts like scheduled task callbacks. ```python driver = nonebot.get_driver() ``` -------------------------------- ### 使用 load_plugins 加载目录 Source: https://nonebot.dev/docs/tutorial/create-plugin 加载指定目录下的所有插件。 ```python nonebot.load_plugins("src/plugins", "path/to/your/plugins") ``` -------------------------------- ### Load plugin configuration Source: https://nonebot.dev/docs/appendices/config Use get_plugin_config to instantiate the configuration model for use within a plugin. ```python from nonebot import get_plugin_config from .config import Config plugin_config = get_plugin_config(Config) weather = on_command( "天气", rule=to_me(), aliases={"weather", "查天气"}, priority=plugin_config.weather_command_priority, block=True, ) ``` -------------------------------- ### Get Last Received Event Source: https://nonebot.dev/docs/appendices/session-control Retrieves the most recent event received via 'receive'. Returns the default value or None if no event exists. ```python from nonebot.matcher import Matcher @matcher.handle() async def _(matcher: Matcher): event = matcher.get_last_receive(default=None) ``` -------------------------------- ### 使用 nb-cli 创建插件 Source: https://nonebot.dev/docs/tutorial/create-plugin 通过命令行交互创建插件。 ```text $ nb plugin create [?] 插件名称: weather [?] 使用嵌套插件? (y/N) N [?] 请输入插件存储位置: awesome_bot/plugins ``` -------------------------------- ### Get Bot Instance Source: https://nonebot.dev/docs/api Retrieves a connected Bot object. Providing a self_id returns a specific bot, otherwise returns an available one. ```python assert nonebot.get_bot("12345") == nonebot.get_bots()["12345"] another_unspecified_bot = nonebot.get_bot() ``` -------------------------------- ### 插件创建后的目录结构 Source: https://nonebot.dev/docs/tutorial/create-plugin 展示使用 nb-cli 创建插件后的目录结构。 ```text 📦 awesome-bot ├── 📂 .venv ├── 📂 awesome_bot │ └── 📂 plugins | └── 📂 weather | ├── 📜 __init__.py | └── 📜 config.py ├── 📜 .env.prod ├── 📜 pyproject.toml └── 📜 README.md ``` -------------------------------- ### 升级与卸载适配器 Source: https://nonebot.dev/docs/tutorial/store 通过命令行、交互式界面或 pip 升级和卸载已安装的适配器。 ```bash nb adapter update <适配器名称> nb adapter uninstall <适配器名称> ``` ```bash $ nb adapter update [?] 想要安装的适配器名称: <适配器名称> $ nb adapter uninstall [?] 想要卸载的适配器名称: <适配器名称> ``` ```bash pip install --upgrade <适配器包名> pip uninstall <适配器包名> ``` -------------------------------- ### 使用 nb-cli 创建嵌套插件 Source: https://nonebot.dev/docs/advanced/plugin-nesting 通过 nb-cli 交互式命令创建嵌套插件结构。 ```shell $ nb plugin create [?] 插件名称: parent [?] 使用嵌套插件? (y/N) Y [?] 输出目录: awesome_bot/plugins ``` -------------------------------- ### 自定义日志处理器 Source: https://nonebot.dev/docs/appendices/log 移除默认处理器并添加自定义配置,需在 nonebot.init 之前执行。 ```python from nonebot.log import logger_id # 移除 NoneBot 默认的日志处理器 logger.remove(logger_id) # 添加新的日志处理器 logger.add( sys.stdout, level=0, diagnose=True, format="<g>{time:MM-DD HH:mm:ss}</g> [<lvl>{level}</lvl>] <c><u>{name}</u></c> | {message}", filter=default_filter ) ``` -------------------------------- ### 插件列表与搜索 Source: https://nonebot.dev/docs/tutorial/store 使用命令行工具查看商店中所有插件或根据关键词进行搜索。 ```bash # 列出商店所有插件 nb plugin list # 搜索商店插件 nb plugin search [可选关键词] ``` -------------------------------- ### 定义插件元数据 Source: https://nonebot.dev/docs/advanced/plugin-info 在插件的顶层模块(如 __init__.py)中定义 __plugin_meta__ 变量以提供插件的描述信息。 ```python from nonebot.plugin import PluginMetadata from .config import Config __plugin_meta__ = PluginMetadata( name="示例插件", description="这是一个示例插件", usage="没什么用", type="application", config=Config, extra={}, ) ``` -------------------------------- ### 安装驱动器命令 Source: https://nonebot.dev/docs/tutorial/store 使用 nb-cli 或 pip 安装驱动器。安装后需手动修改 DRIVER 配置项。 ```bash nb driver install <驱动器名称> ``` ```bash $ nb driver install [?] 想要安装的驱动器名称: <驱动器名称> ``` ```bash pip install <驱动器包名> ``` -------------------------------- ### 使用项目管理器更新版本 Source: https://nonebot.dev/docs/developer/plugin-publishing 利用 PDM、uv 或 Poetry 原生功能更新版本号。 ```bash # 安装 pdm-bump pdm self add pdm-bump # 更新 patch 版本 pdm bump patch # 推送 tag 触发发布 git push origin --tags ``` ```bash # 更新 patch 版本 uv version --bump patch # 创建相应提交与标签 git add pyproject.toml git commit -m "chore: release v0.1.1" # 替换为实际的版本号 git tag v0.1.1 # 替换为实际的版本号 # 推送 tag 触发发布 git push origin --tags ``` ```bash # 更新版本(自动提交并打标签) poetry version patch # 推送 tag 触发发布 git push origin --tags ``` -------------------------------- ### got Source: https://nonebot.dev/docs/appendices/session-control 在函数运行前中断流程,等待接收特定 key 的消息,支持 prompt 提示。 ```APIDOC ## @matcher.got(key, prompt=None) ### Description 中断当前流程,若会话状态中不存在 key,则发送 prompt 并等待用户回复。 ### Parameters - **key** (str) - 必填 - 标识符 - **prompt** (str/Message) - 可选 - 询问消息 ``` -------------------------------- ### 获取已加载的插件 Source: https://nonebot.dev/docs/advanced/plugin-info 使用 get_loaded_plugins 获取当前所有已导入的插件集合。 ```python import nonebot plugins: set[Plugin] = nonebot.get_loaded_plugins() ``` -------------------------------- ### 创建 bot.py 入口文件 Source: https://nonebot.dev/docs/tutorial/application 初始化 NoneBot 框架、注册适配器并加载插件的入口脚本。 ```python import nonebot from nonebot.adapters.console import Adapter as ConsoleAdapter # 避免重复命名 # 初始化 NoneBot nonebot.init() # 注册适配器 driver = nonebot.get_driver() driver.register_adapter(ConsoleAdapter) # 在这里加载插件 nonebot.load_builtin_plugins("echo") # 内置插件 # nonebot.load_plugin("thirdparty_plugin") # 第三方插件 # nonebot.load_plugins("awesome_bot/plugins") # 本地插件 if __name__ == "__main__": nonebot.run() ``` -------------------------------- ### 配置 pyproject.toml 插件目录 Source: https://nonebot.dev/docs/tutorial/create-plugin 在 pyproject.toml 中添加插件目录配置。 ```toml [tool.nonebot] plugin_dirs = ["awesome_bot/plugins"] ``` -------------------------------- ### 使用 join 方法拼接消息 Source: https://nonebot.dev/docs/tutorial/message 通过 join 方法将多个消息段或序列连接在一起。 ```python seg = MessageSegment.text("text") msg = seg.join( [ MessageSegment.text("first"), Message( [ MessageSegment.text("second"), MessageSegment.text("third"), ] ) ] ) msg == Message( [ MessageSegment.text("first"), MessageSegment.text("text"), MessageSegment.text("second"), MessageSegment.text("third"), ] ) ``` -------------------------------- ### 获取所有声明的插件名称 Source: https://nonebot.dev/docs/advanced/plugin-info 使用 get_available_plugin_names 获取当前所有已声明但可能尚未加载的插件名称。 ```python import nonebot plugin_names: set[str] = nonebot.get_available_plugin_names() ``` -------------------------------- ### 创建并激活虚拟环境 Source: https://nonebot.dev/docs/tutorial/application 为项目创建独立的 Python 虚拟环境以隔离依赖。 ```bash # 创建虚拟环境 python -m venv .venv --prompt nonebot2 # 激活虚拟环境 .venv\Scripts\activate ``` ```bash # 创建虚拟环境 python -m venv .venv --prompt nonebot2 # 激活虚拟环境 source .venv/bin/activate ``` -------------------------------- ### Handle Startswith Source: https://nonebot.dev/docs/advanced/dependency Retrieves the message prefix string that triggered the responder. ```python from typing import Annotated from nonebot.params import Startswith async def _(foo: Annotated[str, Startswith()]): ... ``` ```python from nonebot.params import Startswith async def _(foo: str = Startswith()): ... ``` -------------------------------- ### 适配器列表与搜索 Source: https://nonebot.dev/docs/tutorial/store 列出商店中所有适配器或根据关键词搜索适配器。 ```bash # 列出商店所有适配器 nb adapter list # 搜索商店适配器 nb adapter search [可选关键词] ``` -------------------------------- ### 运行项目 Source: https://nonebot.dev/docs/quick-start 在项目目录下启动机器人。 ```bash nb run ``` -------------------------------- ### 配置 .env 文件 Source: https://nonebot.dev/docs/tutorial/application 定义 NoneBot 运行时的基础配置项,如监听地址和命令格式。 ```text HOST=0.0.0.0 # 配置 NoneBot 监听的 IP / 主机名 PORT=8080 # 配置 NoneBot 监听的端口 COMMAND_START=["/"] # 配置命令起始字符 COMMAND_SEP=["."] # 配置命令分割字符 ``` -------------------------------- ### 获取已注册的适配器 Source: https://nonebot.dev/docs/advanced/adapter 通过 get_adapter 方法或适配器名称获取已注册的适配器实例。 ```python import nonebot from nonebot.adapters.console import Adapter adapters = nonebot.get_adapters() console_adapter = nonebot.get_adapter(Adapter) console_adapter = nonebot.get_adapter(Adapter.get_name()) ``` -------------------------------- ### 安装 Console 适配器 Source: https://nonebot.dev/docs/tutorial/application 安装用于控制台交互的适配器。 ```bash pip install nonebot-adapter-console ``` -------------------------------- ### 使用 command 规则 Source: https://nonebot.dev/docs/advanced/matcher 匹配消息是否为命令,支持配置命令前缀和分隔符。 ```python from nonebot.rule import command # 匹配 "/help" 或者 "/帮助" 开头的消息 rule = command("help", "帮助") # 匹配 "/help.cmd" 开头的消息 rule = command(("help", "cmd")) ``` ```python from nonebot import on_command matcher = on_command("help", aliases={"帮助"}) ``` ```python rule = command("help", force_whitespace=True) rule = command("help", force_whitespace=" ") ``` -------------------------------- ### 安装 nb-cli 脚手架 Source: https://nonebot.dev/docs/quick-start 通过 pipx 安装 NoneBot 命令行工具。 ```bash pipx install nb-cli ``` -------------------------------- ### 项目模板选择 Source: https://nonebot.dev/docs/quick-start 选择项目模板,bootstrap 适用于初学者。 ```text [?] 选择一个要使用的模板: bootstrap (初学者或用户) ``` -------------------------------- ### 直接向 ASGI 应用添加路由 Source: https://nonebot.dev/docs/advanced/routing 获取底层应用实例后,直接使用框架(如 FastAPI)的路由功能。 ```python import nonebot from fastapi import FastAPI app: FastAPI = nonebot.get_app() @app.get("/api") async def custom_api(): return {"message": "Hello, world!"} ``` -------------------------------- ### 使用 nb-cli 启动重载 Source: https://nonebot.dev/docs/advanced/driver 推荐使用 nb-cli 命令行工具配合 --reload 参数进行开发调试,以避免 Windows 平台下的潜在问题。 ```bash nb run --reload ``` -------------------------------- ### 判断驱动器是否支持路由 Source: https://nonebot.dev/docs/advanced/routing 通过检查驱动器是否实现了 ASGIMixin 来确定是否可以添加路由规则。 ```python from nonebot import get_driver from nonebot.drivers import ASGIMixin can_use = isinstance(get_driver(), ASGIMixin) ``` -------------------------------- ### 获取驱动器实例 Source: https://nonebot.dev/docs/advanced/driver 在 NoneBot 初始化完成后,使用 get_driver 方法获取全局驱动器实例。 ```python from nonebot import get_driver driver = get_driver() ``` -------------------------------- ### Inject CommandStart Source: https://nonebot.dev/docs/advanced/dependency Retrieve the command prefix for command-type events. ```python from typing import Annotated from nonebot.params import CommandStart async def _(foo: Annotated[str, CommandStart()]): ... ``` ```python from nonebot.params import CommandStart async def _(foo: str = CommandStart()): ... ``` -------------------------------- ### Manage Local Files with nonebot-plugin-localstore Source: https://nonebot.dev/docs/developer/plugin-publishing Use the localstore plugin to manage cache, configuration, and data files in a standardized way. ```python from pathlib import Path from nonebot import require require("nonebot_plugin_localstore") import nonebot_plugin_localstore as store # 获取插件缓存文件(夹)路径 weather_cache_dir: Path = store.get_plugin_cache_dir() weather_cache_file: Path = store.get_plugin_cache_file("cache.json") # 获取插件配置文件(夹)路径 weather_config_dir: Path = store.get_plugin_config_dir() weather_config_file: Path = store.get_plugin_config_file("config.toml") # 获取插件数据文件(夹)路径 weather_data_dir: Path = store.get_plugin_data_dir() weather_data_file: Path = store.get_plugin_data_file("resource-index.json") ``` -------------------------------- ### 创建 NoneBot 项目 Source: https://nonebot.dev/docs/quick-start 启动项目创建向导。 ```bash nb create ``` -------------------------------- ### 修改消息序列 Source: https://nonebot.dev/docs/tutorial/message 使用 append、extend 或自加操作修改现有的消息序列。 ```python msg = Message([MessageSegment.text("text")]) # 自加 msg += "text" msg += MessageSegment.text("text") msg += Message([MessageSegment.text("text")]) # 附加 msg.append("text") msg.append(MessageSegment.text("text")) # 扩展 msg.extend([MessageSegment.text("text")]) ``` -------------------------------- ### 安装项目依赖与开发环境 Source: https://nonebot.dev/docs/developer/plugin-publishing 使用 PDM、uv 或 Poetry 初始化项目并安装依赖。 ```bash # 安装 PDM(若未安装) curl -sSL https://pdm-project.org/install-pdm.py | python3 - # 安装项目依赖(自动创建虚拟环境) pdm sync # 添加新依赖(如 httpx) pdm add httpx ``` ```bash # 安装 uv(Windows) powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # 安装 uv(macOS/Linux) curl -LsSf https://astral.sh/uv/install.sh | sh # 安装所有依赖(含 dev) uv sync --all-groups -p 3.12 # 添加新依赖 uv add httpx ``` ```bash # 安装 Poetry(推荐方式) curl -sSL https://install.python-poetry.org | python3 - # 安装项目依赖 poetry install # 添加新依赖 poetry add httpx ``` -------------------------------- ### NB-CLI 模板选择界面 Source: https://nonebot.dev/docs/editor-support 展示创建项目时选择模板和开发工具的交互界面。 ```text [?] 选择一个要使用的模板: simple (插件开发者) ... [?] 要使用哪些开发工具? ``` -------------------------------- ### 在 bot.py 中加载插件 Source: https://nonebot.dev/docs/tutorial/create-plugin 在机器人入口文件中加载内置插件和本地插件。 ```python # 在这里加载插件 nonebot.load_builtin_plugins("echo") # 内置插件 nonebot.load_plugins("awesome_bot/plugins") # 本地插件 ``` -------------------------------- ### 配置 FastAPI/Quart 应用路径 Source: https://nonebot.dev/docs/advanced/driver 在机器人入口文件中提供 ASGI 应用路径以启用驱动器的重载功能。 ```python app = nonebot.get_asgi() nonebot.run(app="bot:app") ``` -------------------------------- ### Define Environment Settings Source: https://nonebot.dev/docs/appendices/config Specify the environment in the .env file to determine which environment-specific configuration file to load. ```text ENVIRONMENT=dev COMMON_CONFIG=common config # 这个配置项在任何环境中都会被加载 ``` -------------------------------- ### 配置超级用户 Source: https://nonebot.dev/docs/appendices/permission 在 dotenv 文件中定义超级用户列表。 ```text SUPERUSERS=["console_user"] ``` -------------------------------- ### handle Source: https://nonebot.dev/docs/appendices/session-control 用于向事件处理流程添加一个事件处理函数。 ```APIDOC ## @matcher.handle() ### Description 将一个异步函数注册为事件处理函数,按添加顺序执行。 ### Usage ```python @matcher.handle() async def handle_func(): ... ``` ``` -------------------------------- ### 导入调度器 Source: https://nonebot.dev/docs/best-practice/scheduler 使用 require 方法加载插件并导入 scheduler 对象。 ```python from nonebot import require require("nonebot_plugin_apscheduler") from nonebot_plugin_apscheduler import scheduler ``` -------------------------------- ### Specify Environment File Source: https://nonebot.dev/docs/appendices/config Override the default environment configuration by explicitly specifying the file during initialization. ```python nonebot.init(_env_file=".env.dev") ``` -------------------------------- ### 机器人入口文件模板 Source: https://nonebot.dev/docs/tutorial/create-plugin 机器人入口文件的基础结构。 ```python import nonebot nonebot.init() # 加载插件 nonebot.run() ``` -------------------------------- ### 手动更新版本 Source: https://nonebot.dev/docs/developer/plugin-publishing 手动修改 pyproject.toml 并通过 Git 标签触发发布。 ```bash git add pyproject.toml git commit -m "chore: release v0.1.1" # 替换为实际的版本号 git tag v0.1.1 # 替换为实际的版本号 git push origin --tags ``` -------------------------------- ### 使用 load_plugin 加载插件 Source: https://nonebot.dev/docs/tutorial/create-plugin 通过模块名或路径加载单个插件。 ```python from pathlib import Path nonebot.load_plugin("path.to.your.plugin") # 加载第三方插件 nonebot.load_plugin(Path("./path/to/your/plugin.py")) # 加载项目插件 ``` -------------------------------- ### 配置 Driver Source: https://nonebot.dev/docs/appendices/config 设置 NoneBot 运行所使用的驱动器。 ```text DRIVER=~fastapi+~httpx+~websockets ``` ```bash # windows cmd set DRIVER '~fastapi+~httpx+~websockets' # windows powershell $Env:DRIVER='~fastapi+~httpx+~websockets' # linux/macOS export DRIVER='~fastapi+~httpx+~websockets' ``` ```python import nonebot nonebot.init(driver="~fastapi+~httpx+~websockets") ``` -------------------------------- ### 使用 TOML 配置加载插件 Source: https://nonebot.dev/docs/tutorial/create-plugin 通过 TOML 文件配置并加载插件。 ```toml [tool.nonebot] plugin_dirs = ["path/to/your/plugins"] [tool.nonebot.plugins] "@local" = ["path.to.your.plugin"] # 本地插件等非插件商店来源的插件 "nonebot-plugin-someplugin" = ["nonebot_plugin_someplugin"] # 插件商店来源的插件 ``` ```python nonebot.load_from_toml("plugin_config.toml", encoding="utf-8") ``` -------------------------------- ### 使用 ArgPlainText 获取用户输入 Source: https://nonebot.dev/docs/appendices/session-control 在 got 装饰器后的处理函数中,通过 ArgPlainText 依赖注入获取用户回复的纯文本内容。 ```python from nonebot.params import ArgPlainText @weather.handle() async def handle_function(args: Message = CommandArg()): if location := args.extract_plain_text(): await weather.finish(f"今天{location}的天气是...") @weather.got("location", prompt="请输入地名") async def got_location(location: str = ArgPlainText()): await weather.finish(f"今天{location}的天气是...") ``` -------------------------------- ### Define plugin configuration model Source: https://nonebot.dev/docs/appendices/config Create a Pydantic model to define and validate plugin configuration settings. ```python from pydantic import BaseModel, field_validator class Config(BaseModel): weather_api_key: str weather_command_priority: int = 10 weather_plugin_enabled: bool = True @field_validator("weather_command_priority") @classmethod def check_priority(cls, v: int) -> int: if v >= 1: return v raise ValueError("weather command priority must greater than 1") ``` -------------------------------- ### Define Parameterless Pre-dependencies Source: https://nonebot.dev/docs/advanced/dependency Use the parameterless argument in handle to execute dependencies before the handler without passing their return values. ```python from nonebot import on_command from nonebot.adapters import Event from nonebot.params import Depends test = on_command("test") async def check(event: Event): if event.get_user_id() in BLACKLIST: await test.finish() @test.handle(parameterless=[Depends(check)]) async def _(): ... ``` -------------------------------- ### NB-CLI 插件安装界面 Source: https://nonebot.dev/docs/tutorial/store 展示在终端中使用 nb plugin 命令进入交互式安装界面的场景。 ```text ~/tutorial/awesome-bot is v0.1.0 via v3.9.12 env base took 5s 12:03 ❯ nb plugin (base) [?] 你想要进行什么操作? 安装插件到当前项目. ``` -------------------------------- ### 插件安装方式 Source: https://nonebot.dev/docs/tutorial/store 提供通过命令行、交互式界面或 pip 安装插件的多种方式。 ```bash nb plugin install <插件名称> ``` ```bash $ nb plugin install [?] 想要安装的插件名称: <插件名称> ``` ```bash pip install <插件包名> ``` -------------------------------- ### 使用 startswith 规则 Source: https://nonebot.dev/docs/advanced/matcher 匹配消息纯文本部分的开头。ignorecase 参数用于控制是否忽略大小写。 ```python from nonebot.rule import startswith rule = startswith(("!", "/"), ignorecase=False) ``` ```python from nonebot import on_startswith matcher = on_startswith(("!", "/"), ignorecase=False) ``` -------------------------------- ### 注册适配器 Source: https://nonebot.dev/docs/advanced/adapter 使用驱动器的 register_adapter 方法将适配器类注册到 NoneBot 中。 ```python import nonebot from nonebot.adapters.console import Adapter driver = nonebot.get_driver() driver.register_adapter(Adapter) ``` -------------------------------- ### 使用内置超级用户权限 Source: https://nonebot.dev/docs/appendices/permission 在事件响应器中通过 permission 参数限制仅超级用户可触发。 ```python from typing import Tuple from nonebot.params import Command from nonebot.permission import SUPERUSER manage = on_command( ("天气", "启用"), rule=to_me(), aliases={("天气", "禁用")}, permission=SUPERUSER, ) @manage.handle() async def control(cmd: Tuple[str, str] = Command()): _, action = cmd if action == "启用": plugin_config.weather_plugin_enabled = True elif action == "禁用": plugin_config.weather_plugin_enabled = False await manage.finish(f"天气插件已{action}") ``` -------------------------------- ### 卸载旧版 NoneBot Source: https://nonebot.dev/docs/quick-start 在安装新版本前,确保卸载可能存在的 NoneBot v1。 ```bash pip uninstall nonebot ``` -------------------------------- ### Initialize NoneBot Source: https://nonebot.dev/docs/api Initializes NoneBot and the global Driver object, reading configuration from environment files. ```python nonebot.init(database=Database(...)) ``` -------------------------------- ### 运行机器人 Source: https://nonebot.dev/docs/tutorial/application 通过 Python 解释器启动入口文件以运行机器人。 ```bash # 激活虚拟环境(未使用虚拟环境时跳过此行) .venv\Scripts\activate # 运行机器人 python bot.py ``` ```bash # 激活虚拟环境(未使用虚拟环境时跳过此行) source .venv/bin/activate # 运行机器人 python bot.py ``` -------------------------------- ### 配置 FastAPI 驱动器 Source: https://nonebot.dev/docs/advanced/driver 设置环境变量以使用 FastAPI 作为默认的 ASGI 服务端驱动器。 ```text DRIVER=~fastapi ``` -------------------------------- ### 安装适配器 Source: https://nonebot.dev/docs/tutorial/store 通过命令行、交互式界面或 pip 安装适配器。 ```bash nb adapter install <适配器名称> ``` ```bash $ nb adapter install [?] 想要安装的适配器名称: <适配器名称> ``` ```bash pip install <适配器包名> ``` -------------------------------- ### 使用 got 装饰器询问用户输入 Source: https://nonebot.dev/docs/appendices/session-control 使用 got 装饰器标记需要询问的参数,并指定提示消息。事件处理函数会按定义顺序执行。 ```python @weather.handle() async def handle_function(args: Message = CommandArg()): if location := args.extract_plain_text(): await weather.finish(f"今天{location}的天气是...") @weather.got("location", prompt="请输入地名") async def got_location(): ... ``` -------------------------------- ### 将日志输出到文件 Source: https://nonebot.dev/docs/appendices/log 使用 logger.add 方法添加文件处理器,支持设置日志级别、格式及轮转策略。 ```python logger.add("error.log", level="ERROR", format=default_format, rotation="1 week") ``` -------------------------------- ### 记录异常堆栈信息 Source: https://nonebot.dev/docs/appendices/log 通过设置 exception=True 选项,在记录错误日志时包含异常堆栈信息。 ```python try: 1 / 0 except ZeroDivisionError: logger.opt(exception=True).error("ZeroDivisionError") ``` -------------------------------- ### 导入默认格式与过滤器 Source: https://nonebot.dev/docs/appendices/log 从 nonebot.log 模块导入预定义的格式和过滤器以保持日志风格一致。 ```python from nonebot.log import default_format, default_filter ``` -------------------------------- ### 使用 keyword 规则 Source: https://nonebot.dev/docs/advanced/matcher 匹配消息纯文本部分是否包含指定字符串。 ```python from nonebot.rule import keyword rule = keyword("hello", "hi") ``` ```python from nonebot import on_keyword matcher = on_keyword({"hello", "hi"}) ```