"""后台管理:提供 Web 管理界面和 REST API,动态修改命令监听配置。""" from aiohttp import web from ..config import ( COMMAND_AT_SENDER, COMMAND_CALLBACK_TIMEOUT, COMMAND_CALLBACK_URL, COMMAND_DENIED_GROUPS, COMMAND_DENIED_USERS, COMMAND_ALLOWED_GROUPS, COMMAND_ALLOWED_USERS, COMMAND_LENGTH_MAX, COMMAND_LENGTH_MIN, COMMAND_LIST_MODE, COMMAND_PREFIX, COMMAND_SCOPE, reload_settings, ) from ..db import get_settings, update_settings from ..response import error, ok # ── API ────────────────────────────────────────────────────── async def api_get_settings(request: web.Request) -> web.Response: """GET /api/settings — 返回全部动态配置。""" settings = await get_settings() return ok(data=settings) async def api_update_settings(request: web.Request) -> web.Response: """PUT /api/settings — 批量更新配置并立即生效。""" try: data = await request.json() except Exception: return error("invalid json") if not isinstance(data, dict): return error("request body must be a json object") # 允许更新的 key 白名单 allowed_keys = { "command_prefix", "command_length_min", "command_length_max", "command_scope", "command_list_mode", "command_allowed_groups", "command_denied_groups", "command_allowed_users", "command_denied_users", "command_at_sender", "command_callback_url", "command_callback_timeout", } filtered = {k: str(v) for k, v in data.items() if k in allowed_keys} if not filtered: return error("no valid settings to update") await update_settings(filtered) reload_settings(filtered) return ok(data=filtered, msg="配置已更新并生效") async def api_reload_settings(request: web.Request) -> web.Response: """POST /api/settings/reload — 从数据库重新加载配置。""" settings = await get_settings() reload_settings(settings) return ok(msg="配置已从数据库重新加载") # ── 管理页面 ───────────────────────────────────────────────── ADMIN_HTML = r"""