Equip Chatbot for your Facebook page using Python
Published:
Although there are a lot of product available in supporting develop messenger chatbot, as a programmer it is limited compare to programming yourself. In this blog, I will write a chatbot for Facebook page using Python programming language. We will use Flask to create a webhook app, Messenger API for message interaction, and ngrok for forwarding local host.
Prerequisites
Before getting started, make sure you have:
- A Facebook Page and a Facebook Developer Account.
- Python installed.
- ngrok.exe downloaded.
Step 1. Setting up a Facebook App
- Go to Facebook Developers and create a new app.
- Add the Messenger product to your app.
- Under Messenger API Settings section, connect and generate a Page Access Token. We will input this token to our script later.
- Subscribe to required events such as messages.
Step 2. Writing webhook app using Flask
Create a new Python file (app.py
) and paste my simple Flask app as below:
from flask import Flask, request
VERIFY_TOKEN = "LHKishandsome"
app = Flask(__name__)
@app.route('/')
def home():
return "Successful running"
@app.route('/webhook', methods=['GET'])
def verify_webhook():
if request.args.get("hub.verify_token") == VERIFY_TOKEN:
return request.args.get("hub.challenge")
return "Verification token mismatch", 403
if __name__ == '__main__':
app.run(port=5000)
Step 3. Connecting the Webhook to Facebook App
The VERIFY_TOKEN
is the string set by your own in Configure webhooks section, Messenger API setting, as shown in the Figure below.
As you may notice, there is one more field we need to fill in, Callback URL. As Flask app only run on local host, we need to use ngrok here to forward that local host. Start your flask app simply by run you python script and verify that the app is running by visiting http://localhost:5000
.
Download ngrok.exe and unzip file into the same directory with app.py
.
Sign up for a account for free at ngrok dashboard and get to token under Authtokens section.
Open the terminal in the app directory and run ngrok http 5000
.
At this point, you can get the url address that forward to our local host, which Flask app running on. Copy that url and paste to Callback URL in Configure webhooks section, Messenger API setting.
Press Verify and save to connect our webhook to Messenger API. \
Step 4. Handling incoming messages
Add these below function to process the input message from User and send response back.
Here is the simple logic for process the input message, you can modify that by your own.
def generate_response(user_message):
if 'hello' in user_message:
return 'Hi there, I am your assistant.'
elif 'bye' in user_message:
return 'Good bye, wish you a happy day.'
else:
return 'I do not got it.'
Message then will be sent back to users every time you send message to the Page you added in at Step 1.
def send_message(recipient_id, message_text):
url = f"https://graph.facebook.com/v15.0/me/messages?access_token={PAGE_ACCESS_TOKEN}"
headers = {"Content-Type": "application/json"}
payload = {
"recipient": {"id": recipient_id},
"message": {"text": message_text}
}
response = requests.post(url, headers=headers, json=payload)
return response.json()
@app.route('/webhook', methods=['POST'])
def handle_message():
data = request.get_json()
for entry in data.get('entry', []):
for message_event in entry.get('messaging', []):
sender_id = message_event['sender']['id']
if 'message' in message_event and 'is_echo' not in message_event['message']:
user_message = message_event['message'].get('text', '')
response = generate_response(user_message)
send_message(sender_id, response)
return "OK", 200
Now, your chatbot is on. Congras and let’s have fun with it.
Step 5. Deploying / Hosting the Chatbot
So far, you have successful built chatbot for you Facebook Page with your own message processing. However, you need to run the chatbot and ngrok script to maintain the chatbot. Here, you have several platform for hosting your Chatbot script (Heroku, Railway, or Render, …) for free hosting.
Check this blog and pick the best one for you Best Platforms to Host Python Apps
Remember to replace the ngrok URL with the deployed server URL in Facebook webhook settings.
Leave a Comment