Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Can I Make a Program to Automatically Reply to WhatsApp Texts Using Python?
WhatsApp has become an essential part of our daily communication. Sometimes we're too busy to reply to messages promptly. Python can help us create an automated WhatsApp response system using the Twilio API. This tutorial shows you how to build such a program step by step.
Prerequisites
Before starting, ensure you have:
- Python installed on your system
- A Twilio account (free tier available)
- Basic knowledge of Python and Flask
Step 1: Installing Required Libraries
First, install the necessary Python libraries. Open your terminal and run:
pip install twilio flask requests
Step 2: Setting Up Twilio Account
Create a free Twilio account at https://www.twilio.com/. After signing up, you'll receive:
- Account SID ? Your unique account identifier
- Auth Token ? Your authentication token
Keep these credentials secure as they'll be needed in your code.
Step 3: Configuring WhatsApp Sandbox
Twilio provides a WhatsApp sandbox for testing. In your Twilio console:
- Navigate to the "Messaging" section
- Click on "Try it out" ? "Send a WhatsApp message"
- Follow the instructions to join the sandbox
- Note down your Twilio WhatsApp number
Step 4: Building the Auto-Reply Program
Here's the complete Python code for the WhatsApp auto-reply system:
from twilio.rest import Client
from flask import Flask, request
import requests
# Twilio credentials
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
client = Client(account_sid, auth_token)
app = Flask(__name__)
@app.route("/whatsapp", methods=['POST'])
def reply_whatsapp():
# Get incoming message
incoming_msg = request.values.get('Body', '').lower()
sender_number = request.values.get('From', '')
# Generate response based on message content
if 'hello' in incoming_msg or 'hi' in incoming_msg:
response_msg = "Hello! Thanks for your message. How can I help you today?"
elif 'help' in incoming_msg:
response_msg = "I'm an automated assistant. Send 'info' for more details or 'advice' for random advice."
elif 'advice' in incoming_msg:
try:
resp = requests.get('https://api.adviceslip.com/advice')
advice = resp.json()['slip']['advice']
response_msg = f"Here's some advice: {advice}"
except:
response_msg = "Sorry, I couldn't fetch advice right now."
else:
response_msg = f"Thanks for your message: '{incoming_msg}'. I'll get back to you soon!"
# Send response
message = client.messages.create(
from_='whatsapp:+14155238886', # Twilio sandbox number
body=response_msg,
to=sender_number
)
return '', 200
if __name__ == '__main__':
app.run(debug=True, port=5000)
Code Breakdown
Imports and Setup: We import Twilio client, Flask framework, and requests library for API calls.
Route Handler: The /whatsapp route processes incoming messages. It extracts the message body and sender information.
Response Logic: The program checks message content and generates appropriate responses. It can handle greetings, help requests, and provide random advice.
Message Sending: Uses Twilio client to send the response back to the sender's WhatsApp number.
Step 5: Making Your App Accessible
For Twilio to send webhooks to your Flask app, it needs to be accessible from the internet. For testing, use ngrok:
# Install ngrok first, then run: ngrok http 5000
Copy the HTTPS URL provided by ngrok and configure it in your Twilio WhatsApp sandbox webhook settings.
Step 6: Testing the Program
To test your auto-reply system:
- Run your Python script:
python your_filename.py - Start ngrok:
ngrok http 5000 - Update your Twilio webhook URL with the ngrok HTTPS URL +
/whatsapp - Send a WhatsApp message to your Twilio number
- Receive an automated response!
Customization Ideas
You can enhance your auto-reply system by:
- Adding keyword-based responses
- Integrating with databases for personalized replies
- Implementing business hours logic
- Adding media responses (images, documents)
Important Considerations
Remember that:
- WhatsApp has rate limits for automated messages
- Always comply with WhatsApp's terms of service
- For production use, consider Twilio's verified WhatsApp Business API
Conclusion
You've successfully created a Python program that automatically replies to WhatsApp messages using Twilio's API. This foundation can be expanded with more sophisticated logic, database integration, and advanced features to create a powerful automated messaging system.
