Introduction
We have previously prepared a tutorial on creating a Facebook Messenger Bot using the Dialogflow integration. Here, we will learn how to create a Facebook Messenger Bot using the Facebook Graph API.
In the following tutorial, we will learn how we can create a Facebook messenger bot to get the different types of responses such as text, generic, buttons, list, media, and feedback response from the bot. Furthermore, we will also learn how we will be able to get the files that we share with the bot in chat on the server-side of our computer.
Bạn đang xem: Create Facebook Messenger Bot Using Python Tutorial with Examples
Here we learn how we can get the following types of responses from the bot:
- Text
- Image
- Buttons
- Videos
- Feedback
- Generic
- Quick reply
Steps to create a Facebook Chatbot
Step 1: Create Facebook Page.
First of all, we need to create a Facebook page. Open https://www.facebook.com/ and click on more buttons and then select “page”.
Step 2: Create Facebook App.
To connect the Dialogflow agent with Facebook Page, we’ll need a Facebook app. For that, go to https://developers.facebook.com/apps/ and click on “Create App”.
Select the “Business” option for your app and click on the “Next” button.
Provide “App Display Name” and “App Contact Email”, and hit the “Create App” button. You’ll have to go through a security check to create an app.
Step 3: Connect Facebook Page to the App.
Our Facebook app is created, and now we need to connect our Facebook page to the app. For that, we need to generate a Page Access Token.
Clicking on “Add Product” on the left sidebar will open a page with many options. Under Add, A Product section, select “Set Up” for Messenger.
Now, select the “Add or Remove Pages”, it will open a new tab and from there select the page you want to connect to, or you can create a new page directly.
Now click on “Continue as your name”.
Here we will be using the “chat_bot” page which we created earlier, select the page and click on the “Next” button.
Provide the permissions to complete the process, and click on “Done”.
Now click on “Ok” and then you have successfully linked your app to the Facebook page.
Step 4: Activate Facebook App.
Now, the last step in the configuration is to Activate the Facebook App. To do that, browse to Basic Settings of the page (from the left sidebar) and provide “Privacy Policy URL”. Make sure that you have selected the app that you created earlier.
Another mandatory setting is selecting a category. Clicking on “Choose a Category” will open up a popup where we can select the appropriate category of our app.
Minimum required settings of the App are in place. Click on “Save Changes” to save the settings.
Step 5: Create Flask App.
Use this command to install the flask library
Xem thêm : Bài hát tiếng Trung: Chúng ta không giống nhau 我们不一样
pip install flask
Add below code for the basic flask app.
from flask import Flask app = Flask(__name__) if __name__ ==’__main__’: app.run()
Now copy the page access token and past it in this code.
Step 6: Generate a token.
To generate the token, click on “Generate token” and click on “I understand” then click on the “copy” button.
Now paste the token as shown in the below code for the Flask app.
from flask import Flask, request import requests app = Flask(__name__) # This is page access token that you get from facebook developer console. PAGE_ACCESS_TOKEN = ‘<Your Page Access Token>’ # This is API key for facebook messenger. API = “https://graph.facebook.com/LATEST-API-VERSION/me/messages?access_token=”+PAGE_ACCESS_TOKEN
Step 7: Setup Webhook in Facebook App.
We need to set up a webhook in Facebook App which will communicate with the flask app.
Create an endpoint in the flask app for verifying the token as shown below.
@app.route(“/”, methods=[‘GET’]) def fbverify(): if request.args.get(“hub.mode”) == “subscribe” and request.args.get(“hub.challenge”): if not request.args.get(“hub.verify_token”)== “<Your Verify token>”: return “Verification token missmatch”, 403 return request.args[‘hub.challenge’], 200 return “Hello world”, 200
To set up a webhook, open the Settings page of the Facebook App and click on the “Add Callback URL” button under the “Webhooks” section.
To copy “Callback URL” from your host URL also you can use your Ngrok URL, “Verify Token” copy from your code that we do in the next step then click on verify and save button.
String in “Verify token” and in flask code the request.args.get(“hub.verify_token”) should be matched.
For Subscription Fields, Click on the “Add Subscriptions” button and it will open a pop-up.
Here, “messages” and “messaging_postbacks” are sufficient to get started with the basic bot. So, we select only those 2 for now. And click on the “Save” button.
Step 8: Create webhook responses using the Flask app.
Now we are going to create different types of responses using flask webhook. For that, we create an endpoint to read user input, and then we send responses based on user input.
The first response we are going to create is when the user says ‘hi’ our webhook sends a “hello” response.
@app.route(“/”, methods=[‘POST’]) def fbwebhook(): data = request.get_json() print(data) try: # Read messages from facebook messanger. message = data[‘entry’][0][‘messaging’][0][‘message’] sender_id = data[‘entry’][0][‘messaging’][0][‘sender’][‘id’] if message[‘text’] == “hi”: request_body = { “recipient”: { “id”: sender_id }, “message”: { “text”: “hello, world!” } } response = requests.post(API, json=request_body).json() return response
After that, we need to go to the Facebook home page. You can check out the list of created “Page”. Please select your created “Page” and click on “Messenger” symbol.
Then, if we type ‘hi’ and our webhook will send a “hello” response.
Xem thêm : Top 9+ loa bluetooth có thẻ nhớ, USB nghe nhạc hay, siêu đỉnh
For sending a quick reply using the below code.
elif message[‘text’] == “quick”: request_body = { “recipient”: { “id”: sender_id }, “messaging_type”: “RESPONSE”, “message”: { “text”: “Pick a color:”, “quick_replies”: [ { “content_type”: “text”, “title”: “Red”, “payload”: “<POSTBACK_PAYLOAD>”, “image_url”: “http://example.com/img/red.png” }, { “content_type”: “text”, “title”: “Green”, “payload”: “<POSTBACK_PAYLOAD>”, “image_url”: “http://example.com/img/green.png” } ] } } response = requests.post(API, json=request_body).json() return response
To send a generic response.
if message[‘text’] == “generic”: request_body = { “recipient”: { “id”: sender_id }, “message”: { “attachment”: { “type”: “template”, “payload”: { “template_type”: “generic”, “elements”: [ { “title”: “Welcome!”, “image_url”: “https://raw.githubusercontent.com/fbsamples/original-coast-clothing/main/public/styles/male-work.jpg”, “subtitle”: “We have the right hat for everyone.”, “default_action”: { “type”: “web_url”, “url”: “https://www.originalcoastclothing.com/”, “webview_height_ratio”: “tall”, }, “buttons”: [ { “type”: “web_url”, “url”: “https://www.originalcoastclothing.com/”, “title”: “View Website” }, { “type”: “postback”, “title”: “Start Chatting”, “payload”: “DEVELOPER_DEFINED_PAYLOAD” } ] }, { “title”: “Welcome!”, “image_url”: “https://raw.githubusercontent.com/fbsamples/original-coast-clothing/main/public/styles/male-work.jpg”, “subtitle”: “We have the right hat for everyone.”, “default_action”: { “type”: “web_url”, “url”: “https://www.originalcoastclothing.com/”, “webview_height_ratio”: “tall”, }, “buttons”: [ { “type”: “web_url”, “url”: “https://www.originalcoastclothing.com/”, “title”: “View Website” }, { “type”: “postback”, “title”: “Start Chatting”, “payload”: “DEVELOPER_DEFINED_PAYLOAD” } ] } ] } } } } response = requests.post(API, json=request_body).json() return response
For sending a response with buttons.
elif message[‘text’] == “button”: request_body = { “recipient”: { “id”: sender_id }, “message”: { “attachment”: { “type”: “template”, “payload”: { “template_type”: “button”, “text”: “What do you want to do next?”, “buttons”: [ { “type”: “web_url”, “url”: “https://www.messenger.com”, “title”: “Visit Messenger” }, { “type”: “web_url”, “url”: “https://www.youtube.com”, “title”: “Visit Youtube” }, ] } } } } response = requests.post(API, json=request_body).json() return response
For sending receipt responses.
elif message[‘text’] == “receipt”: request_body = { “recipient”: { “id”: “<PSID>” }, “message”: { “attachment”: { “type”: “template”, “payload”: { “template_type”: “receipt”, “recipient_name”: “Stephane Crozatier”, “order_number”: “12345678902”, “currency”: “USD”, “payment_method”: “Visa 2345”, “order_url”: “http://originalcoastclothing.com/order?order_id=123456”, “timestamp”: “1428444852”, “address”: { “street_1”: “1 Hacker Way”, “street_2”: “”, “city”: “Menlo Park”, “postal_code”: “94025”, “state”: “CA”, “country”: “US” }, “summary”: { “subtotal”: 75.00, “shipping_cost”: 4.95, “total_tax”: 6.19, “total_cost”: 56.14 }, “adjustments”: [ { “name”: “New Customer Discount”, “amount”: 20 }, { “name”: “$10 Off Coupon”, “amount”: 10 } ], “elements”: [ { “title”: “Classic White T-Shirt”, “subtitle”: “100% Soft and Luxurious Cotton”, “quantity”: 2, “price”: 50, “currency”: “USD”, “image_url”: “http://originalcoastclothing.com/img/whiteshirt.png” }, { “title”: “Classic Gray T-Shirt”, “subtitle”: “100% Soft and Luxurious Cotton”, “quantity”: 1, “price”: 25, “currency”: “USD”, “image_url”: “http://originalcoastclothing.com/img/grayshirt.png” } ] } } } } response = requests.post(API, json=request_body).json() return response
For sending media like images and videos we can use the below code.
elif message[‘text’] == “media”: request_body = { “recipient”: { “id”: sender_id }, “message”: { “attachment”: { “type”: “image”, “payload”: { “url”: “http://www.messenger-rocks.com/image.jpg”, “is_reusable”: True } } } } response = requests.post(API, json=request_body).json() return response
Step 9: Save the file on the server sent by the user.
We can store files on the server side that the user sent on chat. We can save images, videos, pdf, and many more.
For that, we need the URL of the file and we download that file on the server. Below is the code for getting a response using webhook and extracting the URL and download file on the server.
except: # Here we are store the file to our server who send by user from facebook messanger. try: mess = data[‘entry’][0][‘messaging’][0][‘message’][‘attachments’][0][‘payload’][‘url’] print(“for url->”,mess) json_path = requests.get(mess) filename = mess.split(‘?’)[0].split(‘/’)[-1] open(filename, ‘wb’).write(json_path.content) except: print(“Noot Found->”) return ‘ok’
By following the above tutorial, we have learned how we can send various messages and files from the Facebook chatbot. Then, how we can upload the different types of files that we need to send to the chatbot. You can find the full integration code in our Github Repository.
Do let us know if you face any issues in setting up or using the script. We would be happy to help! Contact us or post your query in the comments.
Also, check out our other tutorials Telegram Bot, Slack Bot, WhatsApp Bot, and Discord Bot to learn how to build a chatbot on different platforms.
Also, check out our other tutorials to learn how to build a ChatGPT chatbot on different platforms.
WhatsApp with ChatGPT: Build An Automated, AI-Powered WhatsApp Chatbot With ChatGPT Using Flask
Facebook Messenger with ChatGPT: Build An Automated, AI-Powered Facebook Messenger Chatbot With ChatGPT Using Flask
Slack Chatbot with ChatGPT: Build An Automated, AI-Powered Slack Chatbot With ChatGPT Using Flask
Telegram Bot with ChatGPT: Build An Automated, AI-Powered Telegram Chatbot With ChatGPT Using Flask
Dialogflow ES API: How To Integrate Dialogflow ES API To Add NLP Capabilities In Your Chatbot?
Dialogflow ES with Twilio: Setup Twilio Integration On Your Server To Connect Google Dialogflow ES
Nguồn: https://sigma.edu.vn
Danh mục: Công Nghệ