WhatsApp Chatbot with Twilio and Python: In the competitive digital world of today, developers and businesses are consistently searching for creative ways to communicate more effectively with users. WhatsApp, having approximately 2+ billion active users, provides a great opportunity to connect with the audience on a platform where they spend most of their time. Integrating the powerful communication features of Twilio with the inherent flexibility of Python ensures the right foundation for developing responsive and smart WhatsApp chatbots.
In this guide, let us go through the user-friendly process of generating a WhatsApp chatbot with Twilio and Python. Using this guide, you will be able to create engaged automated conversations. These automated conversations are essentially helpful while managing customer inquiries, imparting information to the clients, or processing straightforward requests. Imagine converting one of the most famous messaging platforms into an automated channel of customer communication.
Advantages of Creating a WhatsApp Chatbot
Since this blog is focused on building a WhatsApp Chatbot with Twilio and Python, it involves understanding a lot of code. Before going straight to the codes, it is worthwhile to recognize the advantages of developing a robust WhatsApp chatbot:
- Access to Global Audience: Approximately 2+ billion users in 180+ countries utilize WhatsApp for daily communication.
- Improving Engagement: One of the most notable advantages of WhatsApp is its high open rate. Its open rate is as high as 98% compared to other channels like emails, which have an open rate of only 20%.
- Communicate Using Different Media: WhatsApp supports different media formats. You can easily receive images, location data, documents, and more.
- Comprehensive Encryption: WhatsApp is a well-protected platform with end-to-end encryption. Through this platform, you can communicate securely and comprehensively protect confidential information.
- 24/7 Availability: Ensure immediate responses to customers, irrespective of where you are.
- Cost Effectiveness: Minimize overhead in customer services, enhancing response times.
What Do You Need?
To understand the codes and steps mentioned in the blog, you need a few prerequisites mentioned as follows:
- Make sure that you have Python 3.6 or higher installed.
- You also need to have a Twilio account.
- You can proceed to the Twilio website (Twilio.com) and sign up for absolutely no cost.
- Pip package manager.
- Basic understanding and knowledge of the Flash web framework.
- A Uniform Resource Locator for your webhook, which can be accessed publicly.
- For development, we will use ngrok here.
- A valid phone number is enabled on WhatsApp.
Configuring Your WhatsApp Sandbox on Twilio
Before generating code, you need to make sure that your Twilio environment is up and running:
- Sign in to your Twilio account, and if you don’t have one, you can create one at the Twilio website.
- Now, proceed to enter the Twilio Console and enter the WhatsApp Sandbox.
- Complete the instructions to ensure the connection between your WhatsApp account and the Sandbox.
- Note down your Auth Token and Twilio Account SID. You will require these later on.
Developing Your WhatsApp Chatbot
1. Configuring Your Python Environment
Let us begin by creating a fresh project directory and establishing a virtual environment:
# Create a project directory
mkdir WhatsApp-chatbot
cd whatsapp-chatbot
# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate # On Windows, use venv\Scripts\activate
# Install required packages
pip install flask twilio python-dotenv
2. Developing the Flask Application
Now, let us proceed to creating a standard Flash application that can manage all incoming messages on WhatsApp simply:
# app.py
import os
from flask import Flask, request, Response
from twilio.twiml.messaging_response import MessagingResponse
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
app = Flask(__name__)
@app.route("/webhook", methods=["POST"])
def webhook():
# Get incoming message details
incoming_msg = request.values.get('Body', '').strip().lower()
sender = request.values.get('From', '')
# Create a response object
resp = MessagingResponse()
# Handle different user inputs
if 'hello' in incoming_msg:
resp.message("Hi there! I'm your WhatsApp bot. How can I help you today?")
elif 'help' in incoming_msg:
resp.message("I can assist with:\n- Product information\n- Business hours\n- Contact details\n\nJust ask me what you need!")
elif 'hours' in incoming_msg:
resp.message("We're open Monday-Friday, 9am-5pm.")
else:
resp.message("I didn't understand that. Try asking for 'help' to see what I can do.")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
3. Ensuring Accessibility of Your Webhook
To make Twilio capable of transferring all incoming WhatsApp messages to your applications, it is important to ensure public accessibility of your webhook. During the stage of development, you need to leverage ngrok:
# Install ngrok if you haven't already
# Then start it on the same port as your Flask app
ngrok http 5000
Now, closely observe the HTTPS uniform resource locator that ngrok gives (e.g., https://a1b2c3d4.ngrok.io). You must set up this URL in the WhatsApp Sandbox in your Twilio platform. It will be followed by the route that you have already defined. (e.g., https://a1b2c3d4.ngrok.io/webhook).
4. Improving Your Chatbot with Natural Language Processing
Let us make our chatbot more intelligent by adding a few NLP capabilities as shown below:
# Add this after your imports
from fuzzywuzzy import fuzz
import random
# Install with: pip install fuzzywuzzy
def process_message(message):
# Define some intents and their respective responses
intents = {
"greeting": ["hello", "hi", "hey", "howdy", "greetings"],
"farewell": ["bye", "goodbye", "see you", "later"],
"thanks": ["thank", "thanks", "appreciate", "grateful"],
"hours": ["hour", "open", "close", "time", "schedule"],
"products": ["product", "offer", "sell", "item"],
"price": ["price", "cost", "how much", "pricing"]
}
responses = {
"greeting": [
"Hello! How can I assist you today?",
"Hi there! What can I help you with?",
"Hey! What brings you here today?"
],
"farewell": [
"Goodbye! Feel free to message again if you need anything.",
"See you later! Have a great day!",
"Take care! I'm here if you need more help."
],
"thanks": [
"You're welcome! Is there anything else I can help with?",
"Glad I could help! Let me know if you need anything more.",
"My pleasure! Don't hesitate to reach out again."
],
"hours": [
"Our business hours are Monday-Friday, 9am-5pm.",
"We're open weekdays from 9am to 5pm.",
"You can visit us between 9am and 5pm, Monday through Friday."
],
"products": [
"We offer a range of digital solutions including website development, mobile apps, and AI integration.",
"Our product line includes software solutions for businesses of all sizes.",
"We specialize in custom software, mobile applications, and enterprise solutions."
],
"price": [
"Our pricing varies based on project requirements. Would you like to speak with a sales representative?",
"We offer custom quotes based on your specific needs. Can I collect some information about your project?",
"Pricing depends on features and scale. I'd be happy to connect you with our sales team for a quote."
]
}
# Find the best matching intent
best_match = None
highest_score = 0
for intent, phrases in intents.items():
for phrase in phrases:
score = fuzz.partial_ratio(message, phrase)
if score > highest_score and score > 70: # 70% match threshold
highest_score = score
best_match = intent
if best_match:
return random.choice(responses[best_match])
else:
return "I'm not sure I understand. Could you rephrase or ask
"hours": [
"Our business hours are Monday-Friday, 9am-5pm.",
"We're open weekdays from 9am to 5pm.",
"You can visit us between 9am and 5pm, Monday through Friday."
],
"products": [
"We offer a range of digital solutions including website development, mobile apps, and AI integration.",
"Our product line includes software solutions for businesses of all sizes.",
"We specialize in custom software, mobile applications, and enterprise solutions."
],
"price": [
"Our pricing varies based on project requirements. Would you like to speak with a sales representative?",
"We offer custom quotes based on your specific needs. Can I collect some information about your project?",
"Pricing depends on features and scale. I'd be happy to connect you with our sales team for a quote."
]
}
# Find the best matching intent
best_match = None
highest_score = 0
for intent, phrases in intents.items():
for phrase in phrases:
score = fuzz.partial_ratio(message, phrase)
if score > highest_score and score > 70: # 70% match threshold
highest_score = score
best_match = intent
if best_match:
return random.choice(responses[best_match])
else:
return "I'm not sure I understand. Could you rephrase or ask
Implementing Your WhatsApp Chatbot
For production, you must deploy the Flask application you have created for a web server. Here, you have options such as
- Heroku: Easy deployment with a free tier for small applications
- AWS Elastic Beanstalk: A Scalable option with AWS infrastructure
- Google Cloud Run: Serverless container deployment
- DigitalOcean App Platform: Simple deployment with predictable pricing
Irrespective of the platform you have selected, you need to make sure to
- Securely configure all the environment variables.
- Set up your Twilio webhook uniform resource locator to direct to your production endpoint.
- Execute logging and error handling correctly.
- You can also think about including a database to ensure storage of your conversation history.
Conclusion
So, this was it! You have just learned an easy way of developing a WhatsApp chatbot with Twilio and Python. Now, you can further work on this foundation and expand it with advanced features such as
- Incorporate databases to store important user details and the entire conversation history.
- Ensure connectivity with the external Application Programming Interface for real-time information (stock prices, weather, etc.)
- Deployment of more advanced NLP via libraries such as spaCy or sophisticated frameworks such as Rasa.
- Add capabilities for media responses, i.e., making the WhatsApp bot capable of sharing documents, images, or location sharing.
- Incorporate it with your operational CRM tool or other customer service solutions.
In an intensely connected world, the role of messaging cannot be overlooked in online communication. WhatsApp chatbots present themselves as a valuable solution for businesses looking to interact with customers on the platform where they come daily and spend a substantial amount of time. The integration of Python’s versatility and the robust API of Twilio ensures that deploying these solutions is easy, even for developers with less experience.
Begin small, prioritize solving particular user problems, and consistently fine-tune your bot depending on real-time conversation data. With more upgrades and integrations, you can easily make your WhatsApp chatbot an intrinsic part of your overall customer engagement strategy.