This commit is contained in:
2026-04-04 00:37:28 +08:00
parent 28702e3228
commit 3372242d78
3 changed files with 47 additions and 63 deletions

View File

@@ -16,7 +16,27 @@ __plugin_meta__ = PluginMetadata(
}, },
) )
# Load config from NoneBot driver # 从 NoneBot driver config 中提取本插件配置(去掉 GROUP_HORSE_RACING_ 前缀)
plugin_config = Config() _nb_config = get_driver().config
_raw = _nb_config.model_dump() if hasattr(_nb_config, "model_dump") else _nb_config.dict()
_prefix = "GROUP_HORSE_RACING_"
plugin_config = Config(**{
k[len(_prefix):]: v
for k, v in _raw.items()
if k.startswith(_prefix)
})
print("[group_horse_racing] Config loaded from NoneBot driver:")
print(f" TEST_MODE = {plugin_config.TEST_MODE}")
print(f" TESTERS = {plugin_config.TESTERS}")
print(f" TEST_GROUPS = {plugin_config.TEST_GROUPS}")
print(f" ALLOWED_GROUPS = {plugin_config.ALLOWED_GROUPS}")
print(f" PARTICIPANT_REWARD = {plugin_config.PARTICIPANT_REWARD}")
print(f" CHAMPION_REWARD = {plugin_config.CHAMPION_REWARD}")
print(f" MIN_BET = {plugin_config.MIN_BET}")
print(f" MIN_ODDS = {plugin_config.MIN_ODDS}")
print(f" RACE_DISTANCE = {plugin_config.RACE_DISTANCE}")
print(f" RACE_TICK_INTERVAL = {plugin_config.RACE_TICK_INTERVAL}")
print(f" RACE_DB_FILE = {plugin_config.RACE_DB_FILE}")
from . import commands, test_commands # noqa: F401, E402 from . import commands, test_commands # noqa: F401, E402

View File

@@ -1,28 +1,27 @@
from pydantic import Field, field_validator from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
from typing import Union
import os
import json import json
class Config(BaseSettings): class Config(BaseSettings):
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
extra="ignore", extra="ignore",
env_prefix="GROUP_HORSE_RACING_",
) )
# 测试模式配置 # 测试模式配置
TEST_MODE: bool = os.getenv("GROUP_HORSE_RACING_TEST_MODE", "False").lower() == "true" TEST_MODE: bool = False
TESTERS: set[int] = Field(default_factory=set) TESTERS: set[int] = Field(default_factory=set)
TEST_GROUPS: set[int] = Field(default_factory=set) TEST_GROUPS: set[int] = Field(default_factory=set)
ALLOWED_GROUPS: set[int] = Field(default_factory=set) ALLOWED_GROUPS: set[int] = Field(default_factory=set)
# 奖励配置 # 奖励配置
PARTICIPANT_REWARD: int = int(os.getenv("GROUP_HORSE_RACING_PARTICIPANT_REWARD", "50")) PARTICIPANT_REWARD: int = 50
CHAMPION_REWARD: int = int(os.getenv("GROUP_HORSE_RACING_CHAMPION_REWARD", "200")) CHAMPION_REWARD: int = 200
MIN_BET: int = int(os.getenv("GROUP_HORSE_RACING_MIN_BET", "10")) MIN_BET: int = 10
MIN_ODDS: float = float(os.getenv("GROUP_HORSE_RACING_MIN_ODDS", "1.2")) MIN_ODDS: float = 1.2
RACE_DISTANCE: int = int(os.getenv("GROUP_HORSE_RACING_RACE_DISTANCE", "100")) RACE_DISTANCE: int = 100
RACE_TICK_INTERVAL: int = int(os.getenv("GROUP_HORSE_RACING_RACE_TICK_INTERVAL", "5")) RACE_TICK_INTERVAL: int = 5
# 消息撤回配置 # 消息撤回配置
MESSAGE_RECALL: dict[str, int] = Field( MESSAGE_RECALL: dict[str, int] = Field(
@@ -40,55 +39,7 @@ class Config(BaseSettings):
) )
# 数据库配置 # 数据库配置
RACE_DB_FILE: str = os.getenv("GROUP_HORSE_RACING_RACE_DB_FILE", "data/group_horse_racing/race.db") RACE_DB_FILE: str = "data/group_horse_racing/race.db"
def __init__(self, **data):
super().__init__(**data)
# 从环境变量解析 TESTERS
testers_env = os.getenv("GROUP_HORSE_RACING_TESTERS", "")
if testers_env:
self.TESTERS = self._parse_id_set(testers_env)
# 从环境变量解析 TEST_GROUPS
test_groups_env = os.getenv("GROUP_HORSE_RACING_TEST_GROUPS", "")
if test_groups_env:
self.TEST_GROUPS = self._parse_id_set(test_groups_env)
# 从环境变量解析 ALLOWED_GROUPS
allowed_groups_env = os.getenv("GROUP_HORSE_RACING_ALLOWED_GROUPS", "")
if allowed_groups_env:
self.ALLOWED_GROUPS = self._parse_id_set(allowed_groups_env)
# 调试:输出所有从环境变量获取的配置
print("[group_horse_racing] Config loaded from env:")
print(f" TEST_MODE = {self.TEST_MODE} (env: {os.getenv('GROUP_HORSE_RACING_TEST_MODE', '')!r})")
print(f" TESTERS = {self.TESTERS} (env: {os.getenv('GROUP_HORSE_RACING_TESTERS', '')!r})")
print(f" TEST_GROUPS = {self.TEST_GROUPS} (env: {os.getenv('GROUP_HORSE_RACING_TEST_GROUPS', '')!r})")
print(f" ALLOWED_GROUPS = {self.ALLOWED_GROUPS} (env: {os.getenv('GROUP_HORSE_RACING_ALLOWED_GROUPS', '')!r})")
print(f" PARTICIPANT_REWARD = {self.PARTICIPANT_REWARD}")
print(f" CHAMPION_REWARD = {self.CHAMPION_REWARD}")
print(f" MIN_BET = {self.MIN_BET}")
print(f" MIN_ODDS = {self.MIN_ODDS}")
print(f" RACE_DISTANCE = {self.RACE_DISTANCE}")
print(f" RACE_TICK_INTERVAL = {self.RACE_TICK_INTERVAL}")
print(f" RACE_DB_FILE = {self.RACE_DB_FILE}")
@staticmethod
def _parse_id_set(v: str) -> set[int]:
"""Parse ID sets from various formats."""
# Handle JSON string format like "[1424473282]"
try:
parsed = json.loads(v)
if isinstance(parsed, list):
return set(int(x) for x in parsed)
except (json.JSONDecodeError, ValueError, TypeError):
pass
# Handle comma-separated format
try:
return set(int(x.strip()) for x in v.split(",") if x.strip())
except ValueError:
pass
return set()
@field_validator("TESTERS", "TEST_GROUPS", "ALLOWED_GROUPS", mode="before") @field_validator("TESTERS", "TEST_GROUPS", "ALLOWED_GROUPS", mode="before")
@classmethod @classmethod
@@ -101,3 +52,18 @@ class Config(BaseSettings):
if isinstance(v, (list, tuple)): if isinstance(v, (list, tuple)):
return set(int(x) for x in v) return set(int(x) for x in v)
return v if isinstance(v, set) else set() return v if isinstance(v, set) else set()
@staticmethod
def _parse_id_set(v: str) -> set[int]:
"""Parse ID sets from various formats."""
try:
parsed = json.loads(v)
if isinstance(parsed, list):
return set(int(x) for x in parsed)
except (json.JSONDecodeError, ValueError, TypeError):
pass
try:
return set(int(x.strip()) for x in v.split(",") if x.strip())
except ValueError:
pass
return set()

View File

@@ -1,11 +1,9 @@
from nonebot import on_command from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, Event, GroupMessageEvent, PrivateMessageEvent from nonebot.adapters.onebot.v11 import Bot, Event, GroupMessageEvent, PrivateMessageEvent
from .config import Config from . import plugin_config as config
from .commands import get_scope, check_access, room_store, points_service from .commands import get_scope, check_access, room_store, points_service
config = Config()
async def check_tester(event: Event) -> bool: async def check_tester(event: Event) -> bool:
"""Check if user is a tester.""" """Check if user is a tester."""