Skip to content

Building a WhatsApp Automation Bot with Flask and Twilio

A clear walkthrough of the moving parts behind a WhatsApp bot: the webhook, message handling, state, and how to test locally before going live.

Muhammad Yasir

@YasirAwan4831

Published 2 min read

Building a WhatsApp Automation Bot with Flask and Twilio

On this page

Messaging apps are where many customers already are, which makes WhatsApp a natural place to automate repetitive conversations: order status, appointment reminders, FAQs and notifications. The architecture is simpler than it looks.

How the pieces fit together

A WhatsApp bot built on Twilio has three parts: the messaging API that receives and sends messages, a webhook (a public URL on your server that Twilio calls for every incoming message), and your application logic that decides what to reply.

  • Twilio WhatsApp API delivers messages to and from users.

  • Flask exposes the webhook endpoint and runs your logic.

  • A database (SQLite is enough to start) stores conversations and user state.

A minimal webhook

Twilio sends incoming messages as form data. Your endpoint reads the text, decides on a reply and returns TwiML, a small XML response Twilio turns into a WhatsApp message.

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.post("/whatsapp")
def incoming():
    text = request.form.get("Body", "").strip().lower()
    sender = request.form.get("From", "")

    reply = MessagingResponse()
    if text in {"hi", "hello"}:
        reply.message("Hello! Type 'status' to check your order.")
    elif text == "status":
        reply.message(lookup_status(sender))
    else:
        reply.message("Sorry, I did not understand. Type 'hi' to start.")
    return str(reply)

Testing locally

Twilio must reach your webhook over the public internet, but your laptop is not public. A tunnelling tool such as Ngrok gives your local Flask server a temporary public URL that you paste into the Twilio console. This lets you test the full loop without deploying anything.

  1. Start Flask locally.

  2. Start the tunnel and copy the HTTPS URL it prints.

  3. Set that URL plus your route (for example /whatsapp) as the incoming-message webhook.

  4. Send a message from your phone and watch the request arrive in your Flask logs.

Adding state

Real conversations have steps: asking for a name, then an order number, then confirming. Store the current step per phone number in your database so each incoming message can be handled in context. Keep the states few and explicit; a small state table is easier to debug than clever branching.

Where AI fits in

Rule-based replies handle predictable requests well. For free-form questions, you can pass the message to a language model with a tightly scoped prompt and a fallback to a human when the model is unsure. Start with rules, then add AI only where rules fall short.

Things to get right before real users

  • Validate that requests really come from Twilio using its request signature.

  • Respect opt-in and messaging policies for WhatsApp business messaging.

  • Log every message and error so problems are visible.

  • Never hard-code credentials; load them from environment variables.

Enjoyed this article?

Share it with someone who might find it useful.