Posted January 15, 2023 / Tags: flask, heroku, messagebird, python, whatsapp / No 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
sudo apt install python-virtualenv
sudo python2 -m pip install virtualenv
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.
whatsappbot
with your own name. python3 -m venv whatsappbot
py -3 -m venv whatsappbot
Step 3: Activate the Environment
. whatsappbot/bin/activate
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 bot.py in the root folder outside the venv directory.
Add the following code in the bot.py 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__':
app.run()
Set the FLASK_APP environment variable with the following command in the terminal.
export FLASK_APP=bot.py
setx FLASK_APP “bot.py”
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__)
@app.route("/")
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 = (
"https://conversations.messagebird.com/v1/conversations/"
+ conversation_id
+ “/messages”
)
payload = {“content”: {“text”: message_text}}
headers = {
“Content-Type”: “application/json”,
“Authorization”: “AccessKey YOUR_ACCESS_KEY”
}
response = requests.post(reqUrl, 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 = “https://conversations.messagebird.com/v1/webhooks"
headersList = {
“Authorization”: “AccessKey MESSAGEBIRD_ACCESS_KEY”,
“Content-Type”: “application/json”
}
payload = json.dumps({
“events”:[“message.created”, “message.updated”],
“channelId”: “YOUR_CHANNEL_ID_FROM_THE_WHATSAPP_SANDBOX”,
“url”:”https://your-domain.ngrok.io/webhook"
})
response = requests.request(“POST”, reqUrl, data=payload, headers=headersList)
print(response.text)
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 0.0.0.0:$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 bot.py 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
No comments