Creating a WhatsApp Chatbot: A Step-by-Step Guide using Python
This guide will walk you through the process of creating a WhatsApp chatbot using Python. We'll be using the Twilio API for WhatsApp integration and Flask for handling webhooks.
Prerequisites
- Python 3.7 or higher installed
- A Twilio account (sign up at https://www.twilio.com/)
- ngrok installed for local testing (download from https://ngrok.com/)
Step 1: Set Up Your Development Environment
-
Create a new directory for your project:
mkdir whatsapp-chatbot
cd whatsapp-chatbot
-
Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
-
Install required packages:
pip install flask twilio python-dotenv
Step 2: Setting Up a Twilio Account and Connecting to WhatsApp
To connect your WhatsApp account to Twilio, follow these steps:
- Create a Twilio Account:
- Go to the Twilio website and sign up for a new account.
- Verify your email address and phone number as part of the registration process.
- Access the Twilio Console:
- Sign in to your Twilio account and navigate to the Console.
- Once logged in, navigate to the Twilio Console. This is your main dashboard where you can manage your Twilio services.
- Get Your Twilio Credentials:
- In the Console, locate your Account SID and Auth Token. These credentials are essential for integrating Twilio with your application.
- Note these down; you will need to add them to your
.env file later.
- Set Up WhatsApp Sandbox:
- In the left sidebar of the Console, click on "Messaging" and then "Try it out" > "Send a WhatsApp message".
- Follow the on-screen instructions to connect your WhatsApp account to Twilio's Sandbox. This involves sending a specific message from your WhatsApp to a Twilio-provided number to activate the sandbox for your account.
- Configure the Sandbox:
- After connecting, you’ll see the Sandbox settings page. Here, you can configure how Twilio handles incoming messages.
- For local development, you will use ngrok to create a public URL that forwards requests to your local Flask server.
- Update Webhook URL:
- Copy the HTTPS URL provided by ngrok (e.g.,
https://1234abcd.ngrok.io).
- In the Twilio Console, under "Messaging" > "WhatsApp Sandbox Settings", enter your ngrok URL followed by
/webhook in the "When a message comes in" field (e.g., https://1234abcd.ngrok.io/webhook).
- Save the changes.
Now your Twilio account should be connected to WhatsApp, and you can start receiving and responding to messages using your chatbot.
Step 3: Create Your Flask Application