This guide will walk you through the process of deploying a WhatsApp bot using the Meta Cloud API with pure Python, and Flask particularly. The app will also integrate webhook events to receive messages in real-time and use OpenAI to generate AI responses-
- A Meta developer account — If you don’t have one, you can create a Meta developer account here.
- A business app — If you don't have one, you can learn to create a business app here. If you don't see an option to create a business app, select Other > Next > Business.
- Overview & Setup: Get started with the Meta API here.
- Locate Your Bots: The bots can be found here.
- WhatsApp API Documentation: official documentation.
- Helpful Guide: Here's a Python-based guide for sending messages.
- API Docs for Sending Messages: Check out this documentation.
- Make sure WhatsApp is added to your App.
- You begin with a test number that you can use to send messages to up to 5 numbers.
- Go to API Setup and locate the test number from which you will be sending messages.
- Here, you can also add numbers to send messages to. Enter your own WhatsApp number.
- You will receive a code on your phone via WhatsApp to verify your number.
- Obtain a 24-hour access token from the API access section.
- It will show an example of how to send messages using a
curl
command which can be send from the terminal or with a tool like Postman. - Let's convert that into a Python function with the request library.
- Create a
.env
files based onexample.env
and update the required variables. - You will receive a "Hello World" message (Expect a 60-120 second delay for the message).
Creating an access that works longer then 24 hours
- Create a system user at the Meta Business account level.
- On the System Users page, configure the assets for your System User, assigning your WhatsApp app with full control. Don't forget to click the Save Changes button.
- Now click
Generate new token
and select the app, and then choose how long the access token will be valid. You can choose 60 days or never expire. - Select all the permissions, as I was running into errors when I only selected the WhatsApp ones.
- Confirm and copy the access token.
Now we have to find the following information on the App Dashboard:
- APP_ID: "<YOUR-WHATSAPP-BUSINESS-APP_ID>" (Found at App Dashboard)
- APP_SECRET: "<YOUR-WHATSAPP-BUSINESS-APP_SECRET>" (Found at App Dashboard)
- RECIPIENT_WAID: "" (This is your WhatsApp ID, i.e., phone number. Make sure it is added to the account as shown in the example test message.)
- VERSION: "v18.0" (The latest version of the Meta Graph API)
- ACCESS_TOKEN: "" (Created in the previous step)
You can only send a template type message as your first message to a user. That's why you have to send a reply first before we continue.
In this section we'll deploy a Python-based WhatsApp bot to an Azure Web App! By deploying the bot to the cloud using Azure we'll allow it to be accessible from anywhere. Although we are using Azure in this repository, you can achieve similar results using other cloud platforms, such as AWS or Google Cloud Platform.
In this section, we will guide you through setting up an Azure account and deploying a web app using the Deployment Center. Azure provides a comprehensive platform for deploying and managing your applications in the cloud.
Follow these steps to set up your Azure account and deploy your WhatsApp bot:
-
Sign up for an Azure account: If you don't already have an account, sign up for a free Azure account at https://azure.microsoft.com. New users are eligible for a $200 credit, which you can use to explore and experiment with Azure services.
-
Create a Resource Group: A resource group helps you organize and manage resources based on their lifecycle and their relationship to each other. In the Azure Portal, create a new resource group called
Deploy-Whatsapp-Bot
. -
Create an App Service: An App Service is a fully managed platform for building, deploying, and scaling your web apps. In the Azure Portal, create a new App Service and associate it with the
Deploy-Whatsapp-Bot
resource group. Set publish toCode
, and select the correctPython
version and yourRegion
(There is a new region called 'Mexico central' which we will use). Finally, select an appropriate App Service Plan based on your needs. There is a free plan available. -
Deploy via GitHub repo: In the Azure Deployment Center, connect your GitHub repository to your App Service. This will enable continuous integration and deployment, so your app will be automatically updated whenever you push changes to the specified branch. Make sure to select the correct branch.
Once you've completed these steps, your Azure account will be set up and ready for deploying your WhatsApp bot. In the next sections, we will discuss how to update the workflow file, the Python file, and the WhatsApp API connection to complete the deployment process.
In the Azure portal, navigate to your App Service, and then go to Configuration > General Settings. Under the "Startup command" field, enter the following command and click "Save" to apply the changes.
startup.txt
In the Azure portal, navigate to your App Service, and then go to Configuration > Application settings. Add the following keys and their respective values. Make sure to replace the placeholder values with your actual keys and secrets. Click "Save" to apply the changes.
OPENAI_API_KEY
: Your OpenAI API keyACCESS_TOKEN
: Key valueAPP_SECRET
: Key valueAPP_ID
: Key valueRECIPIENT_WAID
: Key valueVERSION
: Key valuePHONE_NUMBER_ID
: Key valueVERIFY_TOKEN
: Key value
In this section, we'll go over updating the GitHub Actions workflow file to enable automated deployments to your Azure App Service. We'll configure the workflow to log in to Azure CLI using a service principal and update the Azure credentials in GitHub Actions secrets.
Follow these steps to update the workflow file:
- Log in to Azure CLI using service principal: In your GitHub Actions workflow file, add the following code snippet to enable logging in to the Azure CLI using a service principal:
- name: Log in to Azure CLI using service principal
uses: azure/login@v1
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}
- Create the service principal: To create a service principal, run the following command in the Azure Cloud Shell, replacing
<YOUR-SUBSCRIPTION-ID>
with your actual subscription ID (Home > Subscriptions). This command will output a JSON object containing the necessary credentials, such asclientId
,clientSecret
,subscriptionId
, andtenantId
.
az ad sp create-for-rbac --name "myWhatsAppBotApp" --role contributor --scopes /subscriptions/<YOUR-SUBSCRIPTION-ID> --sdk-auth
- Update Azure credentials in GitHub Actions secrets: In your GitHub repository, navigate to the "Settings" tab and then click on "Secrets and variables > Actions" in the left sidebar. Create a new repository secret named
AZURE_CREDENTIALS
and paste the JSON object you obtained in the previous step as its value.
With these updates in place, your GitHub Actions workflow is now configured to automatically deploy your WhatsApp bot to Azure whenever you push changes to the specified branch. In the next sections, we will discuss updating the Python file and the WhatsApp API connection.
In the Meta App Dashboard, go to WhatsApp > Configuration, then click the Edit button.
- In the Edit webhook's callback URL popup, enter the URL provided by the ngrok agent to expose your application to the internet in the Callback URL field, with /webhook at the end (i.e. https://.azurewebsites.net/webhook).
- Enter a verification token. This string is set up by you when you create your webhook endpoint. You can pick any string you like. Make sure to update this in your
VERIFY_TOKEN
environment variable. - After you add a webhook to WhatsApp, WhatsApp will submit a validation post request to your application. Confirm your localhost app receives the validation get request and logs
WEBHOOK_VERIFIED
in the terminal. - Back to the Configuration page, click Manage.
- On the Webhook fields popup, click Subscribe to the messages field. Tip: You can subscribe to multiple fields.
- If your Flask app and Azure Web App are running, you can click on "Test" next to messages to test the subscription. If you recieve a message your webhook is set up correctly.
First text the phone number that sent you the 'Quick Start, Hello World' Message template.
- Add this number to your WhatsApp app contacts and then send a message to this number.
- Confirm your localhost app receives a message and logs both headers and body in the terminal.
- Test if the bot replies back to you.
- You have now succesfully integrated the bot! 🎉
Anytime you configure the Webhooks product in your App Dashboard, we'll send a GET request to your endpoint URL. Verification requests include the following query string parameters, appended to the end of your endpoint URL. They will look something like this:
GET https://www.your-clever-domain-name.com/webhook?
hub.mode=subscribe&
hub.challenge=1158201444&
hub.verify_token=12345
The verify_token, 12345
in the case of this example, is a string that you can pick. It doesn't matter what it is as long as you store in the VERIFY_TOKEN
environment variable.
Whenever your endpoint receives a verification request, it must:
- Verify that the hub.verify_token value matches the string you set in the Verify Token field when you configure the Webhooks product in your App Dashboard (you haven't set up this token string yet).