Build a Personal Facebook Messenger Bot in 10 minutes with Nodejs and Standard Library

Written by tinkr | Published 2018/12/21
Tech Story Tags: bots | facebook | facebook-messenger-bot | build-messenger-bot | build-facebook-bot

TLDRvia the TL;DR App

Wouldn’t it be awesome to have a personal chatbot that will send you cool stuff throughout the day? Maybe update you on the status of your home devices or send cute cat pics from Reddit?

Let’s build one that sends you the top posts from your favourite subreddits. You can extend it of course with whatever content you want to send.

For this, we need three things:

  1. Facebook PageA Facebook Messenger bot is associated with a Facebook Page. You need to sign up as a Developer and then create a Page.

  2. DialogflowA Google company, Dialogflow helps in NLP (Natural Language Processing). This will help later when you want to extend your bot to respond to specific things.

  3. Code on Standard LibraryThe greatest thing since sliced bread, Code on Standard Library helps you run code in the cloud. This will be the brains of our operation.

Now, let’s get started.

Setup Facebook Page

Go to developers.facebook.com and sign in with your Facebook credentials. Once you’re signed in, click on Get Started and follow instructions to Add a New App.

Create a new App on FB Developer Portal

Give your App a name. This is the name from which you’ll receive your notifications. Make it something cool, like Darth Vader.

Then navigate to the Dashboard tab on the left side bar menu. Scroll down to find Messenger and select Set Up. Before you can add your Messenger integration you’ll need to create a Facebook page.

On the Dashboard tab, choose Set Up on the Messenger card and then Create a new page

This will take you to Facebook. Follow the instructions to create a Community or public figure page.

Create a Community or public figure Facebook page

Once your page has been created, switch back to FB Developer portal and refresh the page. You should now see your page listed in the dropdown Select a Page.

Refresh the page and then choose your Facebook page name from the dropdown to generate a token

Now let us setup Dialogflow. Click on Go to console and sign in with your Google credentials.

Dialogflow uses Natural Language Processing to understand chat conversation

Click on Create Agent and fill in the details. Give your Agent a name. It can be the same name as your Facebook Page.

Give your agent a name and choose the right time zone

When your agent is created, it will automatically add two Intents. Click on Default Welcome Intent to edit it.

You can add more intents if you want.

In the Events section, add the event FACEBOOK_WELCOME. This enables your bot to recognize user when he interacts with the bot for the first time.

Add Facebook Welcome to Events

Scroll down the page and delete the default responses by clicking the trash icon, as we will be responding to the user from our code.

Click on the Trash icon to delete the default responses

Scroll down further and enable Fulfillment. This makes sure that all requests are routed through our chatbot function on Code on Standard Library.

Enable Fulfillment to receive messages on your webhook

Next, we need to connect the Facebook Messenger to Dialogflow. Click on Integrations.

Integrations allow the agent to work with a variety of different services including Facebook Messenger

Turn on Messenger Integration. This will open a modal window. You need to enter two things here. First is the Verify Token which can be any text and second is the Page Access Token.

Switch to the Facebook Developer Portal and copy the Page Access Token.

Choose your Page name from the dropdown to generate a Page Access Token

Paste the Page Access Token in Dialogflow modal window and enter your Verify Token. Click on START button to start the integration. Now click on the clipboard icon to copy the Callback URL.

Click on the Clipboard icon to copy the Callback URL

Now switch to Facebook Developer Portal. It’s time to setup the Webhooks integration. Select Setup Webhooks found below the Token Generation section. Paste the URL you copied into the Callback URL field and enter your Verify Token you specified in the previous step. Tick all Subscription Fields.

Not all are required, but Dialogflow will take care of the unnecessary ones and send you only the relevant ones

Click on Verify and Save and if you’ve setup everything correctly, you should see a green tick with Complete. Now select your page name from the dropdown and click on Subscribe.

Choose your page name from the dropdown and then click on Subscribe to subscribe to your page

There are a couple more things that you need to complete the setup. Go to Settings > Basic and add a Privacy Policy URL and choose a Category for your app. The Privacy Policy URL can be any valid URL.

You can also use the Privacy Policy included with the code, as indicated in the Code on Standard Library section below

Enter the Privacy URL and choose a category for your page

Save changes and Toggle the status button On to make your app go live.

The icon will show status as Live. You might be tempted to think that this means the whole world can see your app and interact with it. Nope.

Your App is Live

Code on Standard Library Setup

This is where our code lives that will enable all the communication. When we send a message to our bot on Facebook, it’ll first go to Dialogflow. Dialogflow will route it to the right intent and then forward it to our function — this function.

First search for fb-messenger-bot in Community API Sources. Click on Create New API.

Once created, you will see three files in the functions folder.

  1. __main__.js The main function fetches the Reddit posts and sends them to the users. Modify the multi object at the top of the function, to customise the subreddits.

  2. webhook.js This function will handle all the webhook requests from Dialogflow. Here is where you’ll add the custom intents if you want to extend the bot functionality.

  3. privacy.js Did you know Code on Standard Library functions can return HTML files? This is a Privacy File that you can use on the FB Developer Portal. The URL will look something like [https://username.lib.id/fb-messenger-bot@dev/](https://boetie.lib.id/tinkr-fb-messenger-bot@dev/)privacy . You should add your own email to the bottom of this document.

Now, navigate to the env.json file and populate the environments with your Standard Library Token and Facebook Page Access Token.

To retrieve your Standard Library Token, place the cursor in between the yellow quotes and right click. Select your Standard Library Token from the drop-down menu and the variable should automatically populate.

Enter your FB Access Token and the Standard Library Token in your env.json file

Once you have saved the env.json file, click on Run.

Click Run to deploy the service

Remember that every time you change any code, you need to save and then Run it, to deploy the new code.

Once deployed, copy the API Endpoint URL that’s shown. This is your webhook endpoint.

Now let us finish Dialogflow setup. Switch to Dialogflow and click on Fulfillment and turn on the Webhook.

Enable the webhook and add URL

Append the copied URL with /webhook/ and click on SAVE at the bottom of the page. Your webhook URL should look like [https://username.lib.id/fb-messenger-bot@dev/](https://boetie.lib.id/tinkr-fb-messenger-bot@dev/)webhook/

Append /webhook/ to your base URL

We are almost done. All we need to do now, is to enable our bot on the Facebook Page. Go to your Facebook page and click on Add a Button. Choose Send Message, complete the details and save.

Add a Send Message Button to your Facebook Page

Now when you hover over the Send Message button, a dropdown will show. Click Test button.

Click on Test button to Test your bot

This will open a chat with a Get Started button. Click on it and if you have set everything up correctly, you will be greeted with “Woohoo!. Welcome {Name}. You have been added to the database.”.

This means you have been added as a user in your function on Code on Standard Library local storage.

If you message your bot “Hi” again, it will reply with “Hi {Name}, you have already been added to the database.

Now to setup tasks.

Tasks on Code on Standard Library

One of the coolest features of Code on Standard Library is Tasks. Setting up Tasks makes your code run automatically on a specified schedule.

Click on Tasks to set up your code to run on a schedule

I’ve currently setup the function for four notifications a day. You can change it to whatever number you prefer. Remember that you’ll also need to change max_notifications variable at the top of the function and add the same number of repeatable tasks in the cron specification.

In the Tasks window, choose your bot function to add a schedule to it.

Choose your function to add a Task schedule

You can setup the task schedule using the Schedule dropdown. But we want a little more control, so let’s use Advanced (cron).

Click on Advanced (cron) to use cron expressions for task schedule

The cron expression can be very confusing to understand. The expression takes 5 values — * * * * *. The first one is the minutes value and the second is the hours value.

So if you enter 30 5,8,11,15 * * *, it translates to 4 tasks run at 05:30, 08:30, 11:30 and 15:30, repeated every day. The times are in UTC, so you’ll need to add or subtract your timezone offset for the correct local time.

As I live in India and my timezone offset is +05:30, this schedule will run at 11:00, 14:00, 17:00 and 21:00 local time.

If the cron expression is valid, the next three invocation times are shown below it

Click on Schedule Task and you’re all done. You should now receive notifications on your messenger at the scheduled times.

If you want to test out the tasks schedule, choose once every minute. Once you get the right messages, turn it off and use the above cron expression or something similar to customise the schedule.

Congratulations! You have a personal chatbot now. I’ll add more tutorials in the coming months on what other interesting things you can do with a chatbot.

Check out Create an Alexa Radio Skill, if you want to build an Alexa skill with your personalized radio stations.


Published by HackerNoon on 2018/12/21