소스 검색

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 4 일 전
부모
커밋
37bc19028e
3개의 변경된 파일18개의 추가작업 그리고 8개의 파일을 삭제
  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
 from typing import Optional, Dict, Any
-from telegram import Update
+from telegram import Update, Message
 from telegram.ext import ContextTypes
 
 logger = logging.getLogger(__name__)
@@ -20,17 +20,21 @@ class InfoCommandsBase:
             return False
         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."""
         try:
             if update.callback_query:
                 await update.callback_query.answer()
-                await update.callback_query.edit_message_text(
+                result = await update.callback_query.edit_message_text(
                     text=text,
                     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,
                     parse_mode=parse_mode
                 )
@@ -45,6 +49,8 @@ class InfoCommandsBase:
                     )
             except Exception as e2:
                 self.logger.error(f"Error sending fallback reply: {e2}")
+        
+        return None
 
     def _get_formatter(self):
         """Get the token display formatter."""

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

@@ -20,7 +20,10 @@ class MarketCommands(InfoCommandsBase):
         
         # Send a loading message first
         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:
             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.")
@@ -103,4 +106,5 @@ class MarketCommands(InfoCommandsBase):
             
         except Exception as 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
 
 # Bot version
-BOT_VERSION = "2.4.227"
+BOT_VERSION = "2.4.228"
 
 # Add src directory to Python path
 sys.path.insert(0, str(Path(__file__).parent / "src"))