From d3b4ca30dab45c87353b559ffc4fd4b02c529d9b Mon Sep 17 00:00:00 2001 From: tcmofashi Date: Thu, 27 Mar 2025 14:01:20 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot.py | 2 ++ src/main.py | 9 +++++---- src/plugins/message/api.py | 9 ++++++--- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/bot.py b/bot.py index bd28e6cee..35473e508 100644 --- a/bot.py +++ b/bot.py @@ -9,6 +9,7 @@ import platform from dotenv import load_dotenv from src.common.logger import get_module_logger from src.main import MainSystem +from src.plugins.message import global_api logger = get_module_logger("main_bot") @@ -252,6 +253,7 @@ if __name__ == "__main__": loop.run_until_complete(main_system.initialize()) loop.run_until_complete(main_system.schedule_tasks()) except KeyboardInterrupt: + # loop.run_until_complete(global_api.stop()) logger.warning("收到中断信号,正在优雅关闭...") loop.run_until_complete(graceful_shutdown()) finally: diff --git a/src/main.py b/src/main.py index fa8100d85..d84d6cf1b 100644 --- a/src/main.py +++ b/src/main.py @@ -33,9 +33,6 @@ class MainSystem: """初始化系统组件""" logger.debug(f"正在唤醒{global_config.BOT_NICKNAME}......") - # 启动API服务器(改为异步启动) - self.api_task = asyncio.create_task(self.app.run()) - # 其他初始化任务 await asyncio.gather( self._init_components(), # 将原有的初始化代码移到这个新方法中 @@ -91,6 +88,7 @@ class MainSystem: self.generate_schedule_task(), self.remove_recalled_message_task(), emoji_manager.start_periodic_check(interval_MINS=global_config.EMOJI_CHECK_INTERVAL), + self.app.run(), ] await asyncio.gather(*tasks) @@ -143,7 +141,10 @@ class MainSystem: async def main(): """主函数""" system = MainSystem() - await asyncio.gather(system.initialize(), system.schedule_tasks(), system.api_task) + await asyncio.gather( + system.initialize(), + system.schedule_tasks(), + ) # await system.initialize() # await system.schedule_tasks() diff --git a/src/plugins/message/api.py b/src/plugins/message/api.py index 355817efb..03b6cee4f 100644 --- a/src/plugins/message/api.py +++ b/src/plugins/message/api.py @@ -49,8 +49,11 @@ class BaseMessageAPI: """异步方式运行服务器""" config = uvicorn.Config(self.app, host=self.host, port=self.port, loop="asyncio") self.server = uvicorn.Server(config) - - await self.server.serve() + try: + await self.server.serve() + except KeyboardInterrupt as e: + await self.stop() + raise KeyboardInterrupt from e async def start_server(self): """启动服务器的异步方法""" @@ -83,4 +86,4 @@ class BaseMessageAPI: loop.close() -global_api = BaseMessageAPI(host=os.environ["HOST"], port=os.environ["PORT"]) +global_api = BaseMessageAPI(host=os.environ["HOST"], port=int(os.environ["PORT"]))