Quellcode durchsuchen

Refactor trading bot shutdown handling and error logging - Removed unused signal handling for graceful shutdown and improved error logging in the BotManager class. Enhanced the main function to provide clearer logging during shutdown and error scenarios, ensuring better traceability and user feedback. Updated comments for clarity and consistency.

Carles Sentis vor 5 Tagen
Ursprung
Commit
679f3b6d0f
2 geänderte Dateien mit 29 neuen und 37 gelöschten Zeilen
  1. 3 2
      src/bot/core.py
  2. 26 35
      trading_bot.py

+ 3 - 2
src/bot/core.py

@@ -285,8 +285,9 @@ For support or issues, check the logs or contact the administrator.
             # Start polling for updates using the modern approach
             logger.info("🔄 Starting bot polling...")
             await self.application.run_polling(
-                drop_pending_updates=True,
-                stop_signals=None  # Let the main process handle signals
+                drop_pending_updates=True
+                # By default, run_polling handles SIGINT, SIGTERM, SIGABRT.
+                # No need to specify stop_signals=None if we want this default behavior.
             )
                     
         except asyncio.CancelledError:

+ 26 - 35
trading_bot.py

@@ -10,7 +10,6 @@ import sys
 import os
 import asyncio
 import logging
-import signal
 from datetime import datetime
 from pathlib import Path
 
@@ -31,7 +30,6 @@ except ImportError as e:
 
 # Global variables for graceful shutdown
 bot_instance = None
-is_shutting_down = False
 
 class BotManager:
     """Manages the trading bot with simple startup and shutdown."""
@@ -143,8 +141,6 @@ class BotManager:
     
     async def run_bot(self):
         """Run the main bot."""
-        global is_shutting_down
-        
         try:
             self.logger.info("🤖 Creating TelegramTradingBot instance...")
             self.bot = TelegramTradingBot()
@@ -161,15 +157,18 @@ class BotManager:
             await self.bot.run()
             
         except KeyboardInterrupt:
-            self.logger.info("👋 Bot stopped by user (Ctrl+C)")
-            is_shutting_down = True
+            self.logger.info("👋 Bot stopped by user (Ctrl+C in BotManager.run_bot)")
             
         except Exception as e:
-            self.logger.error(f"❌ Bot error: {e}")
-            raise
+            self.logger.error(f"❌ Bot error in BotManager.run_bot: {e}", exc_info=True)
+            # Ensure cleanup is attempted
+            if self.bot and self.bot.application and self.bot.application.is_running:
+                 logger.info("Attempting to stop application due to error in run_bot...")
+                 await self.bot.application.stop()
+            raise # Re-raise the exception to be caught by main()
     
     async def start(self):
-        """Main entry point."""
+        """Main entry point for BotManager."""
         try:
             self.print_banner()
             
@@ -185,45 +184,37 @@ class BotManager:
             return True
             
         except Exception as e:
-            self.logger.error(f"❌ Fatal error in bot manager: {e}")
-            print(f"\n💥 Fatal error: {e}")
+            self.logger.error(f"❌ Fatal error in BotManager.start: {e}", exc_info=True)
+            print(f"\n💥 Fatal error during bot start: {e}")
             return False
 
-def signal_handler(signum, frame):
-    """Handle shutdown signals gracefully."""
-    global is_shutting_down, bot_instance
-    
-    print("\n🛑 Shutdown signal received...")
-    is_shutting_down = True
-
 def main():
     """Main function."""
     global bot_instance
     
-    # Set up signal handlers for graceful shutdown
-    signal.signal(signal.SIGINT, signal_handler)
-    signal.signal(signal.SIGTERM, signal_handler)
+    bot_manager = BotManager()
+    bot_instance = bot_manager
     
+    success = False
     try:
-        bot_manager = BotManager()
-        bot_instance = bot_manager
-        
-        # Run the bot
         success = asyncio.run(bot_manager.start())
         
-        if success:
-            print("\n✅ Bot session completed successfully")
-        else:
-            print("\n❌ Bot session failed")
-            sys.exit(1)
-            
     except KeyboardInterrupt:
-        print("\n👋 Bot stopped by user")
+        logger.info("👋 Bot stopped by user (Ctrl+C in main).")
+        print("\n👋 Bot stopped by user.")
     except Exception as e:
-        print(f"\n💥 Unexpected error: {e}")
-        sys.exit(1)
+        logger.critical(f"💥 Unexpected critical error in main: {e}", exc_info=True)
+        print(f"\n💥 Unexpected critical error: {e}")
     finally:
-        print("📊 Your trading statistics have been saved")
+        logger.info("BotManager main function finished.")
+        print("📊 Your trading statistics should have been saved by the bot's internal shutdown.")
+
+        if bot_manager and bot_manager.bot and bot_manager.bot.application:
+             if bot_manager.bot.application.is_running:
+                 logger.warning("Application was still marked as running in main finally block. Attempting forced synchronous stop. This may not work if loop is closed.")
+        
+        if not success:
+            print("\n❌ Bot session ended with errors.")
 
 if __name__ == "__main__":
     main()