Build Facebook Chat Bot with Python


Build Facebook Chat Bot with Python. I do not want to use Facebook Chat Bot management services of 3rd party, like Harafunnel, Chatfuel… I want to create my own chat bot. And I did that with Python.

This article will show you how to build a Facebook Chat bot with Python and deploy Python chat bot on the server.

Specifically what I need to have:

  • 1 Facebook Developer App
  • 1 Fanpage
  • 1 Web Server to run bot application. In this article, I use CentOS, Nginx, Python Flask … to run my application

Now, let’s start!

1. Setup Facebook App, Fanpage

As mentioned above, we need a facebook app (created from the facebook developer page). Then, basic setting for app.

Create Facebook Developer App

To be able to use Chat Bot via Messenger, you need to Add the Messenger Platform to your Facebook app in Dashboard

Add Messenger Platform

After that, Generate Access Token for Fanpage.

If you cannot create Access Token, click Edit Permission

Can not create Access Token for Fanpage

And accept to continue

Choose Fanpage

Now, I have Access Token for my Fanpage

Have Access Token For Fanpage

I will declare this Access Token in my code. Next step, I will verify webhook from my source code.

2. Verify Webhook

This is a required step before your Chat Bot works. Facebook has instructions with NodeJS, but I want to use Python on my own.

I create a project with the following structure:Project Facebook Chat Bot Structure

  • config: The directory contains configurations like tokens, api version.
    • Declaring tokens, api version
    • #
      # API #
      API_FOR_MESSAGE = ""
      API_SETUP_LOCAL = ""
      # TOKEN #
      VERIFY_TOKEN = "random_string_verify"
      PAGE_ACCESS_TOKEN = "fanpage_token"
  • register: Directory contains webhook registration code
    • Code verify webhook
    • #
      from config import *
      def verify(req):
          mode = req.args.get("hub.mode")
          token = req.args.get("hub.verify_token")
          challenge = req.args.get("hub.challenge")
          if mode and token:
              if mode == "subscribe" and token == VERIFY_TOKEN:
                  return challenge
                  return "403 Forbidden"
  • Run Flask to create website application.
    • #
      from flask import Flask, request
      from register import webhook
      app = Flask(__name__)
      @app.route("/webhook", methods=["GET", "POST"])
      def listen_webhook():
          if request.method == "GET":
              return webhook.verify(request)
      if __name__ == "__main__":

Now I run my application. Flask will default to port 5000 at localhost.

Run Flask in Local

I created a route to verify webhook: localhost:5000/webhook. However, let facebook confirm my webhook. I need to put the local url on a public url. And Ngrok helped me do this.

I use Ngrok to share my localhost with port 5000 to public.

Ngrok share localhost

The next thing todo is Subscribe this ngrok webhook url to Facebook App.

Subscribe Webhook

Click Subscribe To Events and setting some fields

Choose Webhook Setting

  • Fill ngrok webhook url
  • Fill the String Token declared at
  • Choose Subscribe fields: Here I choose 3 types that I think are popularly used
    • messages: Receive, send regular messages
    • messaging_postbacks: Receive, send messages continuously
    • messaging_referrals: Receive and send messages when there are referrals to the messenger. For example:

Click Verify and Save. If verify is successful, you will see the Webhook icon on the toolbar in green

Success Verify Webhook

I have configured Chat Bot. The next step is to handle the Bot Chat message and deploy to my CentOS Server.

3. Handle Facebook Chat Bot Message and Deploy

Now, we will process the message. Messages will be sent to Webhook via POST method. Above I subscribed 3 types: messages, messaging_postbacks and messaging_referrers. So now I will create 3 events to listen to the webhook of those 3 types.

Facebook Chatbot Structure Project

This is the project directory structure. I will go into each file and present its specific function.

  • This is the file that will handle the request to send the message to facebook api.
    • #
      from config import *
      import requests
      def post_api_text(sender_psid, text):
          payload = {
              "message": {
                  'text': text
              'recipient': {
                  'id': sender_psid
          auth = {
              'access_token': PAGE_ACCESS_TOKEN
          response =
          return response.json()
    • Above is a function used to send messages in text format. You can add other functions to send buttons, attachment …
  • This file will process received messages with type “message” and return regular messages
    • #
      from api import fb
      def handle(sender_psid, received_message):
          if received_message.get('text'):
              response = "Test response: Received " + received_message.get('text')
              fb.post_api_text(sender_psid, response)
    • The above code will automatically reply to the message when receiving the message.
  • This file will process received messages with type “message” and return messages continuously
    • #
      from api import fb
      def handle(sender_psid, received_postback):
          payload = received_postback.get('payload')
          if payload == "test_postback":
              response = "Message postback"
              fb.post_api_text(sender_psid, response)
    • #
      from api import fb
      def handle(sender_psid, received_referral):
          payload = received_referral.get('ref')
          if payload == "tricksmagical":
              response = "Test referral"
              fb.post_api_text(sender_psid, response)
  • Now, you add webhook POST method to receive messages from facebook and handle that type of message.
    • #
      from flask import Flask, request
      from register import webhook
      from event import message, postback, referral
      app = Flask(__name__)
      @app.route("/webhook", methods=["GET", "POST"])
      def listen_webhook():
          if request.method == "GET":
              return webhook.verify(request)
          if request.method == "POST":
              payload = request.json
              if payload["object"] == "page":
                  for entry in payload["entry"]:
                      webhook_event = entry["messaging"][0]
                      sender_psid = webhook_event['sender']['id']
                      print('Sender PSID: ' + sender_psid)
                      if webhook_event.get('message'):
                          message.handle(sender_psid, webhook_event.get('message'))
                      if webhook_event.get('postback'):
                          postback.handle(sender_psid, webhook_event.get('postback'))
                      if webhook_event.get('referral'):
                          referral.handle(sender_psid, webhook_event.get('referral'))
                  return "EVENT_RECEIVED"
                  return "404 Not Found"
      if __name__ == "__main__":

Well done. Now you can deploy this project to Server. To deploy on the server, see my article: Deploy NodeJS Application on CentOS 7. Deploy Python is like deploying NodeJS.

After deploying, you must change the webhook url (ngrok) to your server url (your domain url). and verify the webhook again.

Change ngrok webhook url

And test your bot.

Test facebook chatbot

You can view my source code at Github:

You can pull and customize as you like.

4. Submit your bot

Currently, only you can use Bot. In order for people to use Chat Bot, you must submit your bot.

Submit Chat Bot

Go to Messenger > Settings. And fulfill those requirements. Then Submit, it will take about 1 day for Facebook to browse your chat bot.

Leave a Reply