by davi
WhatsApp bot
import os
from flask import Flask, render_template, request
from twilio.rest import Client
from gunicorn.app.base import BaseApplication
from abilities import apply_sqlite_migrations
from models import db
app = Flask(__name__)
@app.route("/", methods=['GET'])
def home():
twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID', 'Not Set')
twilio_auth_token = os.environ.get('TWILIO_AUTH_TOKEN', 'Not Set')
return render_template('index.html',
twilio_account_sid=twilio_account_sid if twilio_account_sid != 'Not Set' else None,
twilio_auth_token=twilio_auth_token if twilio_auth_token != 'Not Set' else None)
@app.route("/wa", methods=['POST'])
def wa_hello():
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
Frequently Asked Questions
What are some potential business applications for this WhatsApp bot template?
This WhatsApp bot template offers versatile applications across various industries. Some potential use cases include: - Customer support: Automate responses to common inquiries - Appointment scheduling: Allow customers to book services via WhatsApp - Order tracking: Provide real-time updates on shipments - Lead generation: Capture and qualify leads through conversational interactions - Surveys and feedback collection: Gather customer insights effortlessly
The template's integration with a database allows for storing and retrieving information, making it suitable for more complex business processes.
How can this WhatsApp bot template improve customer engagement?
The WhatsApp bot template can significantly enhance customer engagement by: - Providing instant responses 24/7 - Offering a familiar and convenient communication channel - Personalizing interactions based on stored customer data - Streamlining processes like bookings or purchases - Sending proactive notifications or reminders
By leveraging the database functionality, businesses can create more personalized and context-aware conversations, leading to improved customer satisfaction and loyalty.
What industries could benefit most from implementing this WhatsApp bot template?
While the WhatsApp bot template is versatile, some industries that could particularly benefit include: - E-commerce: Order processing, product recommendations, and customer support - Healthcare: Appointment scheduling, medication reminders, and health tips - Hospitality: Reservations, concierge services, and guest feedback - Financial services: Account inquiries, transaction alerts, and loan applications - Education: Course information, assignment reminders, and student support
The template's database integration allows for storing and retrieving relevant information, making it adaptable to various industry-specific needs.
How can I extend the functionality of the WhatsApp bot template to handle more complex user interactions?
To handle more complex interactions, you can extend the wa_hello()
function in main.py
. Here's an example of how you might implement a simple command system:
```python @app.route("/wa", methods=['POST']) def wa_hello(): # ... existing code ...
message_body = request.form.get("Body", "").lower()
if message_body == "help":
response = "Available commands: help, info, status"
elif message_body == "info":
response = "This is a WhatsApp bot powered by Twilio and Flask."
elif message_body == "status":
response = "The system is operational."
else:
response = "Welcome to our WhatsApp Bot! Type 'help' for available commands."
try:
client.messages.create(
body=response,
from_=to_number,
to=from_number
)
except Exception as e:
print(f"Error sending message: {str(e)}")
return "", 200
```
This example adds basic command handling to the WhatsApp bot template, allowing for more interactive and dynamic conversations.
How can I use the database functionality in the WhatsApp bot template to store user information?
To store user information using the database functionality, you can create a model in models.py
and use it in your bot logic. Here's an example:
First, add a User model to models.py
:
```python class User(db.Model): id = db.Column(db.Integer, primary_key=True) phone_number = db.Column(db.String(20), unique=True, nullable=False) name = db.Column(db.String(100)) last_interaction = db.Column(db.DateTime)
def __repr__(self):
return f'<User {self.phone_number}>'
```
Then, in main.py
, you can use this model to store and retrieve user information:
```python from models import db, User from datetime import datetime
@app.route("/wa", methods=['POST']) def wa_hello(): # ... existing code ...
user = User.query.filter_by(phone_number=from_number).first()
if not user:
user = User(phone_number=from_number)
db.session.add(user)
user.last_interaction = datetime.utcnow()
db.session.commit()
# ... rest of your bot logic ...
```
This example demonstrates how to integrate database operations into the WhatsApp bot template, allowing you to store and update user information with each interaction.
Created: | Last Updated:
Here's a step-by-step guide for using the WhatsApp bot template with database integration:
Introduction
This template provides a starting point for creating a WhatsApp bot with database integration using Flask and Twilio. The bot will send a welcome message to users who interact with it.
Getting Started
- Click "Start with this Template" to begin using this template in the Lazy Builder interface.
Initial Setup
To use this template, you'll need to set up a Twilio account and configure some environment variables. Follow these steps:
-
Sign up for a Twilio account at https://www.twilio.com if you haven't already.
-
Once logged in, navigate to the Twilio Console to find your Account SID and Auth Token.
-
In the Lazy Builder interface, go to the "Env Secrets" tab and set the following environment variables:
TWILIO_ACCOUNT_SID
: Your Twilio Account SIDTWILIO_AUTH_TOKEN
: Your Twilio Auth Token
Test
After setting up the environment variables, click the "Test" button in the Lazy Builder interface to deploy your app.
Using the App
Once your app is deployed, you'll need to configure your Twilio WhatsApp Sandbox to use it:
-
In the Twilio Console, navigate to the WhatsApp Sandbox and set up your sandbox number.
-
In the Twilio WhatsApp Sandbox settings, set the "When a message comes in" webhook URL to:
https://your-app-url.com/wa
Replace "your-app-url.com" with the actual URL of your deployed app, which will be provided by Lazy after deployment. -
Test your bot by sending a message to your Twilio WhatsApp Sandbox number. You should receive a welcome message in response.
Integrating the App
This WhatsApp bot can be integrated with other services or expanded upon based on your needs. Here are some ideas:
- Add more complex message handling logic in the
wa_hello()
function. - Implement database operations using the SQLAlchemy models (you can add these in the
models.py
file). - Create additional routes and functions to handle different types of messages or commands.
Remember to update your Twilio webhook URL if you add new functionality that requires different endpoints.
By following these steps, you'll have a basic WhatsApp bot up and running with database integration, ready for further customization and development.
Here are 5 key business benefits for this WhatsApp bot template:
Template Benefits
-
Automated Customer Service - Businesses can use this bot to provide 24/7 automated customer support through WhatsApp, answering common questions and handling basic requests without human intervention.
-
Streamlined Communication - The template enables direct, instant messaging with customers on a platform they already use, improving engagement and response times.
-
Scalable Outreach - With WhatsApp's large user base, businesses can potentially reach billions of customers worldwide, making it an excellent tool for marketing and announcements.
-
Data Collection and Analysis - The integrated database allows for storing customer interactions, preferences, and behaviors, which can be analyzed to improve products, services, and marketing strategies.
-
Cost-Effective Operations - By automating responses and handling multiple conversations simultaneously, the bot can significantly reduce customer service costs compared to traditional phone or email support.