WhatsApp bot

Test this app for free
73
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
Get full code

Created: | Last Updated:

A good starting place for a WhatsApp bot app

Introduction to the WhatsApp Bot 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
    

    

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.

    
                  

Step 6: Test Your Bot

        

Send a message to your Twilio WhatsApp Sandbox number. You should receive a welcome message in response.

    

requirements.txt:
flask
gunicorn
twilio
werkzeug==3.0.1`

Technologies

WhatsApp WhatsApp