DEV Community

Lizzie Siegle for Twilio

Posted on

Build a Facebook Messenger bot with Twilio Autopilot, Functions, and SendGrid in Node.js

image with Spectra Hackathon organizers, Autopilot, SendGrid

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 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

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


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 to create one.

To link your Facebook page with Twilio, you must install Facebook Messenger for Autopilot. In the Configure tab, scroll down to Properties and check Use in -> Programmable SMS Inbound as shown below.
Use in programmable SMS inbound
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
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
Paste the URL in the Callback URL field back on your Facebook Messenger Configuration page and then click Save. Now take your phone or laptop to visit 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
Lastly, you will need a SendGrid account to get an API key. In the Twilio Functions Configuration section, save it as the environment variable SENDGRID_API_KEY like so:
SendGrid API key configuration
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" to pass on the communication to a human, "Redirect" to hit a webhook to perform something different next, "Collect" to gather data, and more.

From the Autopilot console 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."
Enter fullscreen mode Exit fullscreen mode

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
Then click on the expand button next to the text field to add multiple samples on different lines at once.
expand button
Feel free to add whatever sample sentences you want or copy the following:

What page is this
What is spectra
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
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
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

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 of Twilio Runtime. 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');
    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 =;
    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?`
    .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 => {
Enter fullscreen mode Exit fullscreen mode

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

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 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": ""
Enter fullscreen mode Exit fullscreen mode

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

What's Next

Baymax gif
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. Let me know in the comments or online what Facebook bots you want to build next!

Twitter: @lizziepika
GitHub: elizabethsiegle

Top comments (0)