Selaa lähdekoodia

Enhance Telegram bot error handling and asyncio integration - Wrap bot startup in try-except for better error logging, and refactor main function to support async context detection.

Carles Sentis 5 päivää sitten
vanhempi
sitoutus
16f8c7e01c
2 muutettua tiedostoa jossa 52 lisäystä ja 23 poistoa
  1. 2 0
      docs/deployment.md
  2. 50 23
      src/telegram_bot.py

+ 2 - 0
docs/deployment.md

@@ -45,6 +45,8 @@ Environment=PATH=/path/to/ManualTrader/venv/bin
 ExecStart=/path/to/ManualTrader/venv/bin/python trading_bot.py
 Restart=always
 RestartSec=30
+StandardOutput=journal
+StandardError=journal
 
 [Install]
 WantedBy=multi-user.target

+ 50 - 23
src/telegram_bot.py

@@ -655,30 +655,35 @@ The order has been submitted to Hyperliquid.
             logger.error("❌ TELEGRAM_CHAT_ID not configured")
             return
         
-        # Create application
-        self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
-        
-        # Set up handlers
-        self.setup_handlers()
-        
-        logger.info("🚀 Starting Telegram trading bot...")
-        
-        # Send startup notification
-        await self.send_message(
-            "🤖 <b>Manual Trading Bot Started</b>\n\n"
-            f"✅ Connected to Hyperliquid {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}\n"
-            f"📊 Default Symbol: {Config.DEFAULT_TRADING_SYMBOL}\n"
-            f"📱 Manual trading ready!\n"
-            f"⏰ Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
-            "Use /start for quick actions or /help for all commands."
-        )
-        
-        # Start the bot
-        await self.application.run_polling()
+        try:
+            # Create application
+            self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
+            
+            # Set up handlers
+            self.setup_handlers()
+            
+            logger.info("🚀 Starting Telegram trading bot...")
+            
+            # Send startup notification
+            await self.send_message(
+                "🤖 <b>Manual Trading Bot Started</b>\n\n"
+                f"✅ Connected to Hyperliquid {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}\n"
+                f"📊 Default Symbol: {Config.DEFAULT_TRADING_SYMBOL}\n"
+                f"📱 Manual trading ready!\n"
+                f"⏰ Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
+                "Use /start for quick actions or /help for all commands."
+            )
+            
+            # Start the bot with proper asyncio handling
+            await self.application.run_polling()
+            
+        except Exception as e:
+            logger.error(f"❌ Error in telegram bot: {e}")
+            raise
 
 
-def main():
-    """Main entry point for the Telegram bot."""
+async def main_async():
+    """Async main entry point for the Telegram bot."""
     try:
         # Validate configuration
         if not Config.validate():
@@ -691,12 +696,34 @@ def main():
         
         # Create and run the bot
         bot = TelegramTradingBot()
-        asyncio.run(bot.run())
+        await bot.run()
         
     except KeyboardInterrupt:
         logger.info("👋 Bot stopped by user")
     except Exception as e:
         logger.error(f"❌ Unexpected error: {e}")
+        raise
+
+
+def main():
+    """Main entry point for the Telegram bot."""
+    try:
+        # Check if we're already in an asyncio context
+        try:
+            loop = asyncio.get_running_loop()
+            # If we get here, we're already in an asyncio context
+            logger.error("❌ Cannot run main() from within an asyncio context. Use main_async() instead.")
+            return
+        except RuntimeError:
+            # No running loop, safe to use asyncio.run()
+            pass
+        
+        # Run the async main function
+        asyncio.run(main_async())
+        
+    except Exception as e:
+        logger.error(f"❌ Failed to start telegram bot: {e}")
+        raise
 
 
 if __name__ == "__main__":