
WhatsApp is one of the most popular messaging platforms in the world, making it a prime candidate for automation through bots. Whether you’re looking to create a basic rule-based bot or an advanced AI-driven conversational assistant, Python provides the tools to make it happen.
In this blog, we’ll explore two approaches: a basic “not smart” bot and an AI-powered smart bot. This guide will also include keywords like “WhatsApp bot Python tutorial,” “GitHub,” “free,” “Twilio,” “API,” “Django,” “source code,” “Telegram,” and more to ensure it ranks well on search engines.
1. Creating a Basic Rule-Based WhatsApp Bot
The simplest form of a WhatsApp bot responds to specific keywords or phrases with predefined messages. This approach uses basic logic and is ideal for straightforward use cases, like answering FAQs or providing menu options.
Steps to Create a Rule-Based Bot
- Set Up Twilio API for WhatsApp:
- Sign up for a Twilio account and enable the WhatsApp sandbox.
- Note down your Account SID, Auth Token, and the Twilio sandbox phone number.
- Write the Bot Logic: Use Python along with Flask to build a webhook that responds to incoming messages.
Code Example
from twilio.rest import Client
from flask import Flask, request, jsonify
ACCOUNT_SID = 'your_account_sid_here'
AUTH_TOKEN = 'your_auth_token_here'
WHATSAPP_NUMBER = 'whatsapp:+14155238886'
MY_WHATSAPP_NUMBER = 'whatsapp:+your_number_here'
client = Client(ACCOUNT_SID, AUTH_TOKEN)
app = Flask(__name__)
@app.route('/whatsapp', methods=['POST'])
def whatsapp_bot():
incoming_message = request.form.get('Body')
sender_number = request.form.get('From')
if incoming_message.lower() == 'hello':
response_message = "Hi there! How can I help you today?"
elif incoming_message.lower() == 'help':
response_message = "Here are some commands you can use:\n- 'Hello': Greet the bot\n- 'Help': Get this help message\n- 'Bye': End the chat"
else:
response_message = "I'm sorry, I didn't understand that. Type 'Help' for a list of commands."
client.messages.create(
from_=WHATSAPP_NUMBER,
body=response_message,
to=sender_number
)
return jsonify({"status": "success"}), 200
if __name__ == '__main__':
app.run(debug=True)
Key Features
- Simplicity: The bot uses basic
if-else
conditions to respond. - Quick Setup: Requires minimal configuration and coding.
Limitations
- No Context Awareness: It cannot maintain a conversation or understand context.
- Rigid Responses: Only responds to predefined inputs.
This approach is great for small projects or as an introduction to creating a WhatsApp bot using Python, Flask, and Twilio. You can even find examples and inspiration on GitHub or explore “WhatsApp bot free” options to expand your knowledge.
2. Building an AI-Driven WhatsApp Bot
For a smarter bot that understands user intent and provides context-aware responses, you can integrate AI capabilities using tools like OpenAI’s GPT models. These bots can engage in dynamic conversations and improve user experience significantly.
Steps to Create an AI-Powered Bot
- Integrate OpenAI GPT API:
- Sign up for an OpenAI account and obtain your API key.
- Modify the Bot to Use AI: Replace the rule-based logic with AI-generated responses using the OpenAI GPT API.
Code Example
import openai
from twilio.rest import Client
from flask import Flask, request, jsonify
ACCOUNT_SID = 'your_account_sid_here'
AUTH_TOKEN = 'your_auth_token_here'
WHATSAPP_NUMBER = 'whatsapp:+14155238886'
MY_WHATSAPP_NUMBER = 'whatsapp:+your_number_here'
openai.api_key = 'your_openai_api_key_here'
client = Client(ACCOUNT_SID, AUTH_TOKEN)
app = Flask(__name__)
@app.route('/whatsapp', methods=['POST'])
def whatsapp_bot():
incoming_message = request.form.get('Body')
sender_number = request.form.get('From')
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=f"Respond to this message: {incoming_message}",
max_tokens=100
)
response_message = response['choices'][0]['text'].strip()
except Exception as e:
response_message = "Oops, something went wrong. Please try again later."
client.messages.create(
from_=WHATSAPP_NUMBER,
body=response_message,
to=sender_number
)
return jsonify({"status": "success"}), 200
if __name__ == '__main__':
app.run(debug=True)
Key Features
- Dynamic Responses: The bot generates replies based on the context of the conversation.
- Natural Language Understanding: Users can interact in natural language without needing specific keywords.
- Scalability: Can handle complex queries and provide personalized responses.
Benefits of AI-Driven Bots
- Enhanced User Experience: Feels more like chatting with a human.
- Context Awareness: Can remember past interactions within the conversation.
- Multilingual Support: AI models can handle multiple languages seamlessly.
This advanced bot integrates seamlessly with platforms like Twilio, Django, or even Telegram for enhanced functionality. Look for “WhatsApp bot GitHub” repositories to find AI-driven examples or explore “WhatsApp chatbot free” solutions for inspiration.
Challenges
- Cost: AI APIs like OpenAI’s GPT come with usage costs.
- Complexity: Requires proper error handling and integration.
Conclusion
Whether you need a basic or advanced WhatsApp bot depends on your specific use case. A rule-based bot is great for simple automation, while an AI-powered bot is ideal for dynamic and engaging user experiences. With Python, you have the flexibility to build both and scale as your needs evolve. You can find many useful resources on GitHub, learn from free tutorials, and even experiment with integrating bots into platforms like Telegram. By starting small and scaling smartly, you can create a WhatsApp bot that meets your requirements and stands out in functionality.
0 Comments