소스 검색

Refactor Telegram bot logging and startup sequence - Removed unnecessary logging for the python-telegram-bot version and improved the bot's initialization process with clearer comments. Enhanced shutdown handling to ensure proper resolution of tasks during termination, contributing to better reliability and user feedback.

Carles Sentis 5 일 전
부모
커밋
53ab900dfa
1개의 변경된 파일19개의 추가작업 그리고 10개의 파일을 삭제
  1. 19 10
      src/bot/core.py

+ 19 - 10
src/bot/core.py

@@ -5,7 +5,7 @@ Core Telegram Bot - Handles only bot setup, authentication, and basic messaging.
 
 
 import asyncio
 import asyncio
 import logging
 import logging
-import telegram # Import telegram to check version
+# import telegram # Import telegram to check version (NO LONGER NEEDED)
 from datetime import datetime
 from datetime import datetime
 from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
 from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
 from telegram.ext import Application, ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
 from telegram.ext import Application, ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
@@ -259,7 +259,7 @@ For support or issues, check the logs or contact the administrator.
             logger.error("❌ TELEGRAM_CHAT_ID not configured")
             logger.error("❌ TELEGRAM_CHAT_ID not configured")
             return
             return
         
         
-        logger.info(f"🔧 Using python-telegram-bot version: {telegram.__version__}")
+        # logger.info(f"🔧 Using python-telegram-bot version: {telegram.__version__}") # NO LONGER NEEDED
 
 
         # Create application
         # Create application
         self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
         self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
@@ -270,6 +270,8 @@ For support or issues, check the logs or contact the administrator.
         # Set up handlers
         # Set up handlers
         self.setup_handlers()
         self.setup_handlers()
 
 
+        keep_running_future = asyncio.Future() # Future to keep the bot alive
+
         try:
         try:
             logger.info("🚀 Initializing bot application...")
             logger.info("🚀 Initializing bot application...")
             await self.application.initialize()
             await self.application.initialize()
@@ -289,18 +291,26 @@ For support or issues, check the logs or contact the administrator.
             await self.market_monitor.start()
             await self.market_monitor.start()
             
             
             logger.info("▶️ Starting PTB application (handlers, dispatcher, polling...)...")
             logger.info("▶️ Starting PTB application (handlers, dispatcher, polling...)...")
-            await self.application.start()
+            await self.application.start() # This starts polling and other processes
+            
+            # logger.info(f"🔍 Type of self.application.running after start: {type(self.application.running)}") # NO LONGER NEEDED
+            logger.info("Bot is now running. Awaiting external stop signal (e.g., Ctrl+C)...")
             
             
-            logger.info("Bot is now running. Waiting for application to stop (e.g., via signal or error)...")
-            await self.application.running.wait() # Wait until Application.stop() is called
-            logger.info("PTB application.running event cleared, application has stopped/is stopping.")
+            # Wait indefinitely until an exception (like KeyboardInterrupt) or task cancellation
+            await keep_running_future
                     
                     
         except (KeyboardInterrupt, SystemExit):
         except (KeyboardInterrupt, SystemExit):
             logger.info("🛑 Bot run interrupted by user/system. Initiating shutdown...")
             logger.info("🛑 Bot run interrupted by user/system. Initiating shutdown...")
+            if not keep_running_future.done():
+                keep_running_future.set_exception(KeyboardInterrupt()) # Ensure future is resolved
         except asyncio.CancelledError:
         except asyncio.CancelledError:
             logger.info("🛑 Bot run task cancelled. Initiating shutdown...")
             logger.info("🛑 Bot run task cancelled. Initiating shutdown...")
+            if not keep_running_future.done():
+                keep_running_future.cancel()
         except Exception as e:
         except Exception as e:
             logger.error(f"❌ Unhandled error in bot run loop: {e}", exc_info=True)
             logger.error(f"❌ Unhandled error in bot run loop: {e}", exc_info=True)
+            if not keep_running_future.done():
+                keep_running_future.set_exception(e)
         finally:
         finally:
             logger.info("🔌 Starting graceful shutdown sequence in TelegramTradingBot.run...")
             logger.info("🔌 Starting graceful shutdown sequence in TelegramTradingBot.run...")
             try:
             try:
@@ -309,10 +319,9 @@ For support or issues, check the logs or contact the administrator.
                 logger.info("Market monitor stopped.")
                 logger.info("Market monitor stopped.")
 
 
                 if self.application:
                 if self.application:
-                    if self.application.running.is_set():
-                        logger.info("Stopping PTB application (as it's still marked as running)...")
-                        await self.application.stop() # This should clear the application.running event
-                        logger.info("PTB application stopped.")
+                    logger.info("Attempting to stop PTB application...")
+                    await self.application.stop() 
+                    logger.info("PTB application stop attempted.")
                     
                     
                     logger.info("Shutting down PTB application...")
                     logger.info("Shutting down PTB application...")
                     await self.application.shutdown()
                     await self.application.shutdown()