瀏覽代碼

Refactor bot run method to improve signal handling and streamline shutdown process. Added signal support for graceful termination and enhanced logging for better operational clarity during bot initialization and shutdown.

Carles Sentis 1 周之前
父節點
當前提交
90544498cb
共有 2 個文件被更改,包括 31 次插入44 次删除
  1. 30 43
      src/bot/core.py
  2. 1 1
      trading_bot.py

+ 30 - 43
src/bot/core.py

@@ -9,6 +9,7 @@ import telegram # Import telegram to check version
 from datetime import datetime
 from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
 from telegram.ext import Application, ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
+import signal
 
 from src.config.config import Config
 from src.trading.trading_engine import TradingEngine
@@ -330,55 +331,41 @@ For support or issues, check the logs or contact the administrator.
             logger.error(f"Error sending help message in /help: {e}")
     
     async def run(self):
-        """Run the Telegram bot with manual initialization and shutdown (v20.x style)."""
-        if not Config.TELEGRAM_BOT_TOKEN:
-            logger.error("❌ TELEGRAM_BOT_TOKEN not configured")
-            return
+        """Run the bot."""
+        logger.info("🚀 Initializing bot application (v20.x style)...")
+        await self.application.initialize()
         
-        if not Config.TELEGRAM_CHAT_ID:
-            logger.error("❌ TELEGRAM_CHAT_ID not configured")
-            return
+        logger.info(f"🚀 Starting Telegram trading bot v{self.version} (v20.x style)...")
         
-        logger.info(f"🔧 Using python-telegram-bot version: {telegram.__version__} (Running in v20.x style)")
-
-        # Create application
-        self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
+        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"
+            "Use /start for quick actions or /help for all commands."
+        )
         
-        # Connect notification manager to the bot application
-        self.notification_manager.set_bot_application(self.application)
+        await self.market_monitor.start()
         
-        # Set up handlers
-        self.setup_handlers()
+        logger.info("▶️ Starting PTB application's internal tasks (update processing, job queue).")
+        await self.application.start()
+        await self.application.updater.start_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES)
 
-        try:
-            logger.info("🚀 Initializing bot application (v20.x style)...")
-            await self.application.initialize()
-            
-            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"
-                "Use /start for quick actions or /help for all commands."
-            )
-            
-            await self.market_monitor.start()
-            
-            logger.info("▶️ Starting PTB application's internal tasks (update processing, job queue).")
-            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
+        logger.info("✅ Bot is initialized and polling. Awaiting stop signal or Ctrl+C.")
+        
+        # Create a future to keep the bot running
+        stop_future = asyncio.Future()
         
-        except (KeyboardInterrupt, SystemExit) as e: # Added SystemExit here
-            logger.info(f"🛑 Bot run interrupted by {type(e).__name__}. Initiating shutdown (v20.x style)...")
+        # Set up signal handlers
+        loop = asyncio.get_running_loop()
+        for sig in (signal.SIGINT, signal.SIGTERM):
+            loop.add_signal_handler(sig, lambda: stop_future.set_result(None))
+        
+        try:
+            # Keep the bot running until stop_future is set
+            await stop_future
         except asyncio.CancelledError:
             logger.info("🛑 Bot run task cancelled. Initiating shutdown (v20.x style)...")
-        except Exception as e:
-            logger.error(f"❌ Unhandled error in bot run loop (v20.x style): {e}", exc_info=True)
         finally:
             logger.info("🔌 Starting graceful shutdown sequence in TelegramTradingBot.run (v20.x style)...")
             try:
@@ -405,8 +392,8 @@ For support or issues, check the logs or contact the administrator.
                     logger.info("PTB application shut down.")
                 else:
                     logger.warning("Application object was None during shutdown in TelegramTradingBot.run.")
-                
+
                 logger.info("✅ Graceful shutdown sequence in TelegramTradingBot.run (v20.x style) complete.")
-                
+
             except Exception as e:
                 logger.error(f"💥 Error during shutdown sequence in TelegramTradingBot.run (v20.x style): {e}", exc_info=True) 

+ 1 - 1
trading_bot.py

@@ -14,7 +14,7 @@ from datetime import datetime
 from pathlib import Path
 
 # Bot version
-BOT_VERSION = "2.4.208"
+BOT_VERSION = "2.4.209"
 
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))