ソースを参照

Refactor Telegram bot startup and update handling - Introduce application initialization, manual update polling, and improved shutdown procedures for better stability and error management.

Carles Sentis 6 日 前
コミット
c62f37c1cd
1 ファイル変更43 行追加2 行削除
  1. 43 2
      src/telegram_bot.py

+ 43 - 2
src/telegram_bot.py

@@ -664,6 +664,9 @@ The order has been submitted to Hyperliquid.
             
             logger.info("🚀 Starting Telegram trading bot...")
             
+            # Initialize the application
+            await self.application.initialize()
+            
             # Send startup notification
             await self.send_message(
                 "🤖 <b>Manual Trading Bot Started</b>\n\n"
@@ -674,12 +677,50 @@ The order has been submitted to Hyperliquid.
                 "Use /start for quick actions or /help for all commands."
             )
             
-            # Start the bot with proper asyncio handling
-            await self.application.run_polling()
+            # Start the application
+            await self.application.start()
+            
+            # Start polling for updates manually
+            logger.info("🔄 Starting update polling...")
+            
+            # Get updates in a loop
+            last_update_id = 0
+            while True:
+                try:
+                    # Get updates from Telegram
+                    updates = await self.application.bot.get_updates(
+                        offset=last_update_id + 1,
+                        timeout=30,
+                        allowed_updates=None
+                    )
+                    
+                    # Process each update
+                    for update in updates:
+                        last_update_id = update.update_id
+                        
+                        # Process the update through the application
+                        await self.application.process_update(update)
+                        
+                except Exception as e:
+                    logger.error(f"Error processing updates: {e}")
+                    await asyncio.sleep(5)  # Wait before retrying
+                    
+        except asyncio.CancelledError:
+            logger.info("🛑 Bot polling cancelled")
+            raise
             
         except Exception as e:
             logger.error(f"❌ Error in telegram bot: {e}")
             raise
+            
+        finally:
+            # Clean shutdown
+            try:
+                if self.application:
+                    await self.application.stop()
+                    await self.application.shutdown()
+            except Exception as e:
+                logger.error(f"Error during shutdown: {e}")
 
 
 async def main_async():