fix: unable to shut down bot gracefully when matrix is configured

This commit is contained in:
草师傅 2025-08-28 13:47:54 +08:00
parent 0f71c0e74d
commit e2dcdce9ed
2 changed files with 47 additions and 21 deletions

20
main.py
View file

@ -2,6 +2,7 @@ import asyncio
import logging
import signal
import sys
from asyncio import TaskGroup
import config
from adapters.tg import TelegramAdapter
@ -12,27 +13,20 @@ async def main():
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
tasks = []
cfg = config.Config()
# Initialize and start Telegram adapter
if config.Config().get_config_value('start_telegram_bot', True):
if cfg.get_config_value('start_telegram_bot', True):
tg_adapter = TelegramAdapter()
tasks.append(tg_adapter.start())
if config.Config().get_config_value('also_start_matrix_bot', False):
if cfg.get_config_value('also_start_matrix_bot', False):
import adapters.matrix as matrix_bot
# Initialize and start Matrix bot if configured
tasks.append(matrix_bot.main())
if tasks:
# Setup signal handler for graceful shutdown
def signal_handler(signum, frame):
logging.info("Received shutdown signal, cancelling all tasks...")
for task in tasks:
task.cancel()
# Register signal handlers
for sig in (signal.SIGTERM, signal.SIGINT):
asyncio.get_event_loop().add_signal_handler(sig, signal_handler, sig, None)
try:
await asyncio.gather(*tasks, return_exceptions=True)
async with TaskGroup() as group:
for task in tasks:
group.create_task(task)
except asyncio.CancelledError:
logging.info("All tasks cancelled successfully")
else: