Build a Punchy Quiz Bot in Eight Minutes

Lizzie Siegle - May 19 '20 - - Dev Community

header

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

These entertaining "What kind of ____ are you?” quizzes have risen in popularity, getting shared an average of 1900 times on social media according to Buzzsumo. Read on to see how you can make a punchy and fun Buzzfeed-style quiz "What Twilio Product are You?" with Twilio.
question

Set Up and Configure your Bot with a Twilio Number

To follow along with this post, you need two things:

Go to your Autopilot console and under Create a Bot select Start from Scratch.
select a bot

Give your bot a title like what-twilio-product-are-you and click Create bot.
start from scratch

Select Channels from the left-hand menu and then click Programmable Messaging.
channels

Copy that Messaging URL and in a new tab configure your Twilio number in your phone number console.
messaging URL

If you don't have a Twilio number yet, go to the Phone Numbers section of your Twilio Console and search for a phone number in your country and region, making sure the SMS checkbox is ticked.
buy a number

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

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.

{
        "actions": [
                {
                        "say": "What Twilio product are you? Answer 3 questions to find out!"
                },
                {
                        "redirect": "task://main_collect"
                }
        ]
}
Enter fullscreen mode Exit fullscreen mode

greeting task json

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.

{
        "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
                                                        }
                                                }
                                        }
                                                ]
                        }
                }
        ]
}
Enter fullscreen mode Exit fullscreen mode

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:

{
        "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"
                                        }
                                }
                        }
                }
        ]
}
Enter fullscreen mode Exit fullscreen mode

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. Select a Blank template and click Create.
function

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.

//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();
Enter fullscreen mode Exit fullscreen mode

Then we calculate which answer (A, B, C, or D) was most common in this clean ES6 manner (with O(n) complexity!)

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];
Enter fullscreen mode Exit fullscreen mode

Finally, we return a message containing which Twilio product the user is most like based on their previous answers to the chatbot.

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);
};
Enter fullscreen mode Exit fullscreen mode

Now text your Twilio number to partake in your quiz!
autopilot result

What's Next

celeb baby name
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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player