Build a Punchy Quiz Bot in Eight Minutes
Tags: javascript, bot, ai, serverless
Published: 2020-05-19 23:30:19

---
title: Build a Punchy Quiz Bot in Eight Minutes
published: true
description: Build a serverless Buzzfeed-like quiz chatbot using SMS in under 8 minutes with Twilio.
tags: js, bot, ai, serverless
---
![header](https://twilio-cms-prod.s3.amazonaws.com/images/quiz_cZhU1LJ.width-1616.png)

Have you ever wondered what Twilio product you are most like? Now you can text +1 (321) 340-6085 to find out!

These entertaining <em>"What kind of ____ are you?”</em> quizzes have [risen in popularity](https://www.wired.com/2014/03/buzzfeed-quizzes/), getting shared an average of 1900 times on social media [according to Buzzsumo](http://buzzsumo.com/blog/quizzes-content-marketings-secret-weapon/). Read on to see how you can make a punchy and fun Buzzfeed-style quiz "What Twilio Product are You?" with Twilio.
![question](https://twilio-cms-prod.s3.amazonaws.com/images/89He6LXgXaqDganhcwzanwrONra1dNlrAdkSTDpxnmTFJI.width-500.png)

## Set Up and Configure your Bot with a Twilio Number
To follow along with this post, you need two things:
- A Twilio account - [sign up for a free one here and receive an extra $10 if you upgrade through this link](http://www.twilio.com/referral/iHsJ5D)
- A Twilio phone number with SMS capabilities - [configure one here](https://www.twilio.com/console/phone-numbers/search)

Go to your [Autopilot console](https://www.twilio.com/console/autopilot/list) and under `Create a Bot` select `Start from Scratch`.
![select a bot](https://twilio-cms-prod.s3.amazonaws.com/images/Q-U5ecxm7JM0ZVqX0ECoW3Rn-yR5fUsxlSUPg6jauFXnR.width-1000.png)

Give your bot a title like <em>what-twilio-product-are-you</em> and click `Create bot`.
![start from scratch](https://twilio-cms-prod.s3.amazonaws.com/images/WznsDnb6TMMtFx6j8RxfX7LRWPGzlkMjkjo_ndSc8TbV5.width-1000.png)

Select `Channels` from the left-hand menu and then click `Programmable Messaging`.
![channels](https://twilio-cms-prod.s3.amazonaws.com/images/mHqojErF89eo1Zzzf3oBKB6IMl38QZ1yUYrEK1gO_Ca2H.width-1000.png)

Copy that Messaging URL and in a new tab configure your Twilio number in your [phone number console](https://www.twilio.com/console/phone-numbers/incoming).
![messaging URL](https://twilio-cms-prod.s3.amazonaws.com/images/F7dkqSAPQOEJzejsekA-K0dnsIK5XaD7toS3xPHhBEYVy.width-1000.png)

If you don't have a Twilio number yet, go to the [Phone Numbers](https://www.twilio.com/console/phone-numbers) section of your [Twilio Console](https://www.twilio.com/console) and search for a phone number in your country and region, making sure the SMS checkbox is ticked.
![buy a number](https://twilio-cms-prod.s3.amazonaws.com/images/iS9725REApy8cAUJQa0Uu-9own1dHExPDO2U7a0L24cHk.width-1000.png)

In the `Messaging` section of your purchased number, in the `A Message Comes In` section, set the Webhook to be your Messaging URL and hit `Save`.
![configure num](https://twilio-cms-prod.s3.amazonaws.com/images/6EmMo4III8guzWR8GaiH3IFgT94GX2RKhgGIyMsOGeLZv.width-1000.png)

## Make a Buzzfeed-Style Quiz with Autopilot
Back in your Autopilot bot console, you should see some default tasks that already have been trained with some samples. For example, the `Goodbye` task says "Thank you! Please reach out again if you need anything. Goodbye." and is triggered by phrases such as "that's all", "no thanks", etc. `Greeting` is another ready-made task. Let's edit it now.

Edit `Greeting` by clicking `Program` next to it to include the following JSON that will introduce the bot with a Say action, and then redirect to a new task called `main_collect`. The quiz questions will be asked in main_collect.

```json
{
        "actions": [
                {
                        "say": "What Twilio product are you? Answer 3 questions to find out!"
                },
                {
                        "redirect": "task://main_collect"
                }
        ]
}
```
![greeting task json](https://twilio-cms-prod.s3.amazonaws.com/images/0kGWzTNAeg0TaP4e5d6rM9bYcQPn3wIAA1NTF64Z8tTtu.width-1000.png)

Let's make the main_collect task now. Go back to `Tasks` and click `Add a Task`, calling it `main_collect`. Normally you would probably want to train this task on samples to trigger it, but because we redirect to it from `Greeting`, we don't need to worry about samples. This is a simple bot, it just wants to know what Twilio product you are!

First we add a `Collect` to our JSON Actions Bin. This asks a series of questions together in a group. We also provide the name of the Collect flow (in this case it is `what_twilio_product_are_you`) followed by a questions array. Each question has a name and a `Validate` instruction to limit what the user can answer with. We use the `Validate` attribute `allowed_values` to provide an array of possible answers. If this was a quiz where there is only one right answer, it might only have one allowed value.

If the user sends in an answer that's not in `allowed_values`, the say in `on_failure` will return "Please send a, b, c, or d!" and repeat the question to the user so they can try again. The maximum number of attempts the user can try to answer a question is three times, and then if they do not send an allowed answer, they are redirected back to the `greeting` task.

```json
{
        "actions": [
                {
                        "collect": {
                                "name": "what_twilio_product_are_you",
                                "questions": [
                                                {
                                                "question": "1. You have a virtual meeting🖥️ at 9am🌅. What are you doing at 8:58am?\n A. reviewing the meeting notes and agenda so you can best contribute\n B. You're drinking coffee☕, getting ready to lead the meeting or watch someone you delegated lead the meeting.\n C. Just waking up.🛏You're efficient and will look polished from the top up👔.\n D. Checking your email and Slack📰, getting some easy work tasks out of the way.",
                                                "name": "pandemic_meeting",
                                                "validate": {
                                                        "allowed_values": {
                                                                "list": [
                                                                        "a",
                                                                        "b",
                                                                        "c",
                                                                        "d"
                                                                ]
                                                        },
                                                        "on_failure": {
                                                                "messages": [
                                                                        {
                                                                                "say": "Please send a, b, c, or d!"
                                                                        }
                                                                ],
                                                                "repeat_question": true
                                                        },
                                                        "max_attempts": {
                                                                "redirect": "task://greeting",
                                                                "num_attempts": 3
                                                        }
                                                }
                                        }
                                                ]
                        }
                }
        ]
}
```

You can then copy and paste the lines highlighted above for each question you want your quiz-bot to ask. The code below includes three questions but you can find the [complete `Collect` flow with all fifteen questions in this GitHub Gist](https://gist.github.com/elizabethsiegle/074984c0cf7ac5c69a9f1d7d2347180f):
```json
{
        "actions": [
                {
                        "collect": {
                                "name": "what_twilio_product_are_you",
                                "questions": [
                                        {
                                                "question": "1. You have a virtual meeting🖥️ at 9am🌅. What are you doing at 8:58am?\n A. reviewing the meeting notes and agenda so you can best contribute\n B. You're drinking coffee☕, getting ready to lead the meeting or watch someone you delegated lead the meeting.\n C. Just waking up.🛏You're efficient and will look polished from the top up👔.\n D. Checking your email and Slack📰, getting some easy work tasks out of the way.",
                                                "name": "pandemic_meeting",
                                                "validate": {
                                                        "allowed_values": {
                                                                "list": [
                                                                        "a",
                                                                        "b",
                                                                        "c",
                                                                        "d"
                                                                ]
                                                        },
                                                        "on_failure": {
                                                                "messages": [
                                                                        {
                                                                                "say": "Please send a, b, c, or d!"
                                                                        }
                                                                ],
                                                                "repeat_question": true
                                                        },
                                                        "max_attempts": {
                                                                "redirect": "task://greeting",
                                                                "num_attempts": 3
                                                        }
                                                }
                                        },
                                        {
                                                "question": "2. What unusual celebrity baby name do you secretly🤐like💗?\n A. Pilot Inspektor\n B. Banks💰\n C. X Æ A-12🤖\n D. Apple🍎",
                                                "name": "celeb_baby_name",
                                                "validate": {
                                                        "allowed_values": {
                                                                "list": [
                                                                        "a",
                                                                        "b",
                                                                        "c",
                                                                        "d"
                                                                ]
                                                        },
                                                        "on_failure": {
                                                                "messages": [
                                                                        {
                                                                                "say": "Please send a, b, c, or d!"
                                                                        }
                                                                ],
                                                                "repeat_question": true
                                                        },
                                                        "max_attempts": {
                                                                "redirect": "task://greeting",
                                                                "num_attempts": 3
                                                        }
                                                }
                                        },
                                        {
                                                "question": "3. What's your brunch order?\n A. pancakes🥞, waffles, or french toast \n B. omelette or frittatta🥚\n C. avocado🥑 toast🍞\n D. oatmeal",
                                                "name": "brunch_order",
                                                "validate": {
                                                        "allowed_values": {
                                                                "list": [
                                                                        "a",
                                                                        "b",
                                                                        "c",
                                                                        "d"
                                                                ]
                                                        },
                                                        "on_failure": {
                                                                "messages": [
                                                                        {
                                                                                "say": "Please send a, b, c, or d!"
                                                                        }
                                                                ],
                                                                "repeat_question": true
                                                        },
                                                        "max_attempts": {
                                                                "redirect": "task://greeting",
                                                                "num_attempts": 3
                                                        }
                                                }
                                        }
                                ],
                                "on_complete": {
                                        "redirect": {
                                                "method": "POST",
                                                "uri": "https://YOUR-TWILIO-FUNCTION-URL.twil.io/buzzfeedquiz"
                                        }
                                }
                        }
                }
        ]
}
```
After the last question, the bot redirects to a Twilio Function to tally up all the answers and calculate the all-important answer to "What Twilio Product are you?"

### Calculate the Results with JavaScript in a Twilio Function
Make a new Function by clicking the red plus button in your [Functions Console](https://www.twilio.com/console/functions/manage). Select a <em>Blank</em> template and click `Create`.
![function](https://twilio-cms-prod.s3.amazonaws.com/images/0bZCylppW6dGW89YbsGwjYHSKS5FXY-5woRXH-uymVeQB.width-1000.png)

Append `/buzzfeedquiz` to the path, then copy the path and paste it in your Autopilot bot JSON bin's `on_complete: redirect: uri`. Then add the following JavaScript code to get the memory of each of the fifteen answered questions and create an empty response object that will soon be filled.

```javascript
//get answer from Memory
    let memory = JSON.parse(event.Memory);
    let respObj = {}; //empty response object to fill with Autopilot response SMS message 
    let q1 = memory.twilio.collected_data.what_twilio_product_are_you.answers.pandemic_meeting.answer.toLowerCase(); 
    let q2 = memory.twilio.collected_data.what_twilio_product_are_you.answers.celeb_baby_name.answer.toLowerCase();
    let q3 = memory.twilio.collected_data.what_twilio_product_are_you.answers.brunch_order.answer.toLowerCase();
```
Then we calculate which answer (A, B, C, or D) was most common in this clean ES6 manner (with O(n) complexity!)

```javascript
const result = Object.entries(
    [q1, q2, q3].reduce((previous, current) => {
        if (previous[current] === undefined) previous[current] = 1;
        else previous[current]++;
        return previous;
    }, {})).reduce((previous, current) => (current[1] >= previous[1] ? current : previous))[0];
```
Finally, we return a message containing which Twilio product the user is most like based on their previous answers to the chatbot.

```javascript
var msg = '';
    if(result == 'a') {
        msg = `You're like Programmable SMS.\n\nYou're popular, reliable, and a bit more traditional, but versatile and not boring. You may not always like change. \n\nYou are a solid teammate🧗‍♀️ and worker and get the job done✊. \n\nYou're a control freak and may not always lead, but still sometimes end up representing your group. Keep doing you and being a rock. You're solid❤`;
    }
    else if(result == 'b') {
        msg = `You're like Programmable Voice.\n\nYou're the OG, a pioneer, a leader🎤. You may sometimes hesitate to take risks and innovate, but that's because you've done all of it before📅. \n\nYou have experience, mentor others, and also lead the way for others to follow🧗. \n\nYou prefer to keep things short, sweet, and succinct, and don't waste time💃. You work hard🖥️ but also know how to have fun🐬.`;
    }
    else if(result == 'c') {
        msg=`You're like Twilio Autopilot.\n\nYou follow buzzy trends🐝 like machine learning, kubernetes, and dalgona coffee☕. \n\nYou often try to improve yourself💪 and may be a bit flighty🛫 but that's okay, you're fun🤪, creative🎨, and innovative🤖. The downside to being flexible😅 is that you may be gullible sometimes.\n\n You say "yes"👍 a lot and should probably take up yoga🧘 because though you have a lot on your plate🍽️, you aren't always the best at focusing on what's important📝.\n\n Even though you like comedies🤣, you also watch Die Hard🔫 every holiday season🎄 because you are nuanced.`;
    }
    else if(result == 'd') {
        msg=`You're like Twilio Functions.\n\nYou like to make life easier for your friends and family🙋. You're the type of person who bakes🎂for birthdays🎁. \n\nYou're constantly trying to improve those around you📚 and are always in beta. If you ordered a grilled chicken sandwich🥪 at a restaurant🥡 and it was uncooked, you wouldn't say anything because you wouldn't want to be a bother. \n\nIf someone has a question❓ you don't know the answer to, you look it up for them.💻 You know how to juggle 🤹multiple things at once but also how to prioritize what's important.`;
    }
    else {
        msg=`You're like Twilio Studio.\n\nYou are able to connect with a lot of people, regardless of their backgrounds🙋. You're a free-spirit, the type of person who has friends across different groups. You're included in lots of birthdays🎁. \n\nYou're a reader📚 of both literature and fun, less-serious things like comics, and are always in beta. At a restaurant🥡, you want everything! So many choices! \n\nYou question❓ everything around you, you inquisitive soul. Keep it up with your wide eyes and keep your eyes wide open. There's a whole world to explore for you!` ;
    }
    respObj= {"actions":[
        { "say": msg
        }
    ]};
        callback(null, respObj);
};
```
Now text your Twilio number to partake in your quiz!
![autopilot result](https://twilio-cms-prod.s3.amazonaws.com/images/Screen_Shot_2020-05-15_at_10.53.45_AM.width-1000.png)

### What's Next
![celeb baby name](https://twilio-cms-prod.s3.amazonaws.com/images/89He6LXgXaqDganhcwzanwrONra1dNlrAdkSTDpxnmTFJI.width-500_GKpl1pu.png)
You can add more questions, more answer choices, more emojis, or a more complex system of tallying up the answers. With people sheltering at home, now is a great time to create entertaining quizzes for personal or professional use. Twilio Autopilot makes it easy for you to get creative with chatbots and quizzes to engage with customers, fans, friends, and family, or just have fun!