65 lines
1.9 KiB
Python
65 lines
1.9 KiB
Python
from pydantic import field_validator
|
||
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."""
|
||
|
||
model_config = SettingsConfigDict(
|
||
extra="ignore",
|
||
)
|
||
|
||
# xapi /bot/points 运行时 API 配置
|
||
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",
|
||
"DANDING_API_TOKEN",
|
||
"BOT_TOKEN",
|
||
)
|
||
|
||
@field_validator("POINTS_API_HOST")
|
||
@classmethod
|
||
def validate_api_host(cls, value):
|
||
if not value:
|
||
raise ValueError("POINTS_API_HOST cannot be empty")
|
||
return value.rstrip("/")
|
||
|
||
@field_validator("BOT_USER")
|
||
@classmethod
|
||
def validate_bot_user(cls, value):
|
||
if not value:
|
||
raise ValueError("BOT_USER cannot be empty")
|
||
return value
|