Browse Source

Implement keyboard command handling in TelegramTradingBot

- Added a new method to handle commands sent via the main keyboard, mapping keyboard inputs to their respective command functions.
- Enhanced logging for received commands and unknown command notifications.
- Updated the trading engine to set the initial balance asynchronously, improving performance during initialization.
Carles Sentis 2 days ago
parent
commit
8f2df4becc
3 changed files with 49 additions and 3 deletions
  1. 47 1
      src/bot/core.py
  2. 1 1
      src/trading/trading_engine.py
  3. 1 1
      trading_bot.py

+ 47 - 1
src/bot/core.py

@@ -162,9 +162,55 @@ class TelegramTradingBot:
         self.application.add_handler(CallbackQueryHandler(self.trading_commands.button_callback))
         self.application.add_handler(MessageHandler(
             filters.Regex(r'^(LONG|SHORT|EXIT|SL|TP|LEVERAGE|BALANCE|POSITIONS|ORDERS|STATS|MARKET|PERFORMANCE|DAILY|WEEKLY|MONTHLY|RISK|ALARM|MONITORING|LOGS|DEBUG|VERSION|COMMANDS|KEYBOARD|COO)'),
-            self.trading_commands.handle_keyboard_command
+            self.handle_keyboard_command
         ))
         
+    async def handle_keyboard_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+        """Handles commands sent via the main keyboard."""
+        command_text = update.message.text.upper()
+        logger.info(f"Keyboard command received: {command_text}")
+
+        # Map keyboard text to the appropriate command method
+        command_map = {
+            "LONG": self.trading_commands.long_command,
+            "SHORT": self.trading_commands.short_command,
+            "EXIT": self.trading_commands.exit_command,
+            "SL": self.trading_commands.sl_command,
+            "TP": self.trading_commands.tp_command,
+            "LEVERAGE": self.trading_commands.leverage_command,
+            "COO": self.trading_commands.coo_command,
+            "BALANCE": self.info_commands.balance_command,
+            "POSITIONS": self.info_commands.positions_command,
+            "ORDERS": self.info_commands.orders_command,
+            "STATS": self.info_commands.stats_command,
+            "MARKET": self.info_commands.market_command,
+            "PERFORMANCE": self.info_commands.performance_command,
+            "DAILY": self.info_commands.daily_command,
+            "WEEKLY": self.info_commands.weekly_command,
+            "MONTHLY": self.info_commands.monthly_command,
+            "RISK": self.info_commands.risk_command,
+            "COMMANDS": self.commands_cmds.commands_command,
+            "ALARM": self.management_commands.alarm_command,
+            "MONITORING": self.management_commands.monitoring_command,
+            "LOGS": self.management_commands.logs_command,
+            "DEBUG": self.management_commands.debug_command,
+            "VERSION": self.management_commands.version_command,
+            "KEYBOARD": self.management_commands.keyboard_command,
+        }
+
+        command_func = command_map.get(command_text)
+        if command_func:
+            # We need to simulate a command call, so we'll prepend "/"
+            # to the message text to make it look like a real command.
+            original_text = update.message.text
+            update.message.text = f"/{original_text.lower()}"
+            await command_func(update, context)
+        else:
+            logger.warning(f"Unknown keyboard command: {command_text}")
+            await self.notification_manager.send_generic_notification(
+                f"Unknown command: {command_text}", chat_id=update.effective_chat.id
+            )
+
     async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
         """Handle the /start command."""
         logger.info(f"/start command triggered by chat_id: {update.effective_chat.id}")

+ 1 - 1
src/trading/trading_engine.py

@@ -65,7 +65,7 @@ class TradingEngine:
             if balance and balance.get('total'):
                 usdc_balance = float(balance['total'].get('USDC', 0))
                 # The set_initial_balance method is synchronous
-                self.stats.set_initial_balance(usdc_balance)
+                await self.stats.set_initial_balance(usdc_balance)
         except Exception as e:
             logger.error(f"Could not set initial balance during async init: {e}", exc_info=True)
     

+ 1 - 1
trading_bot.py

@@ -14,7 +14,7 @@ from datetime import datetime
 from pathlib import Path
 
 # Bot version
-BOT_VERSION = "2.4.247"
+BOT_VERSION = "2.4.248"
 
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))