|
@@ -10,7 +10,6 @@ import sys
|
|
|
import os
|
|
|
import asyncio
|
|
|
import logging
|
|
|
-import signal
|
|
|
from datetime import datetime
|
|
|
from pathlib import Path
|
|
|
|
|
@@ -31,7 +30,6 @@ except ImportError as e:
|
|
|
|
|
|
# Global variables for graceful shutdown
|
|
|
bot_instance = None
|
|
|
-is_shutting_down = False
|
|
|
|
|
|
class BotManager:
|
|
|
"""Manages the trading bot with simple startup and shutdown."""
|
|
@@ -143,8 +141,6 @@ class BotManager:
|
|
|
|
|
|
async def run_bot(self):
|
|
|
"""Run the main bot."""
|
|
|
- global is_shutting_down
|
|
|
-
|
|
|
try:
|
|
|
self.logger.info("🤖 Creating TelegramTradingBot instance...")
|
|
|
self.bot = TelegramTradingBot()
|
|
@@ -161,15 +157,18 @@ class BotManager:
|
|
|
await self.bot.run()
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
- self.logger.info("👋 Bot stopped by user (Ctrl+C)")
|
|
|
- is_shutting_down = True
|
|
|
+ self.logger.info("👋 Bot stopped by user (Ctrl+C in BotManager.run_bot)")
|
|
|
|
|
|
except Exception as e:
|
|
|
- self.logger.error(f"❌ Bot error: {e}")
|
|
|
- raise
|
|
|
+ self.logger.error(f"❌ Bot error in BotManager.run_bot: {e}", exc_info=True)
|
|
|
+ # Ensure cleanup is attempted
|
|
|
+ if self.bot and self.bot.application and self.bot.application.is_running:
|
|
|
+ logger.info("Attempting to stop application due to error in run_bot...")
|
|
|
+ await self.bot.application.stop()
|
|
|
+ raise # Re-raise the exception to be caught by main()
|
|
|
|
|
|
async def start(self):
|
|
|
- """Main entry point."""
|
|
|
+ """Main entry point for BotManager."""
|
|
|
try:
|
|
|
self.print_banner()
|
|
|
|
|
@@ -185,45 +184,37 @@ class BotManager:
|
|
|
return True
|
|
|
|
|
|
except Exception as e:
|
|
|
- self.logger.error(f"❌ Fatal error in bot manager: {e}")
|
|
|
- print(f"\n💥 Fatal error: {e}")
|
|
|
+ self.logger.error(f"❌ Fatal error in BotManager.start: {e}", exc_info=True)
|
|
|
+ print(f"\n💥 Fatal error during bot start: {e}")
|
|
|
return False
|
|
|
|
|
|
-def signal_handler(signum, frame):
|
|
|
- """Handle shutdown signals gracefully."""
|
|
|
- global is_shutting_down, bot_instance
|
|
|
-
|
|
|
- print("\n🛑 Shutdown signal received...")
|
|
|
- is_shutting_down = True
|
|
|
-
|
|
|
def main():
|
|
|
"""Main function."""
|
|
|
global bot_instance
|
|
|
|
|
|
- # Set up signal handlers for graceful shutdown
|
|
|
- signal.signal(signal.SIGINT, signal_handler)
|
|
|
- signal.signal(signal.SIGTERM, signal_handler)
|
|
|
+ bot_manager = BotManager()
|
|
|
+ bot_instance = bot_manager
|
|
|
|
|
|
+ success = False
|
|
|
try:
|
|
|
- bot_manager = BotManager()
|
|
|
- bot_instance = bot_manager
|
|
|
-
|
|
|
- # Run the bot
|
|
|
success = asyncio.run(bot_manager.start())
|
|
|
|
|
|
- if success:
|
|
|
- print("\n✅ Bot session completed successfully")
|
|
|
- else:
|
|
|
- print("\n❌ Bot session failed")
|
|
|
- sys.exit(1)
|
|
|
-
|
|
|
except KeyboardInterrupt:
|
|
|
- print("\n👋 Bot stopped by user")
|
|
|
+ logger.info("👋 Bot stopped by user (Ctrl+C in main).")
|
|
|
+ print("\n👋 Bot stopped by user.")
|
|
|
except Exception as e:
|
|
|
- print(f"\n💥 Unexpected error: {e}")
|
|
|
- sys.exit(1)
|
|
|
+ logger.critical(f"💥 Unexpected critical error in main: {e}", exc_info=True)
|
|
|
+ print(f"\n💥 Unexpected critical error: {e}")
|
|
|
finally:
|
|
|
- print("📊 Your trading statistics have been saved")
|
|
|
+ logger.info("BotManager main function finished.")
|
|
|
+ print("📊 Your trading statistics should have been saved by the bot's internal shutdown.")
|
|
|
+
|
|
|
+ if bot_manager and bot_manager.bot and bot_manager.bot.application:
|
|
|
+ if bot_manager.bot.application.is_running:
|
|
|
+ logger.warning("Application was still marked as running in main finally block. Attempting forced synchronous stop. This may not work if loop is closed.")
|
|
|
+
|
|
|
+ if not success:
|
|
|
+ print("\n❌ Bot session ended with errors.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
main()
|