LiteyukiBot-TriM/liteyuki/utils/config.py

41 lines
1.2 KiB
Python
Raw Normal View History

2024-03-19 05:16:25 +00:00
import os
import nonebot
import yaml
from pydantic import BaseModel
2024-03-18 10:21:56 +00:00
from liteyuki.utils.tools import random_hex_string
config = {} # 全局配置,确保加载后读取
2024-03-18 16:27:40 +00:00
2024-03-18 10:21:56 +00:00
2024-03-19 05:16:25 +00:00
class BasicConfig(BaseModel):
host: str = "127.0.0.1"
port: int = 20216
superusers: list[str] = []
command_start: list[str] = ["/", ""]
nickname: list[str] = [f"LiteyukiBot-{random_hex_string(6)}"]
2024-03-19 05:16:25 +00:00
2024-03-18 10:21:56 +00:00
def load_from_yaml(file: str) -> dict:
2024-03-18 16:27:40 +00:00
global config
2024-03-24 13:21:57 +00:00
nonebot.logger.debug("Loading config from %s" % file)
2024-03-19 05:16:25 +00:00
if not os.path.exists(file):
2024-03-26 09:14:41 +00:00
nonebot.logger.warning(f"Config file {file} not found, created default config, please modify it and restart")
with open(file, "w", encoding="utf-8") as f:
2024-03-19 05:16:25 +00:00
yaml.dump(BasicConfig().dict(), f, default_flow_style=False)
2024-03-26 09:14:41 +00:00
with open(file, "r", encoding="utf-8") as f:
conf = init_conf(yaml.load(f, Loader=yaml.FullLoader))
2024-03-19 05:16:25 +00:00
config = conf
if conf is None:
2024-03-26 09:14:41 +00:00
nonebot.logger.warning(f"Config file {file} is empty, use default config. please modify it and restart")
2024-03-19 05:16:25 +00:00
conf = BasicConfig().dict()
return conf
def init_conf(conf: dict) -> dict:
if "" not in conf.get("command_start", []):
conf["alconna_use_command_start"] = True
return conf