Browse Source

Enhance Telegram bot's polling and shutdown processes - Improved the bot's updater management by ensuring it starts and stops correctly, with detailed logging for better traceability. Updated exception handling during shutdown to provide clearer feedback on interruptions. Refined the application shutdown sequence to ensure all components are properly stopped, contributing to a more reliable and user-friendly experience.

Carles Sentis 4 days ago
parent
commit
a9a57e6ea4
1 changed files with 40 additions and 17 deletions
  1. 40 17
      src/bot/core.py

+ 40 - 17
src/bot/core.py

@@ -305,27 +305,41 @@ For support or issues, check the logs or contact the administrator.
             logger.info(f"🚀 Starting Telegram trading bot v{self.version} (v20.x style)...")
             
             await self.send_message(
-                f"🤖 <b>Manual Trading Bot v{self.version} Started (v20.x style)</b>\\n\\n"
-                f"✅ Connected to Hyperliquid {{'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}}\\n"
-                f"📊 Default Symbol: {Config.DEFAULT_TRADING_TOKEN}\\n"
-                f"🔄 All systems ready!\\n\\n"
+                f"🤖 <b>Manual Trading Bot v{self.version} Started (v20.x style)</b>\\\\n\\\\n"
+                f"✅ Connected to Hyperliquid {{'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}}\\\\n"
+                f"📊 Default Symbol: {Config.DEFAULT_TRADING_TOKEN}\\\\n"
+                f"🔄 All systems ready!\\\\n\\\\n"
                 "Use /start for quick actions or /help for all commands."
             )
             
             await self.market_monitor.start()
             
-            logger.info("▶️ Starting PTB application (handlers, dispatcher, polling...) (v20.x style)...")
-            await self.application.start()
-            
-            logger.info("Bot is now running. Awaiting external stop signal (e.g., Ctrl+C) (v20.x style)...")
-            await self.application.run_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES) 
-            
+            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.
+
+            if self.application.updater:
+                logger.info(f"▶️ Activating PTB updater to fetch updates (drop_pending_updates={Config.TELEGRAM_DROP_PENDING_UPDATES}).")
+                # updater.start_polling is an async method that starts fetching updates and populates the application's update_queue.
+                # It needs to run as a background task, managed by the existing event loop.
+                # We don't await it directly here if we want other code (like keep_running_future) to proceed.
+                # However, for graceful shutdown, we'll manage its lifecycle.
+                # For this structure, we expect the main script to keep the event loop running.
+                await self.application.updater.start_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES)
+            else:
+                logger.error("❌ Critical: Application updater is not initialized. Bot cannot receive Telegram updates.")
+                # If updater is critical, we might want to stop here or raise an error.
+                # For now, we'll let keep_running_future potentially handle the stop.
+                if not keep_running_future.done():
+                    keep_running_future.set_exception(RuntimeError("Updater not available"))
+
+
+            logger.info("✅ Bot is initialized and updater is polling. Awaiting stop signal via keep_running_future or Ctrl+C.")
             await keep_running_future 
                     
-        except (KeyboardInterrupt, SystemExit):
-            logger.info("🛑 Bot run interrupted by user/system. Initiating shutdown (v20.x style)...")
+        except (KeyboardInterrupt, SystemExit) as e: # Added SystemExit here
+            logger.info(f"🛑 Bot run interrupted by {type(e).__name__}. Initiating shutdown (v20.x style)...")
             if not keep_running_future.done():
-                keep_running_future.set_exception(KeyboardInterrupt())
+                keep_running_future.set_exception(e if isinstance(e, SystemExit) else KeyboardInterrupt())
         except asyncio.CancelledError:
             logger.info("🛑 Bot run task cancelled. Initiating shutdown (v20.x style)...")
             if not keep_running_future.done():
@@ -342,11 +356,20 @@ For support or issues, check the logs or contact the administrator.
                 logger.info("Market monitor stopped.")
 
                 if self.application:
-                    logger.info("Attempting to stop PTB application (v20.x style)...")
-                    await self.application.stop() 
-                    logger.info("PTB application stop attempted.")
+                    # Stop the updater first if it's running
+                    if self.application.updater and self.application.updater.running:
+                        logger.info("Stopping PTB updater polling...")
+                        await self.application.updater.stop()
+                        logger.info("PTB updater polling stopped.")
+                    
+                    # Then stop the application's own processing
+                    if self.application.running: # Check if application was started
+                        logger.info("Stopping PTB application components (handlers, job queue)...")
+                        await self.application.stop() 
+                        logger.info("PTB application components stopped.")
                     
-                    logger.info("Shutting down PTB application (v20.x style)...")
+                    # Finally, shutdown the application
+                    logger.info("Shutting down PTB application (bot, persistence, etc.)...")
                     await self.application.shutdown()
                     logger.info("PTB application shut down.")
                 else: