Chandima Prabhath commited on
Commit
2a5855c
·
1 Parent(s): 21738c6

uptade reply handeling

Browse files
Files changed (1) hide show
  1. app.py +54 -10
app.py CHANGED
@@ -299,6 +299,8 @@ class WhatsAppBot:
299
  self.conv_manager = ConversationManager(config.MAX_HISTORY_SIZE)
300
  self.intent_router = IntentRouter(self.conv_manager, self.logger)
301
  self.task_queue = queue.Queue()
 
 
302
  self.fastapi_app = FastAPI(title="WhatsApp Eve Bot", version="2.0.0")
303
  self._setup_routes()
304
  self._start_workers()
@@ -360,28 +362,42 @@ class WhatsAppBot:
360
  message_id = payload["idMessage"]
361
 
362
  # ** CHAT RESTRICTION LOGIC **
363
- # Check if the sender is in the allowed list
364
  if chat_id not in self.config.ALLOWED_CHATS:
365
  self.logger.warning(f"Ignoring message from unauthorized chat ID: {chat_id}")
366
- return # Stop processing immediately
367
 
368
- # Set thread context for logging
369
  ThreadContext.set_context(chat_id, message_id)
370
 
371
  message_data = payload.get("messageData", {})
372
  type_message = message_data.get("typeMessage")
373
 
 
 
 
 
 
 
 
 
 
 
374
  text = ""
375
  if type_message == "textMessage":
376
- text = message_data["textMessageData"]["textMessage"]
377
  elif type_message == "extendedTextMessage":
378
- text = message_data["extendedTextMessageData"]["text"]
 
 
 
 
379
 
380
  text = text.strip()
381
  if not text:
382
- self.logger.debug(f"Received empty message from {chat_id}. Ignoring.")
383
  return
384
 
 
 
385
  self.logger.info(f"Processing message from {chat_id}: '{text}'")
386
  self.conv_manager.add_user_message(chat_id, text)
387
 
@@ -450,12 +466,40 @@ class WhatsAppBot:
450
 
451
  def _dispatch_edit_image(self, chat_id, message_id, prompt, payload):
452
  """Checks for a replied-to image and dispatches the edit task."""
453
- quoted_message = payload.get("messageData", {}).get("extendedTextMessageData", {}).get("quotedMessage")
454
- if not quoted_message or quoted_message.get("typeMessage") != "imageMessage":
455
- self.api_client.send_message(chat_id, "To edit an image, please reply to it with your instructions.", message_id)
 
 
 
 
 
 
 
456
  return
457
 
458
- download_url = quoted_message["imageMessage"]["downloadUrl"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  self.task_queue.put({
460
  "type": "edit_image",
461
  "chat_id": chat_id,
 
299
  self.conv_manager = ConversationManager(config.MAX_HISTORY_SIZE)
300
  self.intent_router = IntentRouter(self.conv_manager, self.logger)
301
  self.task_queue = queue.Queue()
302
+ # Cache to store recent image message IDs and their download URLs
303
+ self.image_cache = defaultdict(lambda: deque(maxlen=50))
304
  self.fastapi_app = FastAPI(title="WhatsApp Eve Bot", version="2.0.0")
305
  self._setup_routes()
306
  self._start_workers()
 
362
  message_id = payload["idMessage"]
363
 
364
  # ** CHAT RESTRICTION LOGIC **
 
365
  if chat_id not in self.config.ALLOWED_CHATS:
366
  self.logger.warning(f"Ignoring message from unauthorized chat ID: {chat_id}")
367
+ return
368
 
 
369
  ThreadContext.set_context(chat_id, message_id)
370
 
371
  message_data = payload.get("messageData", {})
372
  type_message = message_data.get("typeMessage")
373
 
374
+ # --- Improved message processing logic ---
375
+
376
+ # 1. Handle image caching
377
+ if type_message == "imageMessage":
378
+ download_url = message_data.get("fileMessageData", {}).get("downloadUrl")
379
+ if download_url:
380
+ self.logger.debug(f"Caching image message {message_id} from {chat_id} with URL: {download_url}")
381
+ self.image_cache[chat_id].append((message_id, download_url))
382
+
383
+ # 2. Extract text from various message types
384
  text = ""
385
  if type_message == "textMessage":
386
+ text = message_data.get("textMessageData", {}).get("textMessage", "")
387
  elif type_message == "extendedTextMessage":
388
+ text = message_data.get("extendedTextMessageData", {}).get("text", "")
389
+ elif type_message == "quotedMessage":
390
+ text = message_data.get("extendedTextMessageData", {}).get("text", "")
391
+ elif type_message == "imageMessage":
392
+ text = message_data.get("fileMessageData", {}).get("caption", "")
393
 
394
  text = text.strip()
395
  if not text:
396
+ self.logger.debug(f"Received message type '{type_message}' without actionable text from {chat_id}. No action taken.")
397
  return
398
 
399
+ # --- End of improved logic ---
400
+
401
  self.logger.info(f"Processing message from {chat_id}: '{text}'")
402
  self.conv_manager.add_user_message(chat_id, text)
403
 
 
466
 
467
  def _dispatch_edit_image(self, chat_id, message_id, prompt, payload):
468
  """Checks for a replied-to image and dispatches the edit task."""
469
+ message_data = payload.get("messageData", {})
470
+
471
+ # Ensure we are dealing with a reply
472
+ if message_data.get("typeMessage") != "quotedMessage":
473
+ self.api_client.send_message(chat_id, "To edit an image, please reply to an image with your instructions.", message_id)
474
+ return
475
+
476
+ quoted_info = message_data.get("quotedMessage")
477
+ if not quoted_info or quoted_info.get("typeMessage") != "imageMessage":
478
+ self.api_client.send_message(chat_id, "You must reply to an image to edit it.", message_id)
479
  return
480
 
481
+ # Get the ID of the message being replied to
482
+ quoted_message_id = quoted_info.get("stanzaId")
483
+ if not quoted_message_id:
484
+ self.logger.error(f"Could not find stanzaId in quoted message: {quoted_info}")
485
+ self.api_client.send_message(chat_id, "Sorry, I couldn't identify which image to edit.", message_id)
486
+ return
487
+
488
+ # Find the downloadUrl from our cache
489
+ download_url = None
490
+ if chat_id in self.image_cache:
491
+ # Search the cache for the matching message ID
492
+ for msg_id, url in self.image_cache[chat_id]:
493
+ if msg_id == quoted_message_id:
494
+ download_url = url
495
+ break
496
+
497
+ if not download_url:
498
+ self.logger.warning(f"Could not find download URL for message ID {quoted_message_id} in cache for chat {chat_id}.")
499
+ self.api_client.send_message(chat_id, "I couldn't find the original image. It might be too old. Please send it again before editing.", message_id)
500
+ return
501
+
502
+ self.logger.info(f"Found cached image URL for message {quoted_message_id}. Dispatching edit task.")
503
  self.task_queue.put({
504
  "type": "edit_image",
505
  "chat_id": chat_id,