Sigma Academy

Sigma Academy

  • Home
  • Học Tiếng Anh
  • Học tiếng Nhật
  • Luyện thi Ielts
  • Giáo Dục
  • Tin tức
    • Bất động sản
    • Phong Thuỷ
    • Công Nghệ
    • Ẩm thực
    • Làm Đẹp
You are here: Home / Công Nghệ / Create Facebook Messenger Bot Using Python Tutorial with Examples

Create Facebook Messenger Bot Using Python Tutorial with Examples

06/10/2023 06/10/2023 Sigma Academy

Video facebook messenger chatbot python

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.

Có thể bạn quan tâm
  • Tổng hợp lý thuyết về phản ứng tỏa nhiệt và thu nhiệt – cân bằng Hoá học 10
  • Thay camera Samsung S9 Plus
  • Review Công Ty Phonecare có lừa đảo không?
  • Thiết kế biển quảng cáo trên Photoshop với 6 bước đơn giản
  • Hướng dẫn refresh website tự động trên Chrome

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 : Pantech Vega Secret Up ( Sky A900 ) White/Black

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 : Xiaomi Redmi 5 Plus, Redmi Note 5 và Redmi Note 5 Pro có gì khác?

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ệ

Bài viết liên quan

Hóa Đại Cương – HIỆU ỨNG NHIỆT CỦA CÁC QUÁ TRÌNH HÓA HỌC
Tổng hợp đầy đủ font chữ biển số xe máy, ô tô 2023
Extension Marketplace
Extension Marketplace
Nội lực là gì? Điểm giống nhau giữa nội lực và ngoại lực là gì?
Hướng dẫn cách thay ổ cứng laptop đơn giản trong một nốt nhạc
Automation Test Là Gì? Kỹ Năng Cần Có Của Một Automation Tester
Automation Test Là Gì? Kỹ Năng Cần Có Của Một Automation Tester
Cách chuyển hình ảnh thành vector trong Illustrator (AI) nhanh chóng
Cách chuyển hình ảnh thành vector trong Illustrator (AI) nhanh chóng
TẠI SAO GỌI NƯỚC NGA LÀ XỨ SỞ BẠCH DƯƠNG?
Hướng dẫn thiết lập cài đặt gốc trên HTC One M8
PHÂN BIỆT BLACK BOX TEST VÀ WHITE BOX TEST, SƠ LƯỢC MỘT SỐ KỸ THUẬT TRONG BLACK BOX TEST
PHÂN BIỆT BLACK BOX TEST VÀ WHITE BOX TEST, SƠ LƯỢC MỘT SỐ KỸ THUẬT TRONG BLACK BOX TEST

Chuyên mục: Công Nghệ

About Sigma Academy

Previous Post: « 25 bản vẽ phối cảnh nhà trệt mặt thụt mặt lồi ấn tượng ai cũng muốn sở hữu TIN223088
Next Post: Xe hybrid: Cấu tạo, ưu nhược điểm, lưu ý khi sử dụng »

Primary Sidebar

Bài viết nổi bật

Bảo vệ: Tổng hợp thông tin các ngành của Đại học Quốc gia Hà Nội

03/07/2024

TB Tuyển sinh Thạc Sĩ Chuyên ngành Khoa học Điều dưỡng – Khoá 3

27/06/2024

Thích ứng với chương trình lớp 10 mới: Đòi hỏi những thay đổi trong dạy và học

25/06/2024

Cập nhật nội dung & những thay đổi trong chương trình lớp 1 mới

Cập nhật nội dung & những thay đổi trong chương trình lớp 1 mới

24/06/2024

Giáo dục công dân lớp 9 – Giải bài tập sgk GDCD 9 ngắn nhất

24/06/2024

Các loại bằng thạc sĩ và cách phân biệt

24/06/2024

Giáo án Giáo dục địa phương lớp 6 năm 2023 – 2024 KHBD môn Giáo dục địa phương (Hà Nội, Hồ Chí Minh, Vĩnh Long, Thanh Hóa)

24/06/2024

[:vi]TOP CÁC TRƯỜNG ĐÀO TẠO NGÀNH KỸ THUẬT XÂY DỰNG CHẤT LƯỢNG[:]

[:vi]TOP CÁC TRƯỜNG ĐÀO TẠO NGÀNH KỸ THUẬT XÂY DỰNG CHẤT LƯỢNG[:]

24/06/2024

Thông báo tuyển sinh đào tạo Thạc sĩ Luật Khóa 37 (2023 - 2025)

Thông báo tuyển sinh đào tạo Thạc sĩ Luật Khóa 37 (2023 – 2025)

24/06/2024

Giải đáp về Chương trình Giáo dục Vinschool

24/06/2024

Ngành cơ điện tử: Học gì, học ở đâu và cơ hội nghề nghiệp

24/06/2024

3 nguyên tắc - 4 phương pháp giáo dục cảm xúc cho trẻ mầm non ba mẹ cần biết

3 nguyên tắc – 4 phương pháp giáo dục cảm xúc cho trẻ mầm non ba mẹ cần biết

24/06/2024

Ngành Logistics học trường nào sẽ dễ xin việc?

Ngành Logistics học trường nào sẽ dễ xin việc?

24/06/2024

Khoa Sau Đại học – Trường Đại học Mở Tp.HCM

24/06/2024

Chương trình liên kết quốc tế là gì? Hình thức liên kết phổ biến hiện nay

Chương trình liên kết quốc tế là gì? Hình thức liên kết phổ biến hiện nay

24/06/2024

Ngành An toàn thông tin

24/06/2024

Học thạc sĩ giáo dục tiểu học ở đâu? Điều kiện thi thạc sĩ giáo dục?

Học thạc sĩ giáo dục tiểu học ở đâu? Điều kiện thi thạc sĩ giáo dục?

24/06/2024

Ngành Digital Marketing học trường nào? Top 25+ trường đào tạo tốt nhất

Ngành Digital Marketing học trường nào? Top 25+ trường đào tạo tốt nhất

24/06/2024

Bộ GDĐT ban hành khung kế hoạch thời gian năm học 2022-2023

24/06/2024

3 nguyên tắc - 4 phương pháp giáo dục cảm xúc cho trẻ mầm non ba mẹ cần biết

3 nguyên tắc – 4 phương pháp giáo dục cảm xúc cho trẻ mầm non ba mẹ cần biết

24/06/2024

Footer

Về chúng tôi

Sigma Academy – sigma.edu.vn là tổ chức giáo dục kỹ năng cho trẻ. Đồng thời là thông tin tự động cập nhật Google chuyên cung cấp kiến thức về tất cả lĩnh vực. Website chúng tôi là web site cập nhật nội dung tự động từ google.com. Nếu có vấn đề gì về bản quyền vui lòng liên hệ: contact@sigma.edu.vn.

  • Điều khoản sử dụng
  • Chính sách bảo mật
  • Liên hệ

Mạng xã hội

  • Facebook
  • Zalo
  • Website
  • Google maps

Theo dõi chúng tôi tại Google News

Địa Chỉ

Trụ sở chính: 116/12 Tân Mỹ, phường Tân Thuận Tây, quận 7, Ho Chi Minh City, Vietnam
Điện thoại: 097.331.14.49 | Email: contact@sigma.edu.vn

Map

Bản quyền © 2025