> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hypersender.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a WhatsApp Bot in Python

> Build a Python WhatsApp bot with Flask or FastAPI: receive messages through Hypersender webhooks and reply with the Hypersender Python SDK.

## Overview

A WhatsApp bot does two things: it **receives** messages and it **replies**. With Hypersender, incoming messages arrive at your webhook URL, and your Python code replies with the [Hypersender Python SDK](https://docs.hypersender.com/v2/packages-and-sdks/python/installation.md). Your bot runs on your own WhatsApp number, connected to Hypersender with a QR code.

This guide builds a working Python WhatsApp bot in about 30 lines, with Flask or FastAPI.

## What you need

* A [Hypersender account](https://app.hypersender.com/register) with a connected WhatsApp instance.
* The Python SDK installed and your API key and instance ID set. See [Installation](https://docs.hypersender.com/v2/packages-and-sdks/python/installation.md).
* A public HTTPS URL for your webhook. While developing, a tunnel such as [ngrok](https://ngrok.com) works.

## Step 1: Write the bot

The bot below answers every incoming message. It checks the webhook secret, ignores messages you sent yourself, shows "typing...", and replies.

> [tab] Flask
>
> ```bash theme={null}
> pip install hypersender flask
> ```
>
> ```python bot.py theme={null}
> import hmac
> import os
>
> from flask import Flask, abort, request
> from hypersender import Hypersender
>
> app = Flask(__name__)
> hs = Hypersender()
> SECRET = os.environ["HYPERSENDER_WHATSAPP_WEBHOOK_SECRET"]
>
>
> def reply_to(text: str) -> str:
>     if text.strip().lower() in ("hi", "hello"):
>         return "Hello! Reply *menu* to see what I can do."
>     if text.strip().lower() == "menu":
>         return "1. Opening hours\n2. Talk to a human"
>     return f"You said: {text}"
>
>
> @app.post("/whatsapp/webhook")
> def whatsapp_webhook():
>     if not hmac.compare_digest(request.headers.get("Authorization", ""), SECRET):
>         abort(401)
>
>     event = request.get_json()
>     message = event["data"]["payload"]
>
>     if event["event"] == "message.any" and not message["fromMe"]:
>         hs.whatsapp.start_typing(message["from"])
>         hs.whatsapp.send_text(message["from"], reply_to(message["body"]))
>
>     return {"status": "ok"}
> ```
>
> ```bash theme={null}
> flask --app bot run --port 8000
> ```

> [tab] FastAPI
>
> ```bash theme={null}
> pip install hypersender fastapi uvicorn
> ```
>
> ```python bot.py theme={null}
> import hmac
> import os
>
> from fastapi import FastAPI, Header, HTTPException, Request
> from hypersender import Hypersender
>
> app = FastAPI()
> hs = Hypersender()
> SECRET = os.environ["HYPERSENDER_WHATSAPP_WEBHOOK_SECRET"]
>
>
> def reply_to(text: str) -> str:
>     if text.strip().lower() in ("hi", "hello"):
>         return "Hello! Reply *menu* to see what I can do."
>     if text.strip().lower() == "menu":
>         return "1. Opening hours\n2. Talk to a human"
>     return f"You said: {text}"
>
>
> @app.post("/whatsapp/webhook")
> async def whatsapp_webhook(request: Request, authorization: str = Header("")):
>     if not hmac.compare_digest(authorization, SECRET):
>         raise HTTPException(status_code=401)
>
>     event = await request.json()
>     message = event["data"]["payload"]
>
>     if event["event"] == "message.any" and not message["fromMe"]:
>         hs.whatsapp.start_typing(message["from"])
>         hs.whatsapp.send_text(message["from"], reply_to(message["body"]))
>
>     return {"status": "ok"}
> ```
>
> ```bash theme={null}
> uvicorn bot:app --port 8000
> ```

> [!NOTE]
>
> The SDK is synchronous. In FastAPI, if your bot does slow work before replying, move it to a background task so the webhook answers quickly.

## Step 2: Point the webhook at your bot

1. Expose your bot over HTTPS, for example `ngrok http 8000`.
2. In the [Hypersender dashboard](https://app.hypersender.com), open your WhatsApp instance and set the webhook URL to `https://<your-domain>/whatsapp/webhook`.
3. Set a webhook secret and put the same value in your environment as `HYPERSENDER_WHATSAPP_WEBHOOK_SECRET`. Hypersender sends it in the `Authorization` header so your bot can reject anything else.

Send a WhatsApp message to your connected number and the bot replies.

## How the webhook payload looks

Every incoming message arrives as a `message.any` event. The fields a bot usually needs:

| Field | Description |
| - | - |
| `event` | The event name, `message.any` for messages |
| `data.payload.from` | The sender's chat ID. Reply to this, e.g. `201234567890@c.us` |
| `data.payload.body` | The message text |
| `data.payload.fromMe` | `True` for messages your own number sent. Skip these to avoid the bot answering itself |
| `data.payload.hasMedia` | `True` when the message has an image, file, or voice note |
| `data.payload.id` | The message ID, for `react_to_message`, `send_seen`, or `reply_to=` |

Other events your bot can handle: `message.reaction`, `message.ack`, `message.revoked`, `message.waiting`, `poll.vote`, `poll.vote.failed`, and `presence.update`. See [WhatsApp webhooks](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/whatsapp-webhooks-introduction.md) for every payload.

## Make the bot feel natural

Use more of the SDK in your replies:

> [tab] Basic Usage
>
> ```python theme={null}
> chat_id = message["from"]
>
> # Mark the message as read and reply to it in a thread
> hs.whatsapp.send_seen(chat_id, message["id"])
> hs.whatsapp.send_text(chat_id, "Got it!", reply_to=message["id"])
>
> # React with an emoji
> hs.whatsapp.react_to_message(chat_id, message["id"], "👍")
>
> # Send a menu as a poll, or an image
> hs.whatsapp.send_poll(chat_id, "How can we help?", ["Orders", "Billing", "Something else"])
> hs.whatsapp.send_image(chat_id, url="https://example.com/menu.png", caption="Today's menu")
> ```

> [!TIP]
>
> Sending many messages? Use `send_text_safe` instead of `send_text`. It paces messages and simulates typing to lower the risk of your number being blocked. See [Send Messages](https://docs.hypersender.com/v2/packages-and-sdks/python/whatsapp/send-messages.md).

## Next steps

* [Send Messages](https://docs.hypersender.com/v2/packages-and-sdks/python/whatsapp/send-messages.md): text, media, polls, locations, and contact cards
* [Contacts](https://docs.hypersender.com/v2/packages-and-sdks/python/whatsapp/contacts.md): check if a number has WhatsApp before messaging it
* [OTP with Python](https://docs.hypersender.com/v2/packages-and-sdks/python/otp/otp-with-python.md): verify users over WhatsApp


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.