Browse Source

Refactor reply handling in InfoCommandsBase to return Message objects and improve error logging in MarketCommands for initial message failures. Ensure fallback mechanisms are in place for message replies, enhancing overall command reliability.

Carles Sentis 1 month ago
parent
commit
37bc19028e
3 changed files with 18 additions and 8 deletions
  1. 11 5
      src/commands/info/base.py
  2. 6 2
      src/commands/info/market.py
  3. 1 1
      trading_bot.py

+ 11 - 5
src/commands/info/base.py

@@ -1,6 +1,6 @@
 import logging
 import logging
 from typing import Optional, Dict, Any
 from typing import Optional, Dict, Any
-from telegram import Update
+from telegram import Update, Message
 from telegram.ext import ContextTypes
 from telegram.ext import ContextTypes
 
 
 logger = logging.getLogger(__name__)
 logger = logging.getLogger(__name__)
@@ -20,17 +20,21 @@ class InfoCommandsBase:
             return False
             return False
         return True  # Add your authorization logic here
         return True  # Add your authorization logic here
 
 
-    async def _reply(self, update: Update, text: str, parse_mode: str = 'HTML') -> None:
+    async def _reply(self, update: Update, text: str, parse_mode: str = 'HTML') -> Optional[Message]:
         """Common reply method for all commands."""
         """Common reply method for all commands."""
         try:
         try:
             if update.callback_query:
             if update.callback_query:
                 await update.callback_query.answer()
                 await update.callback_query.answer()
-                await update.callback_query.edit_message_text(
+                result = await update.callback_query.edit_message_text(
                     text=text,
                     text=text,
                     parse_mode=parse_mode
                     parse_mode=parse_mode
                 )
                 )
-            else:
-                await update.message.reply_text(
+                if isinstance(result, Message):
+                    return result
+                return update.callback_query.message  # Fallback for True case
+            
+            elif update.message:
+                return await update.message.reply_text(
                     text=text,
                     text=text,
                     parse_mode=parse_mode
                     parse_mode=parse_mode
                 )
                 )
@@ -45,6 +49,8 @@ class InfoCommandsBase:
                     )
                     )
             except Exception as e2:
             except Exception as e2:
                 self.logger.error(f"Error sending fallback reply: {e2}")
                 self.logger.error(f"Error sending fallback reply: {e2}")
+        
+        return None
 
 
     def _get_formatter(self):
     def _get_formatter(self):
         """Get the token display formatter."""
         """Get the token display formatter."""

+ 6 - 2
src/commands/info/market.py

@@ -20,7 +20,10 @@ class MarketCommands(InfoCommandsBase):
         
         
         # Send a loading message first
         # Send a loading message first
         sent_message = await self._reply(update, "⏳ Fetching market data...")
         sent_message = await self._reply(update, "⏳ Fetching market data...")
-        
+        if not sent_message:
+            logger.error("Failed to send initial message in market_command.")
+            return
+
         try:
         try:
             if not self._is_authorized(update):
             if not self._is_authorized(update):
                 await context.bot.edit_message_text(chat_id=sent_message.chat.id, message_id=sent_message.message_id, text="❌ Unauthorized access.")
                 await context.bot.edit_message_text(chat_id=sent_message.chat.id, message_id=sent_message.message_id, text="❌ Unauthorized access.")
@@ -103,4 +106,5 @@ class MarketCommands(InfoCommandsBase):
             
             
         except Exception as e:
         except Exception as e:
             logger.error(f"Error in market command: {e}")
             logger.error(f"Error in market command: {e}")
-            await context.bot.edit_message_text(chat_id=sent_message.chat.id, message_id=sent_message.message_id, text="❌ Error getting market information. Please try again later.")
+            if sent_message:
+                await context.bot.edit_message_text(chat_id=sent_message.chat.id, message_id=sent_message.message_id, text="❌ Error getting market information. Please try again later.")

+ 1 - 1
trading_bot.py

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