Welcome back to TECHNICAL AI! In today's fast-paced digital economy, customer service is everything. If you run a small business, a freelance agency, or an online store, you know how difficult it is to reply to every single customer inquiry instantly. Missing a message often means missing a sale.
What if you could have a virtual assistant working for you 24/7, greeting customers, sharing your product catalog, and answering frequently asked questions—all automatically? In this comprehensive, advanced tutorial, we are going to build a highly professional WhatsApp Auto-Responder Bot using Python, Flask, and the Twilio API.
š Why Use the Twilio API for WhatsApp?
There are many "hacky" ways to automate WhatsApp using browser automation (like Selenium). However, those methods are unstable, require your browser to remain open, and can easily get your number banned. Professional developers use Official APIs.
- Enterprise Stability: The Twilio API connects directly to WhatsApp's backend. It is 100% stable and does not rely on your phone's battery or internet connection.
- Webhooks Integration: We can use Flask (a Python web framework) to listen for incoming messages in real-time and trigger instant programmatic responses.
- Scalability: Whether you receive 10 messages a day or 10,000, this API architecture can handle it effortlessly without crashing.
š¦ Step 1: Installing Requirements
To start building this business automation tool, we need to install the required Python libraries. You will need Flask to create the local web server and Twilio to communicate with the WhatsApp API.
Create a requirements.txt file and paste the following dependencies, then run pip install -r requirements.txt in your terminal.
Flask==2.3.2 twilio==8.2.1 requests==2.31.0
š» Step 2: The WhatsApp Auto-Responder Script
Below is the premium Python code for our chatbot. This script creates a webhook endpoint. When a customer sends a message to your Twilio WhatsApp number, Twilio forwards that message to this script. The script then reads the keyword (like "Menu" or "Hours") and sends the appropriate pre-written response.
Create a file named app.py and copy the code below into it.
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
# Initialize the Flask Application
app = Flask(__name__)
print("š TECHNICAL AI - WhatsApp Business Bot is Running...")
@app.route("/whatsapp", methods=['POST'])
def wa_reply():
# Capture the incoming message and convert it to lowercase
incoming_msg = request.values.get('Body', '').lower()
# Initialize the Twilio Messaging Response object
resp = MessagingResponse()
msg = resp.message()
# --- BOT LOGIC & KEYWORD ROUTING ---
if 'menu' in incoming_msg or 'services' in incoming_msg:
msg.body("š ️ *Our Premium Services:*\n\n1️⃣ Python Automation Scripts\n2️⃣ Telegram/WhatsApp Bot Creation\n3️⃣ VPS Server Setup\n\nš *Reply with a number (e.g., 1) for details!*")
elif '1' in incoming_msg:
msg.body("š *Python Automation:*\nWe build custom automation tools to save your time. Pricing starts at $50. Contact the admin to discuss your project.")
elif 'time' in incoming_msg or 'hours' in incoming_msg:
msg.body("š *Business Hours:*\n\nMonday - Friday: 10:00 AM to 7:00 PM\nSaturday & Sunday: Closed\n\nLeave your query and we will get back to you during working hours.")
elif 'contact' in incoming_msg or 'admin' in incoming_msg:
msg.body("š *Contact Support:*\nYou can reach our live support via our official website: https://technical-rex.blogspot.com or email us directly.")
else:
# Default Welcome Message
msg.body("š Welcome to *TECHNICAL AI* Official Business Chat!\n\nI am your virtual assistant. How can I help you grow your business today?\n\nš Type *Menu* to see our services.\nš Type *Hours* to check our timings.\nš Type *Contact* to talk to a human.")
# Return the formatted response to Twilio
return str(resp)
if __name__ == "__main__":
# Run the Flask app on port 5000
app.run(port=5000, debug=True)
š§ Deep Dive: How the Webhook Logic Works
Copying code is easy, but understanding the architecture turns you into an advanced developer. Let's break down the mechanics of this script:
1. The Flask Routing (@app.route)
We are creating a local web server. The @app.route("/whatsapp", methods=['POST']) line tells Python to listen for incoming data exactly at this URL endpoint. When a customer sends a WhatsApp message, Twilio sends a secure HTTP POST request to this exact route containing the user's phone number and message body.
2. Keyword Parsing
The code extracts the message using request.values.get('Body') and immediately converts it to lowercase using .lower(). This is a critical step! It ensures that whether the user types "MENU", "Menu", or "menu", the bot will still recognize the command and reply correctly.
3. Twilio Markup Language (TwiML)
We cannot just return plain text. Twilio requires responses to be formatted in TwiML (an XML-based language). The MessagingResponse() object automatically formats our Python strings into the exact XML structure that the WhatsApp API requires to deliver the message back to the user's phone.
š Connecting the Bot to the Internet (Ngrok)
Right now, this script runs locally on your computer (localhost:5000). Twilio cannot send messages to your local computer directly. To bridge this gap, developers use a free tool called Ngrok.
- Download and run Ngrok on your machine.
- Type
ngrok http 5000in your terminal. - Ngrok will give you a public, secure HTTPS link (e.g.,
https://your-link.ngrok.io). - Paste this link into your Twilio Console under the WhatsApp Sandbox "When a message comes in" field, adding
/whatsappat the end.
And boom! Your local Python script is now live and talking to the global WhatsApp network.
šÆ Conclusion & Customization
You have just built an enterprise-grade customer service bot. You can customize the if/elif statements in the code to add as many products, prices, or FAQs as you need for your specific business. If you run a restaurant, you can add a food menu. If you are a freelancer, you can add your portfolio links.
Automation is the key to scaling your business. By letting Python handle the repetitive queries, you can focus on what actually matters—growing your brand and completing projects.
If you need help setting up the Twilio API, or if you want a custom AI-powered bot integrated with ChatGPT, feel free to reach out via our Contact Us page. Don't forget to bookmark TECHNICAL AI for daily Python scripts and automation tutorials!
