Build a Facebook Messenger bot with Twilio Autopilot, Functions, and SendGrid in Node.js
Tags: bots, node, twilio, sendgrid
Published: 2019-03-28 00:29:22

---
title: Build a Facebook Messenger bot with Twilio Autopilot, Functions, and SendGrid in Node.js
published: true
description: I wanted to automate answering questions sent to the Facebook Page of the hackathon I organize to provide a seamless 24/7 customer service experience. Here’s how you can do that by building a Facebook Messenger bot with Twilio Autopilot🤖, Functions, and SendGrid📧 to make your life as an event organizer/business owner easier💕
tags: bots, node, twilio, sendgrid
---

![image with Spectra Hackathon organizers, Autopilot, SendGrid](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/sendgridspectraautopilot.width-1616.png)

For event-organizers and business-owners, providing quick 24/7 customer service can be tough. I help run a hackathon for women and non-binary people and [our Facebook page](https://www.facebook.com/sospectra) has to respond to so many questions, like when the event is happening, if we're looking for new organizing team members, when hacker applications open, and more! Answering these can get repetitive and tedious--if only there was a way for us developers to automate the process!

![Supergirl gif](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/-Cb6Jrox4LpmkhX4ujmJsYNNWs_7iqNMT3paen5j2v5foRQhBi1exjI4nLcdYiByrOKQgFttz2GkeQ)

Never fear, this step-by-step tutorial will show you how to build an intelligent Facebook Messenger bot with Twilio Autopilot, Functions, and SendGrid in Node.js. If the Autopilot assistant gets stuck and the user wants to speak to a human, the assistant will hand off the conversation to the business, connecting them with a human via Email for a seamless customer experience.
![Autopilot logo](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/QRMhIBzZcCW81UIhirA8o6BjMWdoLZ4SiDem128IBJKYcR.width-500.png)

## Setup
Before you get started, you will need to have a Facebook Page for your brand or business. If you don't have one, follow [these instructions](https://www.facebook.com/pages/creation/) to create one.

To link your Facebook page with Twilio, you must [install Facebook Messenger for Autopilot](https://www.twilio.com/console/channels/XB93e989ba4b741738f51c3f0e12076d42). In the *Configure* tab, scroll down to *Properties* and check *Use in -> Programmable SMS Inbound* as shown below.
![Use in programmable SMS inbound](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/ncYN3tC6q-fskqXTsG-LjHXeCiIuYQnk9xmAUggsVRIxy.width-1000.png)
Scroll down a bit to the *Credentials* section and click the *Facebook Login* button to link. Follow the directions to link your Facebook page with your Twilio Account until you see a page like this:
![linked Twilio Autopilot to Messenger image](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/8faACmoC2fkldY9lGpqCpQIRM_YligDDpxUn1hAxH9HxX.width-1000.png)
Again under *Credentials*, select the Facebook page you want to build your Bot for and click `Save`. Now go to your Autopilot console and either make a new Autopilot Assistant by clicking the red plus button or select one you've already made. Click *Channels* on the left-hand panel and scroll down to select *Facebook Messenger*. Copy that Configuration URL below.
![Configuration URL img](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/uDn-jN-Ayu5UJl1KkbsfpoCqWVqKhO_ATdXjueRcFTiEP.width-1000.png)
Paste the URL in the *Callback URL* field back on your [Facebook Messenger Configuration page](https://www.twilio.com/console/channels/XB93e989ba4b741738f51c3f0e12076d42) and then click `Save`. Now take your phone or laptop to visit [https://messenger.com](https://messenger.com) or the Facebook Messenger mobile app. Send any message to your Facebook page. You should see a reply "This is your new Task."
![This is your new task img](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/IF6aifFAmJW1-LIPbyHVrxgn53ErivhuYwFLO7sJInDlc.width-1000.png)
Lastly, you will need a [SendGrid](https://app.sendgrid.com/) account to [get an API key](https://app.sendgrid.com/settings/api_keys). In the [Twilio Functions Configuration section](https://www.twilio.com/console/runtime/functions/configure), save it as the environment variable `SENDGRID_API_KEY` like so:
![SendGrid API key configuration](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/g9BJdoZi-CcAiJmoq6kIJzM97jbaRs6dj-5KElib9_gVw.width-1000.png)
Now it can be referenced with `context.SENDGRID_API_KEY` in any of your Twilio Functions.

## Make your First Task
Autopilot lets you perform different "actions" in whatever job you want to get done with it. You can use "Say" to communicate something to the user, ["Handoff"](https://www.twilio.com/docs/autopilot/actions/hand-off) to pass on the communication to a human, ["Redirect"](https://www.twilio.com/docs/autopilot/actions/redirect) to hit a webhook to perform something different next, ["Collect"](https://www.twilio.com/docs/autopilot/actions/collect) to gather data, and more.

From the [Autopilot console](https://www.twilio.com/console/autopilot) go to *Task Builder* for your Autopilot assistant. Replace the "This is your new Task" text with the following (the text below is for our women's hackathon page.)
```
{
        "actions": [
                {
                        "say": "Hi! Spectra hosts full-day events in the Bay Area for women and non-binary people in tech. Spectra 2.0 was held at Domino Data Lab in 2018 and our inaugural women's hackathon was at YouTube HQ in July 2016. Never fear! We're currently planning our 2019 event."
                }
        ]
}
```
Now it's time to add some training samples that will prompt that `hello_world` response we just added. Click on the *modify* button as shown below, followed by *View Samples*.
![modify then view samples img](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/DzY_kCfbGToaF74Uq8clRBgEn1wD-6IqwkCv8FrOL6PFx.width-1000.png)
Then click on the *expand* button next to the text field to add multiple samples on different lines at once.
![expand button](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/Screen_Shot_2019-03-27_at_11.02.37_AM.width-1600.png)
Feel free to add whatever sample sentences you want or copy the following:
`
What page is this
hi
What is spectra
Hello
What are you
Who is this
Who are you
What business is this
What is this page
What is spectra women's hackathon
`
You should have at least ten samples for each task so your Assistant has enough data to properly map user input to the task. Press the red "+" button on the right of the text field to add them.
![red plus button](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/Screen_Shot_2019-03-27_at_11.04.12_AM.width-1000.png)
After making all these changes to the Autopilot Assistant we need to create a new model. Go to the Build Models tab under the Natural Language Router and create a new Model Build with a name like "v0.1".
![model build](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/image.width-1000.png)
You can add other static tasks for our Facebook Messenger bot using the same directions as above. Let's now move on to making a dynamic task.
![flexible dog gif](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/MD_GZG5HbkdzYKuvYTe_iH_sprJnYyHzTrdJ-PwdTV0T09Yq7gdVbbdAPdBZ_8cyoJsQb3cBl9RcNg)
## Make a Dynamic Task
Most tasks are static and require a fairly straightforward answer. However, say you want to extract some important data from a sample. This data could vary depending on the user. In the case of the women's hackathon, the user messaging the Facebook page may want to speak with a human and the hackathon organizers may want to get the user's email to contact them.
Go to the [Configure Functions section](https://www.twilio.com/console/runtime/functions/configure) of [Twilio Runtime](https://www.twilio.com/console/runtime/overview). Click the red "+" button under *Dependencies* to add a NPM module. In the name box type `@sendgrid/mail` and under *version* add `6.3.1`.
Save it and click *Manage* under *Overview*. Select the red "+" button to create a new "Blank" function. Give it a name like "Start Email Conversation With User" and add a path like `/getemail`. Change the code of your Function to the following:
```
exports.handler = function(context, event, callback) {
    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(context.SENDGRID_API_KEY);
    const moment = require('moment');
    let memory = JSON.parse(event.Memory);
    let first_name = memory.twilio.collected_data.email_user.answers.first_name.answer || 'to whom it may concern';
    let email = memory.twilio.collected_data.email_user.answers.email.answer;
    console.log("first name ", first_name, "email ", email);
    const msg = {
        to: email,
        from: context.FROM_EMAIL_ADDRESS,
        subject: `Hi From Spectra!`,
        text: `Hi, ${first_name}! This is Lizzie from Spectra. Thanks for speaking with our Facebook bot, and now you're speaking with me! How can I help you?`
    };
    sgMail.send(msg)
    .then(response => {
        const resp = {
            actions: [
            {
                say: "Thank your for talking with our bot. You will receive an email via SendGrid connecting you with a Spectra human soon."
                }         
                ]
        }
        callback(null, resp);
    })
    .catch(err => {
      callback(err);
    });
}
```
What does this code do? We import some required libraries, get the answers the user gave us (their first name and then their email), print out their answers, send an email via SendGrid kicking off a conversation between yourself and the user, and then respond to the user via Facebook Messenger.
![email gif](https://media.giphy.com/media/3oriNUctGOi5sTtvGg/giphy.gif)

Using `${first_name}` accesses the first name the user provided, helping humanize and personalize the interaction.  

Now go back to *Task Builder( and make a new task called `email_user`. Add these samples, or similar ones:
`
I need help
My questions aren't being answered
You're not helping
This isn't helping
I want to speak to a human
My question isn't answered
Help
help me
aid me
I need a human
`
Then make a Task called `email_user` and add the following code and replace the value in `redirect` with your own Twilio Function URL:
```
{
    "actions": [
        {
            "collect": {
                "name": "email_user",
                "questions": [
                    {
                        "question": {
                            "say": "We're sorry we can't chat with you right now to help. What's your first name?"
                        },
                        "name": "first_name",
                        "type": "Twilio.FIRST_NAME"
                    },
                    {
                        "question": {
                            "say": "What is your email?"
                        },
                        "name": "email",
                        "type": "Twilio.EMAIL"
                    }
                ],
                "on_complete": {
                    "redirect": "https://your-function-url.twil.io/getemail"
                }
            }
        }
    ]
}
```
This code will make the bot prompt you for your first name and then your email after you messaged something that it identified as a match for the help task. Then your Twilio Function is triggered to send an email.

Create a new *Build Model*, build your Autopilot assistant again, and test out your bot by sending something like "can you help me?"
[![FB Messenger bot in action](http://img.youtube.com/vi/SozTZlNGlTA/0.jpg)](http://www.youtube.com/watch?v=SozTZlNGlTA)

## What's Next
![Baymax gif](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/DZNiTolJIThVbuYQGZlwZspyIjC6kJKNmwDZaR_rgdvcCkciOVdEq5WJnZ5zhXw4N7Cc0MAV-2VV01)
Autopilot makes it so easy to automate certain tasks yet also to pass on other tasks to real people to humanize online interactions. Next up on my bot agenda is to build a Facebook Page and corresponding Messenger bot for my [personal tech events newsletter](https://tinyletter.com/lizziepika). Let me know in the comments or online what Facebook bots you want to build next!

Email: lsiegle@twilio.com 
Twitter: [@lizziepika](https://twitter.com/lizziepika)
GitHub: [elizabethsiegle](https://github.com/elizabethsiegle)