diff --git a/danding_bot/plugins/danding_points/config.py b/danding_bot/plugins/danding_points/config.py index 8e2cc76..9242b39 100644 --- a/danding_bot/plugins/danding_points/config.py +++ b/danding_bot/plugins/danding_points/config.py @@ -3,6 +3,33 @@ from pydantic_settings import BaseSettings, SettingsConfigDict import os +def _read_nonebot_config(name: str) -> str: + """从 NoneBot driver.config 读取配置;测试或独立加载模块时静默回退。 + + 与 onmyoji_gacha/config.py 同模式:NoneBot 会把 .env 注入 driver.config + 而不是系统环境变量,积分 API 的 token 需要从这里回退读取。 + """ + + try: + from nonebot import get_driver + + driver_config = get_driver().config + except Exception: + return "" + value = getattr(driver_config, name.lower(), "") + return str(value) if value is not None else "" + + +def _first_setting(*names: str, default: str = "") -> str: + """按业务优先级读取多个兼容配置名(环境变量 → NoneBot driver.config)。""" + + for name in names: + value = os.getenv(name, "") or _read_nonebot_config(name) + if value: + return value + return default + + class Config(BaseSettings): """Points system configuration.""" @@ -11,11 +38,15 @@ class Config(BaseSettings): ) # xapi /bot/points 运行时 API 配置 - POINTS_API_HOST: str = os.getenv("DANDING_POINTS_API_HOST", "https://api.danding.vip/bot/points") - BOT_USER: str = os.getenv("DANDING_BOT_USER", "1424473282") - BOT_TOKEN: str = os.getenv( + POINTS_API_HOST: str = _first_setting( + "DANDING_POINTS_API_HOST", + default="https://api.danding.vip/bot/points", + ) + BOT_USER: str = _first_setting("DANDING_BOT_USER", default="1424473282") + BOT_TOKEN: str = _first_setting( "DANDING_BOT_TOKEN", - os.getenv("DANDING_API_TOKEN", os.getenv("BOT_TOKEN", "")), + "DANDING_API_TOKEN", + "BOT_TOKEN", ) @field_validator("POINTS_API_HOST")