Build a WhatsApp Chatbot with Python and Flask
Any statistics or percentages in this article are general industry figures or illustrations, not QuackAPI measurements or promises. Results depend on your audience, consent and sending patterns. QuackAPI connects to WhatsApp as a linked device (an unofficial method), so read our risk and acceptable use policy before sending.
What You'll Build
In this tutorial, you will build a fully functional WhatsApp chatbot that receives incoming messages via webhooks, processes commands like help, pricing, and hours, and sends intelligent auto-replies using the QuackAPI API.
The chatbot will include a menu system, keyword-based routing, and proper error handling. By the end, you will have a deployable Flask application ready for production use.
Setting Up Flask
Install Flask and the requests library for making API calls. Create a new project directory and set up your Flask application with the basic structure needed for webhook handling.
pip install flask requestsReceiving Messages via Webhook
Create a POST endpoint that QuackAPI will call whenever your connected device receives a message. The webhook payload includes the sender number, message type, content, and device ID.
Always respond with a 200 status code quickly to acknowledge receipt. Process messages asynchronously if your logic takes time.
from flask import Flask, request, jsonify
import requests
import os
app = Flask(__name__)
API_KEY = os.environ.get("QUACKAPI_API_KEY")
API_URL = "https://quackapi.com/v1/messages/send"
@app.route("/webhook/whatsapp", methods=["POST"])
def webhook():
data = request.json
event = data.get("event")
sender = data.get("from")
message = data.get("message", {})
device_id = data.get("deviceId")
if event == "message.received" and message.get("type") == "text":
content = message.get("content", "").strip().lower()
handle_command(device_id, sender, content)
return jsonify({"received": True}), 200Building a Command Handler
Route incoming messages to the appropriate handler based on keywords. This pattern makes it easy to add new commands as your chatbot grows. Each command maps to a specific response or action.
def handle_command(device_id, sender, content):
if content in ["help", "?"]:
reply = (
"Available commands:\n"
"1. *pricing* - View our plans\n"
"2. *hours* - Business hours\n"
"3. *menu* - Show main menu\n"
"4. *help* - Show this message"
)
elif content == "pricing":
reply = (
"Our Plans:\n\n"
"Starter: $9/month - 3 devices\n"
"Professional: $29/month - 10 devices\n"
"Enterprise: $79/month - Unlimited\n\n"
"Visit our website to sign up!"
)
elif content == "hours":
reply = (
"Business Hours:\n"
"Monday - Friday: 9AM - 6PM\n"
"Saturday: 10AM - 2PM\n"
"Sunday: Closed"
)
elif content == "menu":
reply = show_menu()
else:
reply = "I didn't understand that. Type *help* to see available commands."
send_reply(device_id, sender, reply)Sending Auto-Replies
Use the QuackAPI API to send replies back to the user. This function handles the HTTP request with proper authentication headers and error handling.
def send_reply(device_id, to, message):
headers = {
"Content-Type": "application/json",
"x-api-key": API_KEY
}
payload = {
"deviceId": device_id,
"to": to,
"content": message,
"type": "text"
}
try:
response = requests.post(API_URL, json=payload, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Failed to send reply: {e}")
return NoneAdding a Menu System
A menu system gives users a structured way to interact with your chatbot. Present numbered options that users can select by replying with the corresponding number or keyword.
def show_menu():
return (
"Welcome to QuackAPI Support!\n\n"
"Please choose an option:\n"
"1. View Pricing\n"
"2. Business Hours\n"
"3. Technical Support\n"
"4. Talk to a Human\n\n"
"Reply with the number or keyword."
)Deploying Your Chatbot
Deploy your Flask chatbot to a cloud platform like Heroku, Railway, or any VPS. Make sure your server is accessible via HTTPS, as QuackAPI requires a secure webhook URL.
Set the QUACKAPI_API_KEY environment variable on your hosting platform. Configure the webhook URL in your QuackAPI device settings to point to your deployed endpoint, for example https://your-app.com/webhook/whatsapp.
For production, consider using Gunicorn as your WSGI server and adding rate limiting to prevent abuse of your webhook endpoint.
# Run with Gunicorn for production
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app