-
-
Notifications
You must be signed in to change notification settings - Fork 6
Komorebi edited this page Feb 12, 2024
·
1 revision
在 SoraBot 中,我们使用 sora.config
模块中的 BaseConfig
来定义配置模型,这个模型可以被用于配置的读取和类型检查等。
例如在 weather
插件目录中新建 config.py
来定义一个模型:
from sora.config import BaseConfig
class Config(BaseConfig):
api_key: str
"""天气 API Key"""
command_to_me: bool = True
"""是否只有@bot或者私聊时才响应"""
allow_cities: list[str] = []
"""允许查询的城市列表"""
Note
BaseConfig
是通过 pydantic 实现的,它是 pydantic.BaseModel
的子类,同时进行了一些扩展,使其可以更好地适用于配置的读取。
我们可以使用 pydantic 提供的一些特性,例如 validator
,它可以用于对配置项进行合法性检查。
from pydantic import validator
from sora.config import BaseConfig
class Config(BaseConfig):
api_key: str
"""天气 API Key"""
command_to_me: bool = True
"""是否只有@bot或者私聊时才响应"""
allow_cities: list[str] = []
"""允许查询的城市列表"""
@validator("api_key")
def check_api_key(cls, v):
if isinstance(v, str) and len(v) < 10:
return v
raise ValueError("天气 API Key 不合法")
在上例中,我们定义了一个 check_api_key
方法,它用于检查 api_key
配置项的合法性。更多关于 pydantic 的用法,可以参考 pydantic 官方文档。
SoraBot 的配置文件在配置中有说明。这里我们以 sora.toml
为例,在其中添加 weather
插件的配置:
[weather]
api_key = "your_api_key"
allow_city = ["北京", "上海", "广州"]
在定义好配置模型和配置文件后,我们就可以在插件中读取配置了。例如在 weather/__init__.py
中:
from .config import Config
config = Config.load_config()
如果我们需要获取某个配置项,可以直接通过 config
对象的属性访问:
api_key = config.api_key
如果配置项不存在,将会抛出异常。
Warning
Config.load_config()
方法会自动读取插件名称对应的配置,例如在上例中,Config.load_config()
会读取 weather
对应的配置。如果你的插件名称与配置名称不同,那么你需要使用 Config.load("config_name")
来指定配置名称。