From 142afde3361106c740f2f8c512c5de1d2254c43b Mon Sep 17 00:00:00 2001 From: HibiKier <775757368@qq.com> Date: Tue, 23 Dec 2025 16:38:08 +0800 Subject: [PATCH] fix(user_console): ensure uid returns a valid value by defaulting to 1 --- zhenxun/models/user_console.py | 2 +- zhenxun/services/__init__.py | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/zhenxun/models/user_console.py b/zhenxun/models/user_console.py index 0f500274..aa527ef5 100644 --- a/zhenxun/models/user_console.py +++ b/zhenxun/models/user_console.py @@ -73,7 +73,7 @@ class UserConsole(Model): uid = data[0] if data else 0 uid = uid + 1 await CacheRoot.set(CacheType.TEMP, "USER_CONSOLE_UID", uid) - return uid + return uid or 1 @classmethod async def add_gold( diff --git a/zhenxun/services/__init__.py b/zhenxun/services/__init__.py index ec0ff65d..b02a5e39 100644 --- a/zhenxun/services/__init__.py +++ b/zhenxun/services/__init__.py @@ -9,6 +9,9 @@ Zhenxun Bot - 核心服务模块 - 定时任务调度器 (scheduler): 提供持久化的、可管理的定时任务服务。 """ +import asyncio + +import nonebot from nonebot import require require("nonebot_plugin_apscheduler") @@ -88,3 +91,26 @@ __all__ = [ "set_global_default_model_name", "with_db_timeout", ] + + +async def cancel_pending_tasks(): + """在关闭前尽量取消仍在运行的协程,避免关闭后继续访问数据库连接池。""" + loop = asyncio.get_running_loop() + current = asyncio.current_task(loop=loop) + pending = [ + task + for task in asyncio.all_tasks(loop) + if task is not current and not task.done() + ] + if not pending: + return + + for task in pending: + task.cancel() + + await asyncio.gather(*pending, return_exceptions=True) + + +driver = nonebot.get_driver() +# 先取消可能在跑的任务,再断开数据库,避免 pool closing 异常 +driver.on_shutdown(cancel_pending_tasks)