Building a Facebook chatbots with Python

Building a Facebook chatbots with Python

  • 2016-08-19
  • 5860

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:

Create a New facebook App.

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

Add Messenger

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)
@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:


Build Your First Python and Django Application

What are the benefits of developing in Node.js vs Python?

Zero to Hero with Python Professional Python Programmer Bundle

The Python Mega Course: Build 10 Python Applications

Advanced Scalable Python Web Development Using Flask