WhatsApp Automation with Python
अंतिम अपडेट:
Which Python approach to use
Three approaches show up in search results. Only two are suitable for a business.
| Approach | Official | Good for | Risk |
|---|---|---|---|
| Cloud API with requests or httpx | OfficialYes | Good forProduction chatbots, notifications, CRM sync | RiskYou build and host the webhook |
| Provider SDK (for example Twilio's Python library) | OfficialYes, through a Business Solution Provider | Good forTeams that want the provider to handle infrastructure | RiskProvider fees and its own API shape |
| pywhatkit or other WhatsApp Web automation | OfficialNo | Good forPersonal experiments only | RiskNumber can be restricted or banned; breaks when WhatsApp Web changes |
What you need before writing code
Set these up in Meta's developer dashboard first. The code below reads them from environment variables.
- A Meta developer account and an app with the WhatsApp product added.
- A phone number ID and a WhatsApp Business account ID for that number. Meta provides a test number you can use while developing.
- An access token. Temporary tokens expire quickly; use a system user token for anything long-running.
- Your app secret, used to verify that webhook calls really come from Meta.
- A public HTTPS URL for the webhook. A tunnelling tool works during development.
Send a message
Sending is one authenticated HTTP request. Free-form text works only inside the 24-hour customer service window; to start a conversation or message after the window you must send an approved template, shown as the second function.
import os
import requests
API_VERSION = os.environ.get("WA_API_VERSION", "v21.0") # use a version Meta currently supports
PHONE_NUMBER_ID = os.environ["WA_PHONE_NUMBER_ID"]
TOKEN = os.environ["WA_ACCESS_TOKEN"]
URL = f"https://graph.facebook.com/{API_VERSION}/{PHONE_NUMBER_ID}/messages"
HEADERS = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}
def _post(payload: dict) -> dict:
response = requests.post(URL, json=payload, headers=HEADERS, timeout=10)
response.raise_for_status()
return response.json()
def send_text(to: str, body: str) -> dict:
"""Free-form text. Only valid inside the 24-hour customer service window."""
return _post({
"messaging_product": "whatsapp",
"to": to, # digits with country code, for example 38640123456
"type": "text",
"text": {"body": body},
})
def send_template(to: str, name: str, language: str = "en") -> dict:
"""Approved template. Required to start a conversation or after the 24-hour window."""
return _post({
"messaging_product": "whatsapp",
"to": to,
"type": "template",
"template": {"name": name, "language": {"code": language}},
})
Receive messages with a webhook
Meta calls your webhook for every inbound message. A GET request verifies the endpoint once, and POST requests deliver messages. Always verify the X-Hub-Signature-256 header against the raw request body before trusting a payload.
import hashlib
import hmac
import os
from flask import Flask, abort, request
from send_message import send_text
app = Flask(__name__)
VERIFY_TOKEN = os.environ["WA_VERIFY_TOKEN"]
APP_SECRET = os.environ["WA_APP_SECRET"]
seen_ids: set[str] = set() # use Redis or a database in production
@app.get("/webhook")
def verify():
if (request.args.get("hub.mode") == "subscribe"
and request.args.get("hub.verify_token") == VERIFY_TOKEN):
return request.args.get("hub.challenge", ""), 200
abort(403)
def valid_signature(raw_body: bytes, header: str | None) -> bool:
if not header or not header.startswith("sha256="):
return False
expected = hmac.new(APP_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header.removeprefix("sha256="))
@app.post("/webhook")
def inbound():
# Verify against the raw bytes, before any JSON parsing.
if not valid_signature(request.get_data(), request.headers.get("X-Hub-Signature-256")):
abort(403)
payload = request.get_json(silent=True) or {}
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
for message in change.get("value", {}).get("messages", []):
if message["id"] in seen_ids: # Meta may deliver the same message more than once
continue
seen_ids.add(message["id"])
handle_message(message)
return "", 200 # acknowledge quickly; do slow work in a queue
def handle_message(message: dict) -> None:
sender = message["from"]
text = message.get("text", {}).get("body", "").strip().lower()
if text in {"price", "pricing"}:
send_text(sender, "Our pricing depends on your volume. Reply HUMAN to talk to a person.")
elif text == "human":
send_text(sender, "Thanks, a team member will reply shortly.")
# notify your team here
else:
send_text(sender, "Hi! Reply PRICE for pricing or HUMAN to talk to a person.")
if __name__ == "__main__":
app.run(port=8000)
How the pieces fit together
Keep the webhook thin. Verify, acknowledge and queue; do slow work such as CRM calls or AI requests outside the request.
- 01Customer message
- 02Meta webhook call
- 03Verify signature
- 04Deduplicate by ID
- 05Route and reply
- 06Write to CRM
Common errors and what they usually mean
Most first-day problems fall into a handful of causes.
- A text message is rejected after a day of silence: the 24-hour window closed, so send an approved template.
- Signature check always fails: you hashed parsed JSON instead of the raw body, or used the wrong app secret.
- The webhook verifies but never receives messages: the webhook is not subscribed to the messages field for the number.
- Authentication errors after a day: the temporary access token expired.
- Duplicate replies: Meta retries when it does not get a fast 200 response, so deduplicate by message ID.
Judging a GitHub project before you use it
Search results for "whatsapp automation python github" are full of repositories. A quick checklist saves you from building on a dead or risky one.
- Does it call Meta's Cloud API or a provider's API, rather than controlling WhatsApp Web?
- When was the last commit, and are issues answered?
- Does it verify webhook signatures?
- Is there a licence that allows commercial use?
- Does it hard-code secrets, or read them from the environment?
अपना 7-दिन का ट्रायल शुरू करें
देखें कि WhatsApp ऑटोमेशन आपके व्यवसाय को लीड जुटाने, बातचीत ऑटोमेट करने और तेज़ फ़ॉलो-अप करने में कैसे मदद कर सकता है।
अक्सर पूछे जाने वाले प्रश्न
How do I automate WhatsApp messages with Python?
- Use Meta's WhatsApp Business Platform Cloud API. Send messages with an authenticated HTTP POST to the messages endpoint, and receive replies on a webhook built with Flask or FastAPI.
Is pywhatkit safe for business use?
- No. It automates WhatsApp Web through a browser, which is not an official integration. It is fragile and can lead to the number being restricted. Use the Cloud API for business messaging.
Can I use the WhatsApp API for free?
- Meta provides a test number for development, but production messaging is charged per message by category and country. See the pricing breakdown.
Should I use Python or Node.js?
- Either works with the same API. Choose the language your team already maintains. The Node.js version of this guide covers the same flow.
स्रोत
About this page
Published by WhatsAppAutomation.si.
Pages here are written and reviewed in-house, cite Meta's documentation for platform rules, and carry a last-updated date. WhatsApp's pricing and policies change, so confirm anything that affects a decision against Meta's current documentation.