Building a Facebook chatbots with Python

Building a Facebook chatbots with Python

<strong>Facebook now has the Messenger Platform which permits us to manufacture bots which can acknowledge messages from clients and react to them.</strong>

Facebook now has the Messenger Platform which permits us to manufacture bots which can acknowledge messages from clients and react to them.

Facebook now has the Messenger Platform which permits us to manufacture bots which can acknowledge messages from clients and react to them. In this instructional exercise, we should perceive how we can assemble a bot and add it to one of our pages so that the clients can interface with the bot by sending messages to the page.

To begin, we have three necessities to satisfy:

  • We require a Facebook Page
  • We require a Facebook App
  • We require a webhook/callback URL to acknowledge approaching messages

I am accepting you as of now have a Facebook Page. In the event that you don’t, simply ahead and make one. It’s extremely basic.

Creating and Configuring The Facebook App

1. Initially, we make a non specific facebook application. We have to give the name, namespace, classification, contact email. Basic and direct. This is what it would seem that for me:


2. Presently we need to scan the “Include Product” segment and include “Envoy”.

3. Produce access token for a Page you oversee. A popup will open approaching you for consents. Stipend the consent and you will soon see the entrance token for that page. It would be ideal if you take a note of this token. We should utilize it later send messages to the clients in the interest of the page.

Next, snap the “Webhooks” area.

4. Before we can setup a webhook, we have to setup a URL which is openly available on the web. The URL must have SSL (that is it should be https). To meet this prerequisite and set up a neighborhood dev environment, we setup a fast flagon application on our nearby machine.

Install Flask from PyPi using pip:

pip install Flask

Facebook will send a GET solicitation to the callback URL we give. The solicitation will contain a custom mystery we can include (while setting up the webhook) and a test code from Facebook. They anticipate that us will yield the test code to check ourselves. To do as such, we compose a speedy GET handler utilizing Flask.

## Filename: 

from flask import Flask, request

app = Flask(name)

@app.route('/', methods=['GET']) def handle_verification(): return request.args['hub.challenge']

if name == 'main':

We run the nearby server utilizing python The application will dispatch at port 5000 of course. Next we utilize ngrok to open the server to the web. ngrok is an awesome device and you ought to truly try it out for running and troubleshooting webhooks/callback urls on your nearby machine.

ngrok http 5000

With that order, we will get a location like Duplicate that url and glue it in the Webhook setup popup. Checkmark the occasions we’re occupied with. I check every one of them. At that point we include a mystery, which our code couldn’t care less about much. So simply include anything you like. The popup now seems as though this:

Click “Verify and Save”. If the verification succeeds, the popup will close and you will be back to the previous screen.

Select a Page again and click “Subscribe”. Presently our application ought to be added to the page we chose. If it’s not too much trouble note, on the off chance that we haven’t created an entrance token for that page in the prior stride, the membership will fall flat. So ensure we have an entrance token produced for that page.

Handling Messages

Presently every time somebody makes an impression on the “Masnun” page, Facebook will make a POST solicitation to our callback url. So we have to compose a POST handler for that url. We additionally require react back to the client utilizing the Graph API. For that we would need to utilize the marvelous requests module.

pip install requests

Here’s the code for tolerating approaching messages and sending them an answer:

from flask import Flask, request
import requests

app = Flask(name)

ACCESS_TOKEN = "EAAP9MMaGh1cBAHS7jZCnuQgm2GWx5grLraIElFlWlIw2r3Afb34m2c2rP0xdkkkKEeiBOykGINAP0tScwmL5NNBJQN9ayPCuq13syvWocmbYZA7BXL86FsZCyZBxTmkgYYp8MDulLc1Tx70FGdU5ebQZAJV28nMkZD"

def reply(user_id, msg): data = { "recipient": {"id": user_id}, "message": {"text": msg} } resp ="" + ACCESS_TOKEN, json=data) print(resp.content)

@app.route('/', methods=['POST']) def handle_incoming_messages(): data = request.json sender = data['entry'][0]['messaging'][0]['sender']['id'] message = data['entry'][0]['messaging'][0]['message']['text'] reply(sender, message[::-1])

return "ok"

if name == 'main':

The code here acknowledges a message, recovers the client id and the message content. It switches the message and sends back to the client. For this we utilize the ACCESS_TOKEN we produced before hand. The approaching solicitation must be reacted with a status code 200 to recognize the message. Generally Facebook will attempt the message a couple of more times and after that cripple the webhook. So sending a http status code 200 is essential. We simply yield “alright” to do as such.

You can now make an impression on your page and check whether it reacts accurately. Look at Flask’s and ngrok’s logs to troubleshoot any issues you may confront.

You can download the specimen code from here:

python facebook

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[]( "")**, our full-stack Python development services...

Python any: How to Check If Element is Iterable or Not

Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().