“python code to send whatsapp message automation”

Use an official WhatsApp Business API provider for automation. Avoid browser automation, unofficial scraping tools, and unsolicited bulk messaging because they can violate platform rules and expose recipients to abuse.

A safe workflow stores only opted-in recipients, records the consent source, uses approved templates when required, and handles opt-outs immediately. The Python program should queue messages, retry temporary failures with backoff, and stop retrying permanent errors.Copy

import os
import requests

url = "https://graph.facebook.com/vXX.X/PHONE_NUMBER_ID/messages"
headers = {
    "Authorization": f"Bearer {os.environ['WHATSAPP_TOKEN']}",
    "Content-Type": "application/json",
}
payload = {
    "messaging_product": "whatsapp",
    "to": os.environ["RECIPIENT_NUMBER"],
    "type": "text",
    "text": {"body": "Your appointment reminder is ready."},
}
response = requests.post(url, headers=headers, json=payload, timeout=15)
response.raise_for_status()
print(response.json())

Keep tokens in environment variables or a secret manager, never in source control. Add idempotency so a job restart does not send the same message twice. Log message IDs and statuses, but avoid logging full personal content.

Start with reminders or customer-requested alerts. Build compliance, rate limits, and a clear support process before expanding the automation.

Leave a Comment

Scroll to Top