A Python and Flask webhook on Meta's WhatsApp Cloud API that answers messages automatically. It checks Meta's signature on every call, ignores repeated webhooks, and reads its replies from a JSON file.
Browser simulation: nothing is sent to WhatsApp. It uses the same rules.json as the real bot, so the replies match.
/webhook, signed with your app secret."""WhatsApp auto-reply bot built with Flask and Meta's WhatsApp Cloud API."""
import hashlib
import hmac
import json
import logging
import os
from collections import OrderedDict
from pathlib import Path
import requests
from flask import Flask, abort, request
PUNCTUATION = ".,!?;:'\"()[]{}-_/\\|।…"
SEEN_LIMIT = 1000
RULES_PATH = Path(__file__).with_name("rules.json")
log = logging.getLogger("whatsapp-bot")
def normalise(text):
"""Lowercase the text and turn punctuation into spaces."""
cleaned = text.lower().translate({ord(c): " " for c in PUNCTUATION})
return f" {' '.join(cleaned.split())} "
def choose_reply(text, config):
"""Return the reply of the first rule with a keyword in the message."""
message = normalise(text)
for rule in config["rules"]:
if any(f" {keyword} " in message for keyword in rule["keywords"]):
return rule["reply"]
return config["fallback"]
def signature_is_valid(secret, body, header):
"""Check that a webhook call was really signed by Meta."""
if not header or not header.startswith("sha256="):
return False
expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
return hmac.compare_digest(header[len("sha256="):], expected)
def incoming_messages(payload):
"""Yield every message in a webhook payload."""
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
yield from change.get("value", {}).get("messages", [])
def create_app(settings=None, send=None):
settings = settings or {
"verify_token": os.environ["VERIFY_TOKEN"],
"app_secret": os.environ["APP_SECRET"],
"access_token": os.environ["ACCESS_TOKEN"],
"phone_number_id": os.environ["PHONE_NUMBER_ID"],
"graph_version": os.environ.get("GRAPH_VERSION", "v23.0"),
}
config = json.loads(RULES_PATH.read_text(encoding="utf-8"))
seen = OrderedDict()
app = Flask(__name__)
def send_text(to, body):
response = requests.post(
f"https://graph.facebook.com/{settings['graph_version']}"
f"/{settings['phone_number_id']}/messages",
headers={"Authorization": f"Bearer {settings['access_token']}"},
json={
"messaging_product": "whatsapp",
"to": to,
"type": "text",
"text": {"body": body},
},
timeout=5,
)
response.raise_for_status()
deliver = send or send_text
def first_time(message_id):
"""Meta can repeat a webhook, so answer each message only once."""
if message_id in seen:
return False
seen[message_id] = True
if len(seen) > SEEN_LIMIT:
seen.popitem(last=False)
return True
@app.get("/")
def health():
return {"status": "ok"}
@app.get("/webhook")
def verify():
token_ok = hmac.compare_digest(
request.args.get("hub.verify_token", ""), settings["verify_token"]
)
if request.args.get("hub.mode") == "subscribe" and token_ok:
return request.args.get("hub.challenge", ""), 200
abort(403)
@app.post("/webhook")
def receive():
body = request.get_data()
header = request.headers.get("X-Hub-Signature-256")
if not signature_is_valid(settings["app_secret"], body, header):
abort(403)
for message in incoming_messages(json.loads(body)):
if not first_time(message.get("id")):
continue
if message.get("type") == "text":
reply = choose_reply(message["text"]["body"], config)
else:
reply = config["non_text"]
try:
deliver(message["from"], reply)
except requests.RequestException as error:
# Status codes only: request details contain the access token.
status = getattr(error.response, "status_code", "no response")
log.error("Could not send reply: %s", status)
return "", 200
return app
if __name__ == "__main__":
create_app().run(port=int(os.environ.get("PORT", 5000)))
{
"fallback": "Sorry, I didn't catch that. Reply *menu* to see what I can help with.",
"non_text": "I can only read text messages for now. Reply *menu* to see what I can help with.",
"rules": [
{
"id": "greeting",
"keywords": ["hi", "hello", "hey", "namaste", "नमस्ते"],
"reply": "Namaste! 🙏 I'm Prabin's auto-reply bot.\n\nReply with a number:\n1. Projects\n2. GitHub\n3. Contact\n4. About Prabin"
},
{
"id": "menu",
"keywords": ["menu", "help", "options"],
"reply": "Reply with a number:\n1. Projects\n2. GitHub\n3. Contact\n4. About Prabin"
},
{
"id": "projects",
"keywords": ["1", "project", "projects", "work", "portfolio"],
"reply": "Selected work:\n• Login and signup page with full validation\n• This WhatsApp auto-reply bot\n\nSee them at https://prabinban.com.np/#work"
},
{
"id": "github",
"keywords": ["2", "github", "code", "repo"],
"reply": "Find Prabin's code here: https://github.com/ggpukar/pukarban"
},
{
"id": "contact",
"keywords": ["3", "contact", "email", "hire", "mail"],
"reply": "You can email Prabin at [email protected]"
},
{
"id": "about",
"keywords": ["4", "about", "who", "prabin"],
"reply": "Prabin Ban is a student developer in Bhaktapur, Nepal, who builds apps, bots and strategy work."
},
{
"id": "thanks",
"keywords": ["thanks", "thank", "dhanyabad", "धन्यवाद"],
"reply": "You're welcome! 🙏"
}
]
}
Download: app.py · rules.json · test_app.py · requirements.txt · .env.example · README.md