|
@@ -5,6 +5,7 @@ Core Telegram Bot - Handles only bot setup, authentication, and basic messaging.
|
|
|
|
|
|
import asyncio
|
|
|
import logging
|
|
|
+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
|
|
@@ -249,7 +250,7 @@ For support or issues, check the logs or contact the administrator.
|
|
|
await update.message.reply_text(help_text, parse_mode='HTML')
|
|
|
|
|
|
async def run(self):
|
|
|
- """Run the Telegram bot."""
|
|
|
+ """Run the Telegram bot with manual initialization and shutdown."""
|
|
|
if not Config.TELEGRAM_BOT_TOKEN:
|
|
|
logger.error("❌ TELEGRAM_BOT_TOKEN not configured")
|
|
|
return
|
|
@@ -258,51 +259,68 @@ For support or issues, check the logs or contact the administrator.
|
|
|
logger.error("❌ TELEGRAM_CHAT_ID not configured")
|
|
|
return
|
|
|
|
|
|
+ logger.info(f"🔧 Using python-telegram-bot version: {telegram.__version__}")
|
|
|
+
|
|
|
+ # Create application
|
|
|
+ self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
|
|
|
+
|
|
|
+ # Connect notification manager to the bot application
|
|
|
+ self.notification_manager.set_bot_application(self.application)
|
|
|
+
|
|
|
+ # Set up handlers
|
|
|
+ self.setup_handlers()
|
|
|
+
|
|
|
try:
|
|
|
- # Create application
|
|
|
- self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
|
|
|
-
|
|
|
- # Connect notification manager to the bot application
|
|
|
- self.notification_manager.set_bot_application(self.application)
|
|
|
-
|
|
|
- # Set up handlers
|
|
|
- self.setup_handlers()
|
|
|
+ logger.info("🚀 Initializing bot application...")
|
|
|
+ await self.application.initialize()
|
|
|
|
|
|
- logger.info("🚀 Starting Telegram trading bot...")
|
|
|
+ logger.info(f"🚀 Starting Telegram trading bot v{self.version}...")
|
|
|
|
|
|
# Send startup notification
|
|
|
await self.send_message(
|
|
|
- f"🤖 <b>Manual Trading Bot v{self.version} Started</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</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."
|
|
|
)
|
|
|
|
|
|
# Start subsystems
|
|
|
await self.market_monitor.start()
|
|
|
|
|
|
- # Start polling for updates using the modern approach
|
|
|
- logger.info("🔄 Starting bot polling...")
|
|
|
- await self.application.run_polling(
|
|
|
- drop_pending_updates=True
|
|
|
- # By default, run_polling handles SIGINT, SIGTERM, SIGABRT.
|
|
|
- # No need to specify stop_signals=None if we want this default behavior.
|
|
|
- )
|
|
|
+ logger.info("▶️ Starting PTB application (handlers, dispatcher, polling...)...")
|
|
|
+ await self.application.start()
|
|
|
+
|
|
|
+ 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.")
|
|
|
|
|
|
+ except (KeyboardInterrupt, SystemExit):
|
|
|
+ logger.info("🛑 Bot run interrupted by user/system. Initiating shutdown...")
|
|
|
except asyncio.CancelledError:
|
|
|
- logger.info("🛑 Bot polling cancelled")
|
|
|
- raise
|
|
|
-
|
|
|
+ logger.info("🛑 Bot run task cancelled. Initiating shutdown...")
|
|
|
except Exception as e:
|
|
|
- logger.error(f"❌ Error in telegram bot: {e}")
|
|
|
- raise
|
|
|
-
|
|
|
+ logger.error(f"❌ Unhandled error in bot run loop: {e}", exc_info=True)
|
|
|
finally:
|
|
|
- # Clean shutdown
|
|
|
+ logger.info("🔌 Starting graceful shutdown sequence in TelegramTradingBot.run...")
|
|
|
try:
|
|
|
+ logger.info("Stopping market monitor...")
|
|
|
await self.market_monitor.stop()
|
|
|
+ logger.info("Market monitor stopped.")
|
|
|
+
|
|
|
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("Shutting down PTB application...")
|
|
|
await self.application.shutdown()
|
|
|
+ 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 complete.")
|
|
|
+
|
|
|
except Exception as e:
|
|
|
- logger.error(f"Error during shutdown: {e}")
|
|
|
+ logger.error(f"💥 Error during shutdown sequence in TelegramTradingBot.run: {e}", exc_info=True)
|