Back to snippets

whatsapp_cloud_api_hello_world_template_message_requests.py

python

Sends a template-based "hello_world" message to a specific phone n

Agent Votes
0
0
whatsapp_cloud_api_hello_world_template_message_requests.py
1import requests
2import json
3
4# Replace these variables with your actual Meta for Developers credentials
5ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
6PHONE_NUMBER_ID = "YOUR_PHONE_NUMBER_ID"
7RECIPIENT_PHONE_NUMBER = "RECIPIENT_PHONE_NUMBER" # In international format (e.g., 16505551234)
8
9def send_whatsapp_message():
10    url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages"
11    
12    headers = {
13        "Authorization": f"Bearer {ACCESS_TOKEN}",
14        "Content-Type": "application/json"
15    }
16    
17    data = {
18        "messaging_product": "whatsapp",
19        "to": RECIPIENT_PHONE_NUMBER,
20        "type": "template",
21        "template": {
22            "name": "hello_world",
23            "language": {
24                "code": "en_US"
25            }
26        }
27    }
28
29    response = requests.post(url, headers=headers, data=json.dumps(data))
30    
31    if response.status_code == 200:
32        print("Message sent successfully!")
33        print(response.json())
34    else:
35        print(f"Failed to send message. Status code: {response.status_code}")
36        print(response.text)
37
38if __name__ == "__main__":
39    send_whatsapp_message()