Build Facebook Chat Bot with Python

0
50

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

Basic Setting 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

Accept Permission Fanpage

Choose Fanpage

Choose Page Access

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.
    • __init__.py: Declaring tokens, api version
    • # __init__.py
      # API #
      API_FOR_MESSAGE = "https://graph.facebook.com/v2.6/me/messages"
      API_SETUP_LOCAL = "https://graph.facebook.com/v2.6/me/messenger_profile"
      
      # TOKEN #
      VERIFY_TOKEN = "random_string_verify"
      PAGE_ACCESS_TOKEN = "fanpage_token"
  • register: Directory contains webhook registration code
    • webhook.py: Code verify webhook
    • # webhook.py
      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
              else:
                  return "403 Forbidden"
  • app.py: Run Flask to create website application.
    • # app.py
      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__":
          app.run()

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 __init__.py
  • 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: http://m.me/tricksmagical?ref=start

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.

  • fb.py: This is the file that will handle the request to send the message to facebook api.
    • # fb.py
      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 = requests.post(
              API_FOR_MESSAGE,
              params=auth,
              json=payload
          )
          return response.json()
    • Above is a function used to send messages in text format. You can add other functions to send buttons, attachment …
  • message.py: This file will process received messages with type “message” and return regular messages
    • # message.py
      from api import fb
      
      def handle(sender_psid, received_message):
          print(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.
  • postback.py: This file will process received messages with type “message” and return messages continuously
    • # postback.py
      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)
  • referral.py:
    • # referral.py
      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)
  • app.py: Now, you add webhook POST method to receive messages from facebook and handle that type of message.
    • # app.py
      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)
                      print(webhook_event)
                      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"
              else:
                  return "404 Not Found"
      
      if __name__ == "__main__":
          app.run()

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: https://github.com/nguyenkhanh97nd/facebook-chat-bot.git

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

avatar