浏览代码

Refactor main function to use async/await for improved concurrency. Update bot initialization and polling process to streamline execution and enhance error handling. Adjust logging for better clarity during bot operations.

Carles Sentis 1 周之前
父节点
当前提交
473dbf7820
共有 2 个文件被更改,包括 16 次插入35 次删除
  1. 12 7
      src/bot/core.py
  2. 4 28
      trading_bot.py

+ 12 - 7
src/bot/core.py

@@ -367,10 +367,8 @@ For support or issues, check the logs or contact the administrator.
             await self.market_monitor.start()
             
             logger.info("▶️ Starting PTB application's internal tasks (update processing, job queue).")
-            await self.application.start() # This is non-blocking and starts the Application's processing loop.
-
-            logger.info(f"▶️ Starting polling (drop_pending_updates={Config.TELEGRAM_DROP_PENDING_UPDATES})...")
-            await self.application.run_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES)
+            await self.application.start()
+            await self.application.updater.start_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES)
 
             logger.info("✅ Bot is initialized and polling. Awaiting stop signal or Ctrl+C.")
             # No need for keep_running_future with run_polling
@@ -389,11 +387,18 @@ For support or issues, check the logs or contact the administrator.
                 logger.info("Market monitor stopped.")
 
                 if self.application:
-                    # Stop the application's own processing
-                    if self.application.running: # Check if application was started
+                    # Stop the updater first
+                    if self.application.updater and self.application.updater.running:
+                        logger.info("Stopping PTB updater...")
+                        await self.application.updater.stop()
+                        logger.info("PTB updater stopped.")
+
+                    # Then stop the application's own processing
+                    if self.application.running:
                         logger.info("Stopping PTB application components (handlers, job queue)...")
-                        await self.application.stop() 
+                        await self.application.stop()
                         logger.info("PTB application components stopped.")
+
                     # Finally, shutdown the application
                     logger.info("Shutting down PTB application (bot, persistence, etc.)...")
                     await self.application.shutdown()

+ 4 - 28
trading_bot.py

@@ -14,7 +14,7 @@ from datetime import datetime
 from pathlib import Path
 
 # Bot version
-BOT_VERSION = "2.4.207"
+BOT_VERSION = "2.4.208"
 
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))
@@ -191,33 +191,9 @@ class BotManager:
             print(f"\n💥 Fatal error during bot start: {e}")
             return False
 
-def main():
-    """Main function."""
-    global bot_instance
-    
+async def main():
     bot_manager = BotManager()
-    bot_instance = bot_manager
-    
-    success = False
-    try:
-        success = asyncio.run(bot_manager.start())
-        
-    except KeyboardInterrupt:
-        logging.getLogger(__name__).info("👋 Bot stopped by user (Ctrl+C in main).")
-        print("\n👋 Bot stopped by user.")
-    except Exception as e:
-        logging.getLogger(__name__).critical(f"💥 Unexpected critical error in main: {e}", exc_info=True)
-        print(f"\n💥 Unexpected critical error: {e}")
-    finally:
-        logging.getLogger(__name__).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 hasattr(bot_manager.bot.application, '_running') and bot_manager.bot.application._running:
-                 logging.getLogger(__name__).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.")
+    await bot_manager.start()
 
 if __name__ == "__main__":
-    main() 
+    asyncio.run(main())