by Lazy Sloth
Create & Build Any WhatsApp Bot Free Template
import os
from flask import Flask, render_template, request
from twilio.rest import Client
from gunicorn.app.base import BaseApplication
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')
if not account_sid or not auth_token:
return "Twilio credentials are not set. Please set them in the Env Secrets tab.", 200
Frequently Asked Questions
What are some potential business applications for this WhatsApp bot template?
This WhatsApp bot template offers a versatile foundation for various business applications. Some potential uses include: - Customer support: Automate responses to common inquiries - Appointment scheduling: Allow customers to book appointments via WhatsApp - Order tracking: Provide real-time updates on order status - Lead generation: Capture and qualify leads through conversational interactions - Product recommendations: Offer personalized product suggestions based on user preferences
How can this WhatsApp bot template improve customer engagement?
The WhatsApp bot template can significantly enhance customer engagement by: - Providing 24/7 availability for customer inquiries - Offering instant responses, reducing wait times - Personalizing interactions based on user data - Streamlining processes like bookings or purchases - Sending proactive notifications about promotions or updates
What industries could benefit most from implementing this WhatsApp bot?
While the WhatsApp bot template is versatile, some industries that could particularly benefit include: - E-commerce: For order updates, product inquiries, and customer support - Healthcare: For appointment reminders, basic health queries, and medication adherence - Hospitality: For bookings, check-ins, and concierge services - Financial services: For account inquiries, transaction alerts, and basic financial advice - Education: For course information, enrollment processes, and student support
How can I extend the functionality of this WhatsApp bot template to handle more complex interactions?
To extend the functionality of the WhatsApp bot template, you can modify the wa_hello()
function in main.py
. Here's an example of how you could add basic intent recognition:
```python @app.route("/wa", methods=['POST']) def wa_hello(): # ... (existing code)
message_body = request.form.get("Body", "").lower()
if "order status" in message_body:
response = "Your order is currently being processed. It will be shipped within 2 business days."
elif "product info" in message_body:
response = "We offer a wide range of products. Please visit our website for more information."
else:
response = "Welcome to our WhatsApp Bot! How can I assist you today?"
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 modification allows the bot to provide different responses based on the content of the incoming message.
Can I integrate this WhatsApp bot template with a database to store user interactions?
Yes, you can integrate the WhatsApp bot template with a database to store user interactions. Here's a basic example using SQLite:
First, add sqlite3
to your imports in main.py
:
python
import sqlite3
Then, add a function to initialize the database:
```python def init_db(): conn = sqlite3.connect('interactions.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS interactions (id INTEGER PRIMARY KEY, user_number TEXT, message TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''') conn.commit() conn.close()
init_db() # Call this function when the app starts ```
Finally, modify the wa_hello()
function to log interactions:
```python @app.route("/wa", methods=['POST']) def wa_hello(): # ... (existing code)
message_body = request.form.get("Body", "")
# Log the interaction
conn = sqlite3.connect('interactions.db')
c = conn.cursor()
c.execute("INSERT INTO interactions (user_number, message) VALUES (?, ?)", (from_number, message_body))
conn.commit()
conn.close()
# ... (rest of the function)
```
This modification will store each incoming message in an SQLite database, allowing you to review and analyze user interactions over time.
Created: | Last Updated:
Introduction to the WhatsApp Bot Creation Template
This template provides a starting point for creating a WhatsApp bot using Twilio's API. The bot will send a welcome message to users who interact with it via WhatsApp. The template includes a Flask web application, which handles incoming requests and sends messages using Twilio.
Clicking Start with this Template
To get started with the WhatsApp Bot template, click the "Start with this Template" button.
Initial Setup
This template requires setting up environment secrets for Twilio credentials. Follow these steps to obtain and set the required environment secrets:
1. **Set up Twilio Account** - If you haven't already, sign up for a Twilio account at https://www.twilio.com.
2. **Get Twilio Credentials** - Navigate to the Twilio Console to find your Account SID and Auth Token.
3. **Set Environment Variables** - In the Lazy Builder, go to the Environment Secrets tab. - Add the following environment secrets: - `TWILIO_ACCOUNT_SID`: Your Twilio Account SID. - `TWILIO_AUTH_TOKEN`: Your Twilio Auth Token.
Test
Press the "Test" button to deploy the app. The Lazy CLI will handle the deployment process.
Using the App
Once the app is deployed, navigate to the provided server link to access the setup guide. The guide will help you ensure that your Twilio credentials are correctly set.
Integrating the App
To integrate the WhatsApp bot with Twilio, follow these steps:
1. **Configure Twilio WhatsApp Sandbox** - In the Twilio Console, navigate to the WhatsApp Sandbox and set up your sandbox number.
2. **Set Webhook URL**
- 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.
3. **Test Your Bot** - Send a message to your Twilio WhatsApp Sandbox number. You should receive a welcome message in response.
Sample Code
Here is the sample code provided in the template:
`main.py:
import os
from flask import Flask, render_template, request
from twilio.rest import Client
from gunicorn.app.base import BaseApplication
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')
if not account_sid or not auth_token:
return "Twilio credentials are not set. Please set them in the Env Secrets tab.", 200
client = Client(account_sid, auth_token)
from_number = request.form.get("From")
to_number = request.form.get("To")
# Send welcome message
try:
client.messages.create(
body="Welcome to our WhatsApp Bot!",
from_=to_number,
to=from_number
)
except Exception as e:
print(f"Error sending message: {str(e)}")
return "", 200
class StandaloneApplication(BaseApplication):
def init(self, app, options=None):
self.application = app
self.options = options or {}
super().init()
def load_config(self):
config = {
key: value
for key, value in self.options.items()
if key in self.cfg.settings and value is not None
}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if name == "main":
options = {"bind": "%s:%s" % ("0.0.0.0", "8080"), "workers": 4, "loglevel": "info", "accesslog": "-", "timeout": 600}
StandaloneApplication(app, options).run()
index.html:
WhatsApp Bot Setup Guide
Step 1: Set up Twilio Account
If you haven't already, sign up for a Twilio account at https://www.twilio.com.
Step 2: Get Twilio Credentials
Once you have a Twilio account, navigate to the Twilio Console to find your Account SID and Auth Token.
Step 3: Set Environment Variables
Set the following environment variables in the Env Secrets tab:
- TWILIO_ACCOUNT_SID
- TWILIO_AUTH_TOKEN
Current status:
TWILIO_ACCOUNT_SID: {% if twilio_account_sid is not none %}Set{% else %}Not Set{% endif %}
TWILIO_AUTH_TOKEN: {% if twilio_auth_token is not none %}Set{% else %}Not Set{% endif %}
Step 4: Configure Twilio WhatsApp Sandbox
In the Twilio Console, navigate to the WhatsApp Sandbox and set up your sandbox number.
Step 5: Set Webhook URL
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.