Facebook Messenger Bot with Dialogflow

Anuraag Jain
The Startup
Published in
5 min readJul 29, 2019

To improve your business you have to keep engaging with the customers. Sometimes things requested by them, which are very frequent can be automated so that they don’t have to wait for a human to reply. This can be achieved using Dialogflow which can be connected to your Facebook Messenger.

To demonstrate this I’ve built a simple project, I chose to Notify users when next IRP/GNIB Appointments are available. It’s quite frustrating to check them at specific time of the day manually.

To accomplish this we need:

  1. Facebook page
  2. Facebook App connected with your Page
  3. Dialogflow app
  4. AWS Lambda
  5. Database (your preference)
Workflow of FB Messenger with Dialogflow and AWS Lambda — cloudcraft.co

The above image explains how your user will be communicating and getting instant replies.

Facebook page

Head over to https://www.facebook.com/pages/creation/ and create your page by filling out the details. This should be a quick one.

Dialogflow App

Dialogflow, allows you to build engaging applications. With Google’s machine learning, you can handle the incoming message smoothly. Go ahead, create an app and then quickly go to “Integrations” and enable Facebook Messenger. Copy the callback URL and enter a verification token. Page Access Token will be obtained once you create the Facebook app.

Facebook App

Head over to https://developers.facebook.com/apps and create an app with your business name or anything random. Now add “Webhooks” to your app and subscribe it to the Page.

Webhooks — Facebook App

Click on “Subscribe to this object” button. In the dialog box, you must paste the URL and the verification token which was displayed in Dialogflow

Now Add “Messenger” to your facebook app and scroll down to the below section.

In the Access Tokens section, select your page and obtain the access token. This token must be added to your Messenger integration in Dialogflow.

Under the Webhooks section, you must select your page and subscribe to the events. I’ve selected certain events, you may explore them according to your needs.

To verify if everything is connected, under settings of your Facebook page click on “Messenger Platform” and there you must be able to view your newly created Facebook App.

AWS Lambda

const { dbConn } = require('./models');module.exports.handler = async (event, context) => {try {// don't allow unauthorized access to this apiif (!event.headers.hasOwnProperty('Authorization') || event.headers.Authorization !== 'my_secret_header') {return context.fail('Unauthorized');}const payload = JSON.parse(event.body);await dbConn.connect();// Decode the intent name which was invoked in Dialogflowconst intent = payload.queryResult.intent.displayName;/*** extract the payload from Facebook. This contains* sender's id , message and bunch of other data.*/const fb_payload = payload.originalDetectIntentRequest.payload;if (intent === 'New Subscription') {// save the sender id in databaseconst fbId = fb_payload.data.sender.id;}// your other intents and their logic goes here.return {statusCode: 200,body: 'success'};} catch (error) {console.log(error);return {statusCode: 200,body: 'Something is wrong'};} finally {await dbConn.disconnect();}};

The above snippet is the dialogflow’s intent handler where your core business logic stays. I’ve added authorization check to secure my API. I’ve used the serverless framework for quick deployment to lambda.

Here my lambda just sends back “success” and reply message is handled from Dialogflow’s Intents. You can also construct the response which Dialogflow expects and send that in the response.

Note: “New Subscription” is the name of the intent from Dialogflow. Here error cases are not managed 😜

Deploy this to API Gateway and copy the URL.

Connecting Dialogflow with Lambda

In Dialogflow, navigate to Fulfilment. Enable this option and paste the API Gateway endpoint and the custom headers.

Dialogflow — Fulfillment

Playing with Intents

Intents are crucial, you must have all words added so that Dialogflow can match them to correct intent to perform correct business logic and give a response back to the user. You also have fallback intent which is triggered when nothing matches with your list of intents.

Dialogflow Intent

In the above image, We’ve removed everything from “Default” and added “Facebook Messenger” response and created a custom card which is displayed to the user when they send “New”, “Join”, “Subscribe” keywords in their messages. Also webhook fulfillment is enabled so that the incoming request to sent to the API Gateway for processing.

Example Conversation🔥

Notifying Users

This conversation happens almost instantly and user can interact with intents. But what if, if you want to send message(s) like update of an event or financial news to your users outside the 24hour chat window policy of Facebook. This can be done by applying to Subscription Messaging for your page.

curl -X POST -H "Content-Type: application/json" -d '{"messaging_type": "MESSAGE_TAG","tag":"NON_PROMOTIONAL_SUBSCRIPTION","recipient": {"id": "sender_id"},"message": {"text": "User message goes here!!"}}' "https://graph.facebook.com/v3.3/me/messages?access_token=<PAGE_ACCESS_TOKEN_HERE>"

Using the above bash script you can send non-promotional messages to the users anytime. “messaging_type” and “tag” are important and must be exactly as above. “id” is the one which we captured and stored in our database when the user invoked “New Subscription” Intent.

Message sent to the users 🚀

Note: Book your appointments on the Official website. This is purely for educational purpose 😀.

--

--

Anuraag Jain
The Startup

Software Engineer | Ireland | Github/Twitter: @anuraagdjain.