mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-03-04 21:04:27 +08:00
563 lines
13 KiB
Plaintext
563 lines
13 KiB
Plaintext
|
---
|
|||
|
sidebar_position: 0
|
|||
|
description: 读取用户配置来控制插件行为
|
|||
|
|
|||
|
options:
|
|||
|
menu:
|
|||
|
weight: 10
|
|||
|
category: appendices
|
|||
|
---
|
|||
|
|
|||
|
# 配置
|
|||
|
|
|||
|
import Tabs from "@theme/Tabs";
|
|||
|
import TabItem from "@theme/TabItem";
|
|||
|
|
|||
|
配置是项目中非常重要的一部分,为了方便我们控制机器人的行为,NoneBot 提供了一套配置系统。下面我们将会补充[指南](../quick-start.mdx)中的天气插件,使其能够读取用户配置。在这之前,我们需要先了解一下配置系统,如果你已经了解了 NoneBot 中的配置方法,可以跳转到[编写插件配置](#插件配置)。
|
|||
|
|
|||
|
NoneBot 使用 [`pydantic`](https://docs.pydantic.dev/) 以及 [`python-dotenv`](https://saurabh-kumar.com/python-dotenv/) 来读取 dotenv 配置文件以及环境变量,从而控制机器人行为。配置文件需要符合 dotenv 格式,复杂数据类型需使用 JSON 格式或 [pydantic 支持格式](https://docs.pydantic.dev/usage/types/)填写。
|
|||
|
|
|||
|
NoneBot 内置的配置项列表及含义可以在[内置配置项](#内置配置项)中查看。
|
|||
|
|
|||
|
## 配置项的加载
|
|||
|
|
|||
|
在 NoneBot 中,我们可以把配置途径分为 **直接传入**、**系统环境变量**、**dotenv 配置文件** 三种,其加载优先级依次由高到低。
|
|||
|
|
|||
|
### 直接传入
|
|||
|
|
|||
|
在 NoneBot 初始化的过程中,可以通过 `nonebot.init()` 传入任意合法的 Python 变量,也可以在初始化完成后直接赋值。
|
|||
|
|
|||
|
通常,在初始化前的传参会在机器人的入口文件(如 `bot.py`)中进行,而初始化后的赋值可以在任何地方进行。
|
|||
|
|
|||
|
```python {4,8,9} title=bot.py
|
|||
|
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"
|
|||
|
```
|
|||
|
|
|||
|
### 系统环境变量
|
|||
|
|
|||
|
在 dotenv 配置文件中定义的配置项,也会在环境变量中进行寻找。如果在环境变量中发现同名配置项(大小写不敏感),将会覆盖 dotenv 中所填值。
|
|||
|
|
|||
|
例如,在 dotenv 配置文件中存在配置项 `custom_config`:
|
|||
|
|
|||
|
```dotenv
|
|||
|
CUSTOM_CONFIG=config in dotenv
|
|||
|
```
|
|||
|
|
|||
|
同时,设置环境变量:
|
|||
|
|
|||
|
```bash
|
|||
|
# windows
|
|||
|
set CUSTOM_CONFIG "config in environment variables"
|
|||
|
# linux/macOS
|
|||
|
export CUSTOM_CONFIG="config in environment variables"
|
|||
|
```
|
|||
|
|
|||
|
那最终 NoneBot 所读取的内容为环境变量中的内容,即 `config in environment variables`。
|
|||
|
|
|||
|
:::warning 注意
|
|||
|
NoneBot 不会自发读取未被定义的配置项的环境变量,如果需要读取某一环境变量需要在 dotenv 配置文件中进行声明。
|
|||
|
:::
|
|||
|
|
|||
|
### dotenv 配置文件
|
|||
|
|