diff --git a/src/derp/cli.py b/src/derp/cli.py index 2474e4e..793dae1 100644 --- a/src/derp/cli.py +++ b/src/derp/cli.py @@ -49,13 +49,27 @@ def build_parser() -> argparse.ArgumentParser: def _run(bot: Bot) -> None: - """Run the bot event loop.""" + """Run the bot event loop with graceful SIGTERM handling.""" + import signal + + async def _start_with_signal(): + loop = asyncio.get_running_loop() + loop.add_signal_handler(signal.SIGTERM, _shutdown, bot) + await bot.start() + try: - asyncio.run(bot.start()) + asyncio.run(_start_with_signal()) except KeyboardInterrupt: logging.getLogger("derp").info("interrupted, shutting down") +def _shutdown(bot: Bot) -> None: + """Signal handler: stop the bot loop so cProfile can flush.""" + logging.getLogger("derp").info("SIGTERM received, shutting down") + bot._running = False + asyncio.get_running_loop().create_task(bot.conn.close()) + + def main(argv: list[str] | None = None) -> int: """Main entry point.""" parser = build_parser()