Build a simple Facebook Messenger Chatbot using Python and Dialogflow

January 2, 2018    Chatbot Facebook Messenger Python API AI

BUILD A SIMPLE FACEBOOK MESSENGER CHATBOT USING PYTHON AND DIALOGFLOW

make a facebook messenger chatbot using python and dialogflow api ai

Have you ever wanted to have your personal assistance who could talk on your behalf when you are not active on facebook? This tutorial I’ll tell you how you can build one for yourself with just 20 lines of Python code. You just need some basic understanding of Python, APIs and OOPs concepts.

We will be using Python3 as our programming language. Then to connect the chatbot to facebook we will use a python package called ` fbchat` and to get the replies we will use Dialogflow service provided by Google.

Installing Dependencies :

Let’s first install all the dependencies (make sure you have Python and PIP already installed) -

  • To install fbchat -
    pip install fbchat
    
  • Dialogflow provides a python package named apiai to interact with its api, to install use -
    pip install apiai
    

Setting up Dialogflow :

  • Before we continue to the coding part we need to set up a Dialogflow account. Go to the website and sign up for a free account.
  • After logging in, you will be redirected to the Dialogflow dashboard. In the left side menu scroll down and click on the Small Talk.
  • Once you are inside Small Talk, enable it. Now you will see many sections under Small Talk Customization Progress which will have some common questions that users ask to a chatbot. Enter you responses to all those questions and click Save.
  • You can test your chatbot on the rigth side of the screen to see how its working.

Let’s Code :

Let’s first import all the packages and modules that we’ll be needing -

from fbchat import Client,log
from fbchat.models import *
import apiai,json

We will be extending the Client class which will help us in logging in and out, reading and sending messages to facebook and the log class will help us to print to the terminal so that we can understand what is going on. The apiai will send request and receive json response from Dialogflow API and the json module will decode that response and take out the required data.

Now we will create an instance of class Client, I have named it techytushar, you can name it whatever you want :

class techytushar(Client):

Then inside this class we will define two methods apiai (which will be used to set up the connection to Dialogflow) and onMessage(the code which will run when a message is received).

apiai :

    def apiai(self):
        self.ClientAccessToken = 'dialogflow api'
        self.ai = apiai.ApiAI(self.ClientAccessToken)
        self.request = self.ai.text_request()
        self.request.lang = 'de'
        self.request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

The ClientAccessToken will contain your Dialogflow access token. ai will be used to set up the connection and the requests are used to send the text request to get the reply. (refer to the Dialogflow api documentation). Note that the whole code is indented, that’s because it is placed inside a class.

onMessage :

    def onMessage(self, author_id=None, message=None,thread_id=None, thread_type=ThreadType.USER, **kwargs):
        #marking the message as read
        self.markAsRead(author_id)
        #printing to terminal as a message is received.
        log.info("Message {} from {} in {}".format(message,thread_id,thread_type.name))
        #printing message text
        print("The received message - ",message)
        try:
            #setting up connection with apiai
            self.apiai()
            #sending the query (message received)
            self.request.query = message
            #getting the json response
            api_response = self.request.getresponse()
            json_reply = api_response.read()
            #decoding to utf-8 (converting byte object to json format)
            decoded_data = json_reply.decode("utf-8")
            #loading it into json
            response = json.loads(decoded_data)
            #taking out the reply from json
            reply = response['result']['fulfillment']['speech']
        except Exception as e:
            print(e)
            reply = "sorry, techytushar is not available."

        #if we are not the sender of the message
        if author_id!=self.uid:
            #sending the message i.e. the reply string.
            self.sendMessage(reply, thread_id = thread_id, thread_type = thread_type)

        self.markAsDelivered(author_id,thread_id)

Above is the code for the onMessage method which will execute when a message is received. It will first mark the message as read, then print the message in terminal, then it will send request to apiai to get the reply and send the reply to the user. The code is well commented for clear understanding, refer to fbchat documentation.

Finally we need to log into facebook and start listening for messages:

client = techytushar(<your email>,<your password>)
#listen for incoming message
client.listen()

That’s all, now your chatbot is good to go. Just run the program and ask your friends to talk to your personal assistant. Full code can be found here.


Subscribe to the newsletters