import httpx import asyncio from config import PHONE_NUMBER_ID, WHATSAPP_API_TOKEN async def send_whatsapp_message(wa_id: str, message: str): """Send a message via WhatsApp Business API""" url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages" headers = { "Authorization": f"Bearer {WHATSAPP_API_TOKEN}", "Content-Type": "application/json" } payload = { "messaging_product": "whatsapp", "to": wa_id, "type": "text", "text": {"body": message} } try: async with httpx.AsyncClient() as client: resp = await client.post(url, headers=headers, json=payload) print(f"Sent message → {resp.status_code}: {resp.text}") return resp.status_code == 200 except Exception as e: print(f"Failed to send message: {e}") return False async def send_whatsapp_image(wa_id: str, image_url: str, caption: str = ""): """Send an image via WhatsApp Business API""" url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages" headers = { "Authorization": f"Bearer {WHATSAPP_API_TOKEN}", "Content-Type": "application/json" } payload = { "messaging_product": "whatsapp", "to": wa_id, "type": "image", "image": { "link": image_url, "caption": caption } } try: async with httpx.AsyncClient() as client: resp = await client.post(url, headers=headers, json=payload) print(f"Sent image → {resp.status_code}: {resp.text}") return resp.status_code == 200 except Exception as e: print(f"Failed to send image: {e}") return False async def send_multiple_messages(wa_id: str, messages: list): """Send multiple messages with delays to avoid rate limiting""" for i, message in enumerate(messages): if isinstance(message, dict) and message.get("type") == "image": # Send image success = await send_whatsapp_image(wa_id, message["url"], message.get("caption", "")) else: # Send text message success = await send_whatsapp_message(wa_id, str(message)) if not success: print(f"Failed to send message {i+1}") return False # Add delay between messages to avoid rate limiting (1 second) if i < len(messages) - 1: # Don't delay after the last message await asyncio.sleep(1) return True