from app.services.download_media import download_whatsapp_media from app.services.message import process_message_with_llm from app.services.cache import MessageCache import logging message_cache = MessageCache() logger = logging.getLogger(__name__) async def handle_message(message, user_chats, message_cache, access_token): try: # Process the message content content = message.get("text", {}).get("body") message_id = message.get("id") image = message.get("image") document = message.get("document") video = message.get("video") sender_id = message.get("from") logger.info(f"Content: {content}") logger.info(f"sender_id: {sender_id}") # Download media if exists if image: file_path = f"{image.get('id')}.jpg" logger.info(f"file_path: {file_path}") image_file_path = await download_whatsapp_media(image.get("id"), access_token=access_token, file_path=file_path) logger.info(f"image file_path: {image_file_path}") else: image_file_path = None if document: filename = message.get("document", {}).get("filename") logger.info(f"file_path: {filename}") document_file_path = await download_whatsapp_media(document.get("id"), access_token=access_token, file_path=filename) logger.info(f"document file_path: {document_file_path}") else: document_file_path = None if video: video_type = message.get("video", {}).get("mime_type") video_filename= f"{video.get('id')}.{video_type.split('/')[-1]}" logger.info(f"video_type: {video_type}") video_file_path = await download_whatsapp_media(video.get("id"), access_token=access_token, file_path=video_filename) else: video_file_path = None # Check for duplicates if message_cache.exists(message_id): logger.info(f"Duplicate message detected and skipped: {message_id}") return {"status": "duplicate", "message_id": message_id} # Initialize chat history if sender_id not in user_chats: user_chats[sender_id] = [] # Append content to user chat if user_chats[sender_id] == []: user_chats[sender_id].append({"role": "user", "parts": "This is the chat history so far"}) logger.info(f"user_chats: {user_chats}") # Process the message result = await process_message_with_llm(sender_id, content, user_chats[sender_id], image_file_path = image_file_path, doc_path = document_file_path) if content != None: user_chats[sender_id].append({"role": "user", "parts": content}) user_chats[sender_id].append({"role": "model", "parts": result}) message_cache.add(message_id) return {"status": "success", "message_id": message_id, "result": result} except Exception as e: return {"status": "error", "message_id": message.get("id"), "error": str(e)}