To build a WhatsApp chatbot in Python, connect a Meta business account to the official WhatsApp Cloud API, expose a publicly reachable HTTPS webhook for incoming events, and send replies through the API. This tutorial walks through a small text-in, text-out bot using Flask and direct HTTPS requests. You will need a Meta business portfolio, a WhatsApp Business Account (WABA), a business phone number, and API credentials before writing the Python code.
What you need before you start
Meta’s WhatsApp Cloud API documentation describes the official WhatsApp Business Platform API and its required business assets. These are platform prerequisites, not Python packages.
As an Amazon Associate I earn from qualifying purchases.
- A Meta business portfolio and a WhatsApp Business Account (WABA).
- A business phone number connected to the WABA.
- The phone-number ID and an access token from Meta’s setup flow.
- A Python application with an HTTPS callback URL that Meta can reach.
Use Meta’s current setup instructions to confirm the required permissions and API details for your account. Do not place access tokens, app secrets, or webhook verification strings in source code, screenshots, or a public repository.
How the chatbot works
The bot has two separate network paths. Your Python app sends replies to the Cloud API, while Meta delivers incoming message and status events to your webhook. The webhook must be reachable over HTTPS with a valid certificate, and your app must be subscribed to the WABA to receive its events. See Meta’s webhook documentation for configuration details.
#1 Best Overall
- 【SANOOV Pi 5 4GB Kit Package】SANOOV RPi 5 basic kit includes 1x Pi 5 4GB RAM Single Board, 1x Active Cooler, 1x ABS SANOOV Case for Raspberry Pi 5, 1x GaN PD 27W 5.1V5A Power supply,1x Screwdriver. Tip: SD card is NOT included.
- 【ABS Case Lightweight Texture】 Compared to metal case,ABS case have a softer texture and feel, and the rounded design prevents damage to motherboard components. Meanwhile, the case is partially hollowed out to ensure heat dissipation.
- 【Cooling Kit for Pi 5】Compatible with Active Cooler for Raspberry Pi 5, It can provide Pi 5 board with better cooling effect in using. SANOOV Case can accurately access usb-c power jack,Micro HD Out ports, usb ports, Ethernet jack, card slot, power button, 4-lane MIPI DSI/CSI connectors and so on, and it also supports installation of cooling fan.
- 【27W GaN USB-C Power Supply】The SANOOV GaN 27W USB C Power Supply with smaller size and more stable electric current, fully compatible with Pi 5 16GB/8GB/4GB/2GB, offers a variety of output voltage options, including 5.1V at 5A, 9.0V at 3.0A, 12.0V at 2.25A, and 15.0V at 1.8A, providing for different device requirements.
- 【Support Dual 4Kp60 Display】Each of the two display sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs.
- Meta sends a verification request when you configure the callback URL.
- After verification, Meta sends event notifications to the webhook when subscribed events occur.
- Your app checks that an event contains an inbound text message and chooses a reply.
- Your app makes an authenticated request to the messages endpoint using the phone-number ID.
Set up a Python project and secrets
Install Flask and an HTTP client in a virtual environment:
python -m venv .venv
# macOS or Linux
source .venv/bin/activate
# Windows PowerShell
.venvScriptsActivate.ps1
pip install Flask requests
Set configuration in your shell or deployment platform rather than hard-coding it. The example below reads the values from environment variables:
Rank #2
- ✅ New Improve for Raspberry Pi 5 8GB Kit: 1 x Pi 5 Single Board (8GB), 1 x 64GB Card, 1 x Active Cooler, 1 x Pi 5 ABS Case, 2 x Display OUTPUT Over 4K Cables, 1 x USB-C 27W 5.1V 5A Power Supply, 1 x Card Reader, 1 x Card Adapter, 1 x Screwdriver, 1 x User Manual. RPi is designed to deliver maximum performance in applications such as server solutions, home automation and multimedia.(Tip: The Case cannot install M.2 HAT Add on Board and Solid State Drive!)
- ❄️ Active Cooler & Actively Adjust Speed According Temperature: SANOOV Pi 5 8GB kit offer an active cooler(combines an aluminium heatsink with a temperature-controlled blower fan). The fan supports speed control and is fully compatible with Pi OS. Different from ordinary fans, the active cooler adjust fan speed according to the temperature of the Pi 5 board during use. If the temperature is high, the fan will increase speed to dissipate heat. If low, the fan will decrease speed.
- 🗃 ABS Case & Protection and Cooling: SANOOV Pi 5 Case is made from the high quality ABS material, ABS case is a two-piece injection-molded to provide tough protection for the board while providing access to all the connectors, including USB-C power jack, micro HD-out ports, usb ports, Ethernet jack, sd card slot. And the unique removable top cover design can access to GPIO easily. This is a protective ABS case specifically designed for the Raspberry Pi 5 holds the board firmly in place.
- 🔌 High Quality Power Supply by GaN & 27W 5.1V 5A USB-C: SANOOV power supply for Raspberry Pi 5 powered by GaN Technology with multiple protection functions.GaN technology makes our 27W power supplies smaller, operate at lower temperatures, and more stable without sacrificing power consumption. Importantly this GaN power supply is not limited to Pi5. Devices compatible with charging cables can use this power supply, which is small, convenient and easy to carry.
- 🚀 More Powerful Processor & Ultra HD View: Pi 5 8GB is equipped with broadcom 64 quad-core Arm Cortex A76 processor with gigabit ethernet and upgraded with IEEE 802.11ac Wi-Fi, Bluetooth 5.0 dual-band 2.4Ghz and 5Ghz and Power Over Ethernet (POE). Upgrading delivers 2-3 x speed vs Pi 4, redefining the experience. SANOOV Pi 5 kit has two Mini display Out ports, both ports offer an ultra hd 4kp60 view, which dramatically improves graphics performance.
export WHATSAPP_TOKEN="your-access-token"
export PHONE_NUMBER_ID="your-phone-number-id"
export VERIFY_TOKEN="a-random-webhook-verification-string"
export APP_SECRET="your-meta-app-secret"
The verification string is a value you choose and also enter in Meta’s webhook configuration. Keep it private, along with the token and app secret. Meta’s documentation says user tokens expire after 24 hours; system-user tokens may be configured to last up to 60 days or permanently, depending on configuration. Treat token lifetime as a setting to verify in your account, not as a guarantee, and plan a secure renewal process.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesBuild the webhook and reply handler
Create app.py. The GET route handles Meta’s webhook verification handshake. The POST route processes notifications separately: a notification may be a status update or another event rather than an inbound user message, so the handler checks the nested structure before reading text.
Rank #3
- 5 sets of code: Python (compatible with 2&3), C, Java, Scratch and Processing (Scratch and Processing code provide graphical interfaces)
- Detailed tutorial: Can be downloaded (in English, 962-page in total) or viewed online (original in English, can be translated into other languages by browsers) (The tutorial link can be found on the product box, no paper tutorial)
- 128 projects from simple to complex: Provides step-by-step guide with electronics and components knowledge, each project has schematics, wiring diagrams, complete code and detailed explanations
- 223 items in total: This ultimate kit includes the most commonly used electronic components, modules, sensors, wires and other compatible items
- Compatible models: Raspberry Pi 5 / 500 / 400 / 4B / 3B+ / 3B / 3A+ / 2B / 1B+ / 1A+ / Zero 2 W / Zero W / Zero (NOT included in this kit)
import os
import requests
from flask import Flask, abort, request
app = Flask(__name__)
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
WHATSAPP_TOKEN = os.environ["WHATSAPP_TOKEN"]
PHONE_NUMBER_ID = os.environ["PHONE_NUMBER_ID"]
@app.get("/webhook")
def verify_webhook():
mode = request.args.get("hub.mode")
token = request.args.get("hub.verify_token")
challenge = request.args.get("hub.challenge")
if mode == "subscribe" and token == VERIFY_TOKEN and challenge:
return challenge, 200
abort(403)
@app.post("/webhook")
def receive_webhook():
payload = request.get_json(silent=True) or {}
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
for message in value.get("messages", []):
sender = message.get("from")
if not sender:
continue
if message.get("type") == "text":
text = message.get("text", {}).get("body", "").strip()
if not text:
continue
reply = choose_reply(text)
send_text(sender, reply)
else:
# Add explicit handling for media and other supported types.
pass
return "EVENT_RECEIVED", 200
def choose_reply(text):
normalized = text.casefold()
if normalized in {"hi", "hello", "hey"}:
return "Hello! How can I help?"
return "Thanks for your message. What would you like help with?"
def send_text(recipient, text):
# Select the current Graph API version from Meta's documentation.
url = f"https://graph.facebook.com/{os.environ['GRAPH_API_VERSION']}/{PHONE_NUMBER_ID}/messages"
headers = {
"Authorization": f"Bearer {WHATSAPP_TOKEN}",
"Content-Type": "application/json",
}
payload = {
"messaging_product": "whatsapp",
"to": recipient,
"type": "text",
"text": {"body": text},
}
response = requests.post(url, headers=headers, json=payload, timeout=15)
response.raise_for_status()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Set GRAPH_API_VERSION using the version shown in Meta’s current documentation; it is intentionally not fixed in this example. The URL uses the phone-number ID, not the business phone number itself. Meta’s messages reference describes the request endpoint and payload.
This is a teaching example, not a deployed or tested service. It omits production safeguards such as signature validation, structured logging, durable processing, and application-specific error handling. Add those before using the bot with real customers. In particular, validate webhook authenticity using Meta’s current guidance before trusting event contents.
Rank #4
- IoT Starter Kit for Beginners: The SunFounder Raspberry Pi Pico W Ultimate Starter Kit offers a rich IoT learning experience for beginners aged 8+. With 450+ components, 117 projects, and expert-led video lessons, this kit makes learning microcontroller programming and IoT engaging and accessible, RoHS Compliant
- Expert-Guided Video Lessons: This kit includes 27 video tutorials by the renowned educator, Paul McWhorter. His engaging style simplifies complex concepts, ensuring an effective learning experience in microcontroller programming
- Wide Range of Hardware: The kit includes a diverse array of components like sensors, actuators, LEDs, LCDs, and more, enabling you to experiment and create a variety of projects with the Raspberry Pi Pico W
- Supports Multiple Languages: The kit offers versatility with support for three programming languages - MicroPython, C/C++, and Piper Make, providing a diverse programming learning experience
- Dedicated Support: Benefit from our ongoing assistance, including a community forum and timely technical help for a seamless learning experience
Configure and verify the webhook
- Run the Flask app locally and make its callback path,
/webhook, reachable from the public internet over HTTPS with a valid certificate. A local development tunnel can provide reachability, but choose and configure one yourself; the important requirement is public HTTPS access. - In Meta’s app and WhatsApp setup, enter the callback URL and the same verification string used for
VERIFY_TOKEN. - Complete the GET verification handshake. Meta’s request should receive the challenge value back with a successful response; a mismatch in the string or route prevents verification.
- Subscribe the app to the WABA and the relevant message events using Meta’s current configuration flow.
- Send a test message to the configured business number and inspect the POST payload and application logs. Confirm the bot handles a message event without treating status notifications as messages.
Webhook payloads include account and phone-number metadata alongside event-specific data. Status notifications can represent sent, delivered, read, failed, or deleted states; they are not user messages to answer. Consult Meta’s webhook payload reference when extending the parser.
Test the outbound API request
Once the callback is configured, send a message from a test conversation and verify that the webhook receives a text message and that the API request succeeds. The example raises an error for unsuccessful HTTP responses; in a real app, log the response status and safe diagnostic details without recording tokens or unnecessary message content. A successful request only confirms the API accepted the send request; use subsequent status events to track delivery state.
Best Value
- Part Number: Pi Debug Probe
- Original USB Debug Probe for Raspberry Pi Pico, Hardware debug kit designed for Pico, Based on RP2040 Microcontroller, With transparent plastic case
- Pi Debug Probe is an official USB hardware debugger designed for Pico, all-in-one design, with the features of solderless and plug-and-play, can be connected to the debug interface of the target board via SWD interface.
- This makes it easy to use a Pi Pico on non-R Pi platforms such as Windows, Mac, and “normal” Linux computers, where you don’t have a GPIO header to connect directly to the Pico’s serial UART or SWD port.
- Onboard Micro-USB port for connecting to PC or other motherboards. Onboard 3PIN SWD interface for connecting to the target board. Onboard 3PIN USB to UART bridge
Prepare the bot for launch
Follow the template rule for business-initiated messages
Meta’s WhatsApp Business Messaging Policy says businesses may initiate conversations only with an approved message template. Design outbound workflows accordingly, and consult the live policy for the applicable rules rather than assuming a free-form reply can start a conversation.
Check current costs and API settings
WhatsApp Business API fees follow Meta’s rate card, and the terms allow rate-card updates. Check the current region-specific pricing information before estimating operating costs; a static figure can become misleading as pricing changes. The API version, token permissions, and account-specific setup details can also change, so use Meta’s live documentation during configuration.
Make event handling resilient
- Handle missing fields, unsupported message types, and non-message events without crashing the request handler.
- Return promptly to webhook deliveries; move slow work to a background queue if the bot later performs substantial processing.
- Make processing safe against repeated deliveries by tracking event identifiers or otherwise preventing duplicate replies. Confirm current delivery and retry behavior in Meta’s webhook documentation for the API configuration you use.
- Rotate any token or secret that has been exposed, and keep production secrets in a managed environment rather than source control.
- Run the app behind a stable HTTPS endpoint with monitoring and uptime appropriate for the service.
Direct API calls or a Python wrapper?
Direct HTTP requests, as shown here, keep the request and event-handling logic visible and under your control. A Python wrapper can reduce some integration work. PyWa is a third-party framework, not an official Meta Python SDK; its documentation describes integrations for Flask and FastAPI.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
| Approach | What you implement | Fit |
|---|---|---|
| Direct HTTPS calls | Your app handles webhook routes, payload checks, API requests, and error handling directly. | Useful when you want a small dependency footprint and explicit control of the integration. |
| PyWa | The wrapper provides an abstraction over parts of the WhatsApp integration; the exact responsibilities depend on the framework and configuration. | Consider it if you want an abstraction that fits an existing Flask or FastAPI app. See PyWa’s documentation. |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




