Explorar o código

Refactor price command to include loading messages and improve error handling. Added asynchronous message editing for better user feedback during price retrieval, ensuring clearer communication of errors and results.

Carles Sentis hai 4 días
pai
achega
775b4e2952
Modificáronse 3 ficheiros con 38 adicións e 18 borrados
  1. 32 12
      src/commands/info/price.py
  2. 5 5
      src/commands/info/risk.py
  3. 1 1
      trading_bot.py

+ 32 - 12
src/commands/info/price.py

@@ -3,6 +3,7 @@ from telegram import Update
 from telegram.ext import ContextTypes
 from .base import InfoCommandsBase
 from src.utils.token_display_formatter import get_formatter
+from src.config.config import Config
 
 logger = logging.getLogger(__name__)
 
@@ -14,18 +15,26 @@ class PriceCommands(InfoCommandsBase):
         if not self._is_authorized(update):
             return
 
-        try:
-            # Check if a specific token was requested
-            args = context.args
-            if not args:
-                await self._reply(update, "❌ Please specify a token. Example: /price BTC")
-                return
+        # Determine token first to use in the loading message
+        token = context.args[0].upper() if context.args else Config.DEFAULT_TRADING_TOKEN
 
-            token = args[0].upper()
-            market_data = self.trading_engine.get_market_data(token)
+        # Send a loading message first
+        sent_message = await self._reply(update, f"⏳ Fetching price for {token}...")
+        if not sent_message:
+            logger.error("Failed to send initial message in price_command.")
+            return
+
+        try:
+            # Construct the full market symbol
+            symbol = f"{token}/USDC:USDC"
+            market_data = await self.trading_engine.get_market_data(symbol)
             
             if not market_data or not market_data.get('ticker'):
-                await self._reply(update, f"❌ Could not fetch price data for {token}")
+                await context.bot.edit_message_text(
+                    chat_id=sent_message.chat.id,
+                    message_id=sent_message.message_id,
+                    text=f"❌ Could not fetch price data for {symbol}"
+                )
                 return
 
             ticker = market_data['ticker']
@@ -52,9 +61,20 @@ class PriceCommands(InfoCommandsBase):
             volume_24h = float(ticker.get('quoteVolume', 0))
             price_text_parts.append(f"💎 <b>24h Volume:</b> {await formatter.format_price_with_symbol(volume_24h)}")
 
-            await self._reply(update, "\n".join(price_text_parts))
+            final_message = "\n".join(price_text_parts)
+            await context.bot.edit_message_text(
+                chat_id=sent_message.chat.id,
+                message_id=sent_message.message_id,
+                text=final_message,
+                parse_mode='HTML'
+            )
 
         except Exception as e:
             error_message = f"❌ Error processing price command: {str(e)}"
-            await self._reply(update, error_message)
-            logger.error(f"Error in price command: {e}") 
+            logger.error(f"Error in price command: {e}", exc_info=True)
+            if sent_message:
+                await context.bot.edit_message_text(
+                    chat_id=sent_message.chat.id,
+                    message_id=sent_message.message_id,
+                    text=error_message
+                ) 

+ 5 - 5
src/commands/info/risk.py

@@ -22,11 +22,11 @@ class RiskCommands(InfoCommandsBase):
             token = context.args[0].upper() if context.args else Config.DEFAULT_TRADING_TOKEN
             
             # Get current positions and orders
-            positions = await self.trading_engine.get_positions()
-            orders = await self.trading_engine.get_orders()
+            positions = self.trading_engine.get_positions()
+            orders = self.trading_engine.get_orders()
             
             # Get trading statistics
-            stats = self.trading_engine.get_trading_stats()
+            stats = self.trading_engine.get_stats()
             
             # Calculate unrealized P&L for open positions
             total_unrealized_pnl = 0.0
@@ -120,5 +120,5 @@ class RiskCommands(InfoCommandsBase):
             await update.message.reply_text(message, parse_mode='HTML')
             
         except Exception as e:
-            logger.error(f"Error in risk command: {e}")
-            await update.message.reply_text("❌ Error getting risk information. Please try again later.")
+            logger.error(f"Error in risk command: {e}", exc_info=True)
+            await self._reply(update, "❌ Error getting risk information. Please try again later.")

+ 1 - 1
trading_bot.py

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