diff --git a/adapters/matrix.py b/adapters/matrix.py index f4c260e..f536a85 100644 --- a/adapters/matrix.py +++ b/adapters/matrix.py @@ -2,6 +2,7 @@ import asyncio import json import logging import os +import sys from nio import AsyncClient, MatrixRoom, RoomMessageText from nio.events.room_events import RoomMessageText @@ -95,7 +96,6 @@ class MatrixAdapter: async def stop(self): """Stop the bot.""" logger.info("Stopping Matrix bot...") - await self.client.logout() await self.client.close() @@ -144,10 +144,13 @@ async def main(): await bot.start() except KeyboardInterrupt: logger.info("Bot interrupted by user") + # TODO: fix unable to gracefully shutdown issue + await bot.stop() + sys.exit(0) except Exception as e: logger.error(f"Bot error: {e}") - finally: await bot.stop() + sys.exit(1) if __name__ == "__main__": diff --git a/main.py b/main.py index 3531f7c..77f87b4 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,6 @@ import asyncio import logging +import signal import sys import config @@ -20,7 +21,20 @@ async def main(): # Initialize and start Matrix bot if configured tasks.append(matrix_bot.main()) if tasks: - await asyncio.gather(*tasks, return_exceptions=True) + # 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) + except asyncio.CancelledError: + logging.info("All tasks cancelled successfully") else: logging.error("No bot is configured to start. Please check your configuration.")