Build a WhatsApp Chatbot With Python, Flask, and Messagebird by Marshall Chikari

Posted January 15, 2023 / Tags: , , , , / 3 Comments

In this tutorial, I will show you how to build a chatbot using the Messagebird API for WhatsApp and the Flask framework for Python.

The first step is to get access to the WhatsApp API. Use this link to sign up and navigate to WhatsApp on the dashboard to follow the instructions on setting up your own number to work with the API. For now, we can use the Messagebird sandbox to test our bot.

Connect your phone to the sandbox from the Messagebird dashboard and click on WhatsApp then WhatsApp sandbox. When you send your first message to that number, you will be assigned a unique channel id. When you are verified to use your own number, you will also get your own channel id which we will use to communicate with our bot.

Step 1: Install Virtual Environment

  • To Install on Linux: sudo apt install python-virtualenv
  • To Install on Mac: sudo python2 -m pip install virtualenv
  • To Install on Windows: py -2 -m pip install virtualenv

Step 2: Create an Environment Create a directory or folder where you will create your environment using a version of python on your machine. I’m going to use python3 in this tutorial.

  • In Linux and MacOS: In your terminal navigate to the directory you created in step 2 and enter the following command replacing whatsappbot with your own name. python3 -m venv whatsappbot
  • In Windows: py -3 -m venv whatsappbot

Step 3: Activate the Environment

  • In Linux and MacOS: . whatsappbot/bin/activate
  • In Windows: whatsappbot\Scripts\activate

Step 4: Install Flask Enter the following command: pip install Flask messagebird requests gunicorn jinja2 werkzeug urllib3

Open your project folder and create a file in the root folder outside the venv directory.

Add the following code in the file to make an application that prints “Hello bot” and save the file:

from flask import Flask
app = Flask(__name__)

@app.route('/bot', methods=['POST'])
def bot():
   #webhook logic

if __name__ == '__main__':

Set the FLASK_APP environment variable with the following command in the terminal.

  • On Mac and Linux: export
  • On Windows: setx FLASK_APP “”

The first thing we need to do in our chatbot is to obtain the message entered by the user. This message comes in the payload of the POST request.

import json
from flask import Flask, jsonify, request
import requests

app = Flask(__name__)

def hello():
  return "Bot is alive!"

@app.route('/webhook', methods=['POST'])
def bot():
   data = request.json
   message = data["message"]["content"]["text"].lower()   

  if (message == "hello"):
       return conversation_reply(data["conversation"]["id"],"How are you")   if (message == "bye"):
       return conversation_reply(data["conversation"]["id"],"Good bye!”)

def conversation_reply(conversation_id, message_text):
reqUrl = (
+ conversation_id
+ “/messages”

  payload = {“content”: {“text”: message_text}}

  headers = {
    “Content-Type”: “application/json”,
    “Authorization”: “AccessKey YOUR_ACCESS_KEY”

  response =, json=payload, headers=headers)

  return jsonify(response.json())

In the above code, we are importing the necessary libraries and creating a flask app. We are defining two routes, one for the root of the application and the other for the webhook. In the webhook route, we are parsing the JSON data sent by the user and extracting the message. We are then checking if the message is “hello” or “bye” and responding accordingly. We are also defining a function conversation_reply that sends a message to the user using the Messagebird API.

You will need to replace YOUR_ACCESS_KEY with your actual access key obtained from the Messagebird dashboard.

Finally, you can run the application using the command flask run and test it by sending a message to the number connected to the sandbox.

This is just a basic example, you can add more functionality and improve the chatbot as per your requirements.

To test the chatbot on localhost, you can use ngrok. If you don’t have ngrok installed, you can download it from here. Once you have ngrok, run your flask app with the command flask run and in another terminal window, run ngrok http 5000. This will provide you with a public URL that you can use as the webhook URL for the Messagebird API.

You can also create a separate file to run the following command, that will create the webhook, replace the access key, channel id, and URL with the ones you got from running ngrok, and don’t forget to add /webhook to the end of the URL:

import requests
reqUrl = “"
headersList = {
 “Authorization”: “AccessKey MESSAGEBIRD_ACCESS_KEY”,
 “Content-Type”: “application/json” 
payload = json.dumps({
“events”:[“message.created”, “message.updated”],
response = requests.request(“POST”, reqUrl, data=payload, headers=headersList)

You can then test your bot by sending messages to the sandbox number.

You can also deploy your WhatsApp bot to Heroku. To do this, you need to add a Procfile, requirements.txt, and runtime.txt file to your root folder. Inside the Procfile, add web: gunicorn --bind$PORT app:app. In the requirements.txt file, add the necessary dependencies, replacing with the actual versions you are using. In the runtime.txt file, add the version of Python you are using.

You will also need to create environment variables to hide your MESSAGEBIRD API key in the production environment. Update your code inside to import the MESSAGEBIRD_ACCESS_KEY from the environment variable.

Finally, run the command `git push heroku master` to deploy the application to Heroku and set the environment variable with the command

Leave a Comment:

Your email address will not be published. Required fields are marked *

Sage H H says:

Hey it’s Sage! Here is the free AI tool that AUTOMATICALLY writes copy to drive TRAFFIC and CALLS. Just use this proven SEO fill-in-the-blanks templates and the AI will do the rest:

1. “best [YOUR SERVICE] in [YOUR CITY]”
2. “[YOUR SERVICE] [YOUR CITY] pricing”
3. “[YOUR SERVICE] near me” –

Actually the AI can write ANYTHING you want.
Get the FREE TRIAL while it lasts!

Go to:

Marry K K says:

Optimize your website with our free SEO audit at Identify SEO issues, increase your site’s reach, and multiply your conversions. Just a click away from a better SEO strategy.

Mike B B says:

Want to improve your website’s ranking? Visit for a free SEO audit. Maximize efficiency, amplify web presence, and attract quality traffic. Get immediate insights without any time investment.

Popular Posts
    No posts found