Nowadays, communication channels are fundamental for a business. If your customer has a question or a requirement, it should be solved quickly. The internet, and the life in general, moves so fast these days that the classic email is not fast enough. For this reason, there are several tools that may help you to increase your answering times. For example, add a classic FAQ section to your site, to avoid answering the same questions over and over, or something more sophisticated such as a 24/7 chat support.

One of these new tools are the chatbots. Thanks to them, you may have automated answers to common questions about your business, allowing your user to consult information about his/her account and even update it through a wizard. The best thing about this is that you do not need a person answering the chat, but your user will feel like he/she is talking with one; easing the process and generating proximity and reliability.

On this blog post we are going to explore how to implement a basic chatbot that will work on Facebook Messenger. Django Framework is going to be used to implement the examples, but you may extrapolate them to any other framework. As well, how to configure a Django app is not going to be discussed. So, let’s start!

First thing first, configure your facebook application

In order to be able to use the chatbot on Facebook Messenger, you need to create a facebook app, that will hold all your chatbot settings, and a facebook page, that will be the face or your business and the recipient of the messages that your potential clients would send.

Once you have created the app and the page, go to the app and add messenger as one of the products. After setting it up, go to messenger settings and create a token for your page.

Save this token because we will use it later. Now, we need to configure the webhook, but for this we need a server that receives and process it. So let’s create it!

Creating and configuring our application

For this section, I will assume that you already have a Django instance configured and running. For this reason, I will only give examples of the view that will handle the facebook webhook; the missing configuration, like the url, is up to you. In order to simplify the code, I will use an APIView from Django Rest Framework; but feel free to adapt the example to your preferences.

As well, facebook requires the webhook to be a public url so I will use ngrok to create one pointing to my local instance in order to allow facebook to send requests to my app without deploying it to production.

Taking this into consideration, let’s start.

First, we configure the webhook. Go to Webhooks section and click on setup webhooks. A modal like the following will appear. There, you need to configure the url, the verify token, that we will explain later, and the subscriptions you need to trigger the webhook. For a basic implementation, the messages option should be enough.

Once we click on Verify and Save, facebook will send a GET request to the callback url with two parameters: hub.verify_token, that matches the value you set on the verify token input (1234 in the example) and hub.challenge, that is an unique code that facebook will send. Your app should validate that the received verify token matches the one you used and, if it matches, should return the unique challenge code. For this reason, it is highly recommendable that you save your verify token in a secure way, such as an environment variable. Considering this, a view like the following one should do the trick.

from rest_framework import status
from rest_framework.views import APIView
class HandleFacebookPostView(APIView):
    def get(self, request, *args, **kwargs):
        if request.GET.get('hub.verify_token', '') == settings.FACEBOOK_VERIFY_TOKEN:
                return Response(request.GET.get('hub.challenge'))
        return Response(
            {'error': 'bad parameter'},
            status=status.HTTP_400_BAD_REQUEST)

Once we have this view configured, we may click on “Verify and Save”. If facebook gets what he expects, the configuration will be saved and the modal will hide. Now, every time an event that matches one of the subscriptions you selected is triggered, facebook will send a post request. So, let’s see how to manage those post requests.

Using the same View, define its post method as the following

    def post(self, request, *args, **kwargs):
    	# facebook may send you several entries in one
    	# request. That is why we need several loops
    	# to correctly manage their post
        for entry in request.data['entry']:
            for message in entry['messaging']:
                # if the entry is from a message you received
                # it will contain a "message" key
                if 'message' in message:
                    # received message
                    self.answer_message(
                    	message['sender']['id'],
                    	message['message']['text'])
                    return Response({'success': True})
                # if the entry is from a message you sent
                # it will contain a "delivery" key
                if 'delivery' in message:
                    # sent message
                    return Response({'success': True})
                return Response({'success': True})

As you may see, we simply check each of the entries that facebook sends in the webhook and we send an answer if the entry is from a message. Now let’s check how to send this message.

In order to send a message, we will need to send a POST request to the facebook endpoint using the app token we created before as the authentication. To handle this easier, we will encapsulate all in a method

    def answer_message(self, fb_id, message):
    	url = settings.FACEBOOK_SEND_MESSAGE_URL # https://graph.facebook.com/v2.6/me/messages
	    message_data = {
	        "recipient": {
	            "user_ref": fb_id
	        },
	        "message": {
	            "text": "Hello!"
	        }
	    }
	    response = requests.post(
	        url,
	        params={"access_token": settings.FACEBOOK_PAGE_ACCESS_TOKEN},
	        json=message_data)
	    return response, message_data

And That’s it! Now, every time your page receives a message from an user, your page will answer “Hello!”.

From here, you have a world of possibilities. You may use a Natural language processor, such as wit.ai that is provided by Facebook directly, to train your bot and answer your customer depending on his/her needs or requirements. As well, you could create a neuronal network that would learn from them and improve its answers every day. It is up to you!

From my experience, Facebook documentation may be hard to understand at once, specially because it is not centralized and it tends to be overwhelming, but once you start working with it and once you receive your first automated response, you really see how powerful this tool may be and how many opportunities it offers.

I hope that this tutorial helps you to take your first steps in the chatbots world!


Comments