# WhatsApp bot and API in Python: Cloud API and SuperSkope examples

Build a WhatsApp bot in Python: send messages and handle webhooks on Meta’s Cloud API with requests and Flask, or reply in existing chats via SuperSkope.

Canonical URL: https://superskope.com/blog/whatsapp-api-python
Updated: 2026-11-27
Author: SuperSkope

## Short answer

To build a WhatsApp bot in Python with the official Cloud API, run a Flask or FastAPI webhook that verifies Meta’s X-Hub-Signature-256 header, then reply with requests.post to graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages. Free-form replies work within 24 hours of the user’s last message.

To work in existing chats and groups on a regular number, use a linked-device API such as SuperSkope, which is unofficial.

## Two ways to build a WhatsApp bot in Python

A WhatsApp bot is a program that receives messages and replies. In Python you have two practical routes. The official route uses Meta’s Cloud API: your Flask or FastAPI app receives webhooks from Meta and replies with HTTPS requests. The linked-device route uses an API such as SuperSkope that connects a regular WhatsApp number, so the bot can work in existing chats and groups.

You do not need a special SDK for either. Both are plain HTTPS and JSON, and the requests library is enough. The examples below are labelled with the API they call.

|  | Official Cloud API | SuperSkope (linked device) |
| --- | --- | --- |
| Number | Registered business number | Your existing WhatsApp number |
| Receives messages via | Meta webhook (POST to your URL) | Signed webhook or a pull-based events feed |
| Can reply to | 1:1 chats and API-created groups of up to 8 | Selected 1:1 chats and existing groups |
| Starting conversations | Approved templates only | Start-chat endpoint, for people who asked to hear from you |
| Cost | Per delivered message after the free tier | Plan per workspace; no Meta message fees |
| Policy | Authorised by Meta | Not authorised; avoid bulk or cold messaging |

## Send a WhatsApp message from Python (official Cloud API)

Set three environment variables from your App Dashboard: the access token, the phone number ID and a recipient who has opted in. This sends Meta’s hello_world template, which works outside the 24-hour window.

```
# Official WhatsApp Cloud API (Meta)
import os
import requests

url = f"https://graph.facebook.com/v27.0/{os.environ['PHONE_NUMBER_ID']}/messages"
headers = {"Authorization": f"Bearer {os.environ['WHATSAPP_TOKEN']}"}
body = {
    "messaging_product": "whatsapp",
    "to": os.environ["TEST_RECIPIENT"],
    "type": "template",
    "template": {"name": "hello_world", "language": {"code": "en_US"}},
}
response = requests.post(url, headers=headers, json=body, timeout=30)
response.raise_for_status()
print(response.json()["messages"][0]["id"])  # a wamid; delivery arrives later by webhook
```

Copy-only example. No request is run by this page.

## A minimal WhatsApp chatbot in Python with Flask (official Cloud API)

Meta verifies your webhook with a GET request carrying hub.verify_token and hub.challenge, then POSTs events signed with your app secret in the X-Hub-Signature-256 header. Verify the signature on the raw body before trusting it, deduplicate message IDs, and answer with HTTP 200. Replying inside the handler keeps the example short; in production, queue the work and reply from a worker.

> Meta now identifies users by a business-scoped user ID as well as phone number. If a user has adopted a WhatsApp username, phone fields such as from may be missing, so store the user_id fields too.

```
# Official WhatsApp Cloud API (Meta) webhook bot
import hashlib, hmac, os
import requests
from flask import Flask, abort, request

app = Flask(__name__)
TOKEN = os.environ["WHATSAPP_TOKEN"]
PHONE_NUMBER_ID = os.environ["PHONE_NUMBER_ID"]
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
APP_SECRET = os.environ["APP_SECRET"].encode()
seen = set()  # use a database table in production

def reply(to, text):
    requests.post(
        f"https://graph.facebook.com/v27.0/{PHONE_NUMBER_ID}/messages",
        headers={"Authorization": f"Bearer {TOKEN}"},
        json={"messaging_product": "whatsapp", "to": to, "type": "text", "text": {"body": text}},
        timeout=30,
    )

@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)

@app.post("/webhook")
def receive():
    raw = request.get_data()
    expected = "sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Hub-Signature-256", "")):
        abort(401)
    for entry in request.get_json().get("entry", []):
        for change in entry.get("changes", []):
            for msg in change.get("value", {}).get("messages", []):
                if msg["id"] in seen or msg.get("type") != "text":
                    continue
                seen.add(msg["id"])
                if msg["text"]["body"].strip().lower() == "hours":
                    reply(msg["from"], "We are open 9am to 7pm, Monday to Saturday.")
    return "", 200
```

Copy-only example. No request is run by this page.

## Reply to existing chats and groups from Python (SuperSkope)

With SuperSkope, a Python worker can follow the events feed, fetch the text of new messages it is allowed to read, and reply with an idempotency key derived from the event ID. If the worker crashes and processes the same event again, the repeat returns the saved result instead of sending a second reply. The key needs events:read, messages:read and messages:write for the selected chats.

```
# SuperSkope customer API (linked device, not Meta's platform)
import os, time
import requests

BASE = "https://api.superskope.com/api/v1"
AUTH = {"Authorization": "Bearer " + os.environ["SUPERSKOPE_API_KEY"]}

cursor = requests.get(f"{BASE}/events", headers=AUTH, timeout=30).json()["nextCursor"]
while True:
    page = requests.get(f"{BASE}/events", headers=AUTH, params={"after": cursor}, timeout=30)
    page.raise_for_status()  # HTTP 410 means the cursor expired: resync, then start again
    data = page.json()
    for event in data["events"]:
        if event["type"] != "message.received":
            continue
        chat_id, message_id = event["chatId"], event["data"]["messageId"]
        msg = requests.get(f"{BASE}/chats/{chat_id}/messages/{message_id}", headers=AUTH, timeout=30).json()["message"]
        if msg["text"].strip().lower() != "eta":
            continue
        result = requests.post(
            f"{BASE}/chats/{chat_id}/messages",
            headers={**AUTH, "Idempotency-Key": "eta-reply-" + event["id"]},
            json={"type": "text", "text": "Today's deliveries are on schedule.", "replyTo": message_id},
            timeout=40,
        ).json()
        if result.get("state") != "sent":
            print("Check before doing anything else:", result)  # never resend automatically
    cursor = data["nextCursor"]  # persist this in production
    if not data["hasMore"]:
        time.sleep(5)
```

Copy-only example. No request is run by this page.

- [Build a WhatsApp agent around your existing number](https://superskope.com/blog/build-whatsapp-agent)
- [Read the developer documentation](https://docs.superskope.com/)

## Adding AI to a Python WhatsApp bot

Most bots today pass the message to a language model and send back its answer. Keep three boundaries. First, the model decides what to say, but your code decides whether it may be sent, to whom and how often. Second, let a person take over a conversation and stop the bot there. Third, never put API keys in the prompt.

On the official platform, Meta’s Business Solution terms bar general-purpose AI assistants, such as a ChatGPT-style chatbot offered to the public, from the Business API from 15 January 2026, as reported by TechCrunch. Business bots for support, sales and notifications remain allowed. Replies inside the 24-hour window are charged as service messages after the free 1,000 per number.

- [Give an AI agent narrow WhatsApp permissions](https://superskope.com/blog/scoped-whatsapp-agent-permissions)
- [Build a WhatsApp agent around your existing number](https://superskope.com/blog/build-whatsapp-agent)

## What about Python libraries that automate WhatsApp Web?

Some Python packages drive WhatsApp Web through a browser or reimplement its protocol. They are free and quick for a personal script, but they are unofficial clients. WhatsApp’s Help Center says linking an account to unofficial versions of WhatsApp violates its terms and can lead to a ban, and scripted bulk sending is the most common trigger.

> WhatsApp’s Terms of Service prohibit bulk, automated and non-personal messaging without WhatsApp’s authorisation, and unofficial clients can lead to restrictions or a ban. Use a linked-device API for replies, operations and groups you already run, never for cold outreach or broadcasts.

- [Is an unofficial WhatsApp API safe?](https://superskope.com/blog/unofficial-whatsapp-api)

## Production checklist for a Python WhatsApp bot



- Verify webhook signatures on raw bytes, before parsing JSON.
- Store processed message or event IDs in a database, not in memory, so duplicates and restarts are safe.
- Return 200 quickly and do model calls and replies in a worker queue.
- Use idempotency keys or a send ledger so a retry never sends twice.
- Handle rate limits: back off on Meta error 131056 or 130429; respect SuperSkope’s per-key write limit of 10 a minute.
- Log message IDs and outcomes, not tokens or full customer messages.

- [WhatsApp webhooks: setup, signatures and retries](https://superskope.com/blog/whatsapp-webhook-guide)
- [Handle webhook retries without duplicate replies](https://superskope.com/blog/webhook-retries-without-duplicates)

## Frequently asked questions

**Is there an official WhatsApp Python SDK?** You do not need one. Meta’s Cloud API is plain HTTPS and JSON, and its own documentation shows Python examples using the requests library. Community wrappers exist, but check whether they call the official Cloud API or automate WhatsApp Web, which is unofficial.

**Can a Python WhatsApp bot work in groups?** With Meta’s Cloud API, only in groups created through its Groups API, which hold up to 8 participants and require an Official Business Account. With a linked-device API such as SuperSkope, a bot can read and reply in existing groups the number belongs to, if the key is granted those groups.

**How do I host a Python WhatsApp webhook?** Any server reachable over HTTPS with a valid, non-self-signed certificate works: a small VM, a container platform or a serverless function. For development, a tunnelling tool gives your laptop a public HTTPS URL. Meta must be able to reach the URL to verify it.

**Can I build a WhatsApp chatbot in Python for free?** The code and Meta’s API access are free, and replies inside the 24-hour window are free for the first 1,000 a month per number. You pay for hosting, any model calls, and messages beyond the free tier or templates you send first.

## Sources



- [Meta: Cloud API get started](https://developers.facebook.com/documentation/business-messaging/whatsapp/get-started)
- [Meta: Send messages and customer service windows](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages)
- [Meta: WhatsApp webhooks overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)
- [Meta: Create a webhook endpoint](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)
- [Meta: Pricing on the WhatsApp Business Platform (rates effective 1 Oct 2026)](https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing)
- [Meta: About the WhatsApp Business Platform (rate limits)](https://developers.facebook.com/documentation/business-messaging/whatsapp/about-the-platform)
- [Meta: Groups API overview and limits](https://developers.facebook.com/documentation/business-messaging/whatsapp/groups)
- [WhatsApp Help Center: unofficial apps and bans](https://faq.whatsapp.com/1217634902127718)
- [TechCrunch: WhatsApp bars general-purpose chatbots from the Business API (Oct 2025)](https://techcrunch.com/2025/10/18/whatssapp-changes-its-terms-to-bar-general-purpose-chatbots-from-its-platform)

## Continue reading

- [Build a WhatsApp agent around your existing number.](https://superskope.com/blog/build-whatsapp-agent)
- [WhatsApp webhooks: setup, signatures, retries and troubleshooting](https://superskope.com/blog/whatsapp-webhook-guide)
- [Send a WhatsApp message with an API: Cloud API and SuperSkope examples](https://superskope.com/blog/whatsapp-api-send-message)
