File size: 2,536 Bytes
90f252d
a35f267
90f252d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca24f6
 
 
 
90f252d
 
a35f267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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