visit
The first step is to get access to use the WhatsApp API use this
When you send your first message to that number you will be assigned a unique channel id, but 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. If you already installed a virtual environment skip step 1.
sudo apt install python-virtualenv
sudo python2 -m pip install virtualenv
py -2 -m pip install virtualenv
python3 -m venv whatsappbot
py -3 -m venv whatsappbot
. whatsappbot/bin/activate
whatsappbot\Scripts\activate
pip install Flask messagebird requests gunicorn jinja2 werkzeug urllib3
Add the following code in the bot.py file to make an application that prints “Hello bot” save the file and close:
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, edit your bot.py file with the following code and I’m going to explain how it works.
import jsonfrom 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 = (
“//conversations.messagebird.com/v1/conversations/"
+ conversation_id
+ “/messages”
)
headersList = {
“Authorization”: “AccessKey MESSAGEBIRD_ACCESS_KEY“,
“Content-Type”: “application/json”,
}
payload = json.dumps({“type”: “text”, “content”: {“text”: message_text}})
response = requests.request(“POST”, reqUrl, data=payload, headers=headersList)
return jsonify({“status”: “ok”, “response”: response.text})
if __name__ == ‘__main__’:
app.run()
If you do not have ngrok on your machine install it from
flask run
ngrok http 5000
import requests
reqUrl = “//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”:”//your-domain.ngrok.io/webhook"
})
response = requests.request(“POST”, reqUrl, data=payload, headers=headersList)
print(response.text)
Inside the Procfile add.
web: gunicorn — bind 0.0.0.0:$PORT app:app
flask==2.0.2
Jinja2==3.0.3
gunicorn==20.1.0
requests==2.27.1
urllib3==1.26.8
werkzeug==2.0.3
messagebird==2.0.0
python-3.9.10
import json
from flask import Flask, jsonify, request
import requests
from os import environ
MESSAGEBIRD_ACCESS_KEY = environ[“MESSAGEBIRD_ACCESS_KEY”]
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 = (“//conversations.messagebird.com/v1/conversations/" + conversation_id + “/messages”)headersList = {“Authorization”: “AccessKey “ + MESSAGEBIRD_ACCESS_KEY, “Content-Type”: “application/json”,}
payload = json.dumps({“type”: “text”, “content”: {“text”: message_text}})
response = requests.request(“POST”, reqUrl, data=payload, headers=headersList)
return jsonify({“status”: “ok”, “response”: response.text})
if __name__ == ‘__main__’:
app.run()
heroku login
heroku create
heroku config:set MESSAGEBIRD_ACCESS_KEY=your-actual-api-key-from-the-messagebird-dashboard
git push heroku main
heroku ps:scale web=1
import requests
reqUrl = “//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”:”//your-domain.herokuapp.com/webhook"
})
response = requests.request(“POST”, reqUrl, data=payload, headers=headersList)
print(response.text)
That’s it you now have a WhatsApp bot for more information and to enhance your bot read the
Find me on
Previously published