メニュー

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

How to build a chatbot

This guide will give you the resources and information you need to build your chatbot.

With Autopilot, you can build AI chatbots powered by machine learning to help your users interact with your application through natural conversations. Autopilot uses a task-driven programming model where tasks correspond to outcomes the user wants from interacting with your bot, like booking an appointment or changing a flight. It uses natural language understanding (NLU) to detect what your users are saying and match it to the appropriate task. Your chatbot can be trained to recognize different possible phrases and words the user could say that correspond to a task.

Instead of requiring your users to provide exact responses or keywords to interact with your bot, the chatbot can be trained to parse and/or recognize similar phrases or words.

In this guide, we’re going to:

  • Create an Autopilot Assistant with a pre-built template using the Autopilot Command Line Interface (CLI).
  • Modify the Assistant to work with your Twilio account.
  • Program and train the Assistant to perform some new tasks.
  • Deploy the Assistant as a chatbot on the messaging channels supported today - Programmable Chat, SMS, WhatsApp, and Facebook Messenger.

1. Install the Autopilot CLI with npm

Start by installing the Autopilot CLI. This will allow you to quickly create an Autopilot bot in your account using the template provided.

Install the CLI with this command:

sudo npm install -g @twilio/autopilot-cli

Get npm if you don’t already have it installed.

After Autopilot CLI is installed, configure the CLI with your Twilio account credentials:

ta init

Your credentials will be stored in a local JSON file at ~/.twilio/config.json. You can learn more about the different commands supported by the CLI here.

2. Create an Assistant

In this guide, we’ll be creating a bot that helps users with their airline reservations. The Autopilot CLI comes with different templates you can use to jump-start your development. You can find this template, as well as others for different use cases, in the Autopilot templates repository on GitHub.

Once you’ve installed the Autopilot CLI, use the ta create command to create a new bot in your account from a template.

Screen Shot 2019-07-20 at 8.09.00 PM.png

If you have added multiple credentials to the CLI, you can provide the profile name to select the Twilio account you want to use:

ta create [--schema <file>] [--credentials <profile-name>]

Select AirlineReservations in the command line and the CLI will create a new bot with the same name in your account. You can always change its name later as you see fit.

Bot List.png

3. Modify the Bot Behavior

Let’s review how the bot you just created from the template is set up and make a few small changes to make it work in your Twilio account.

Tasks

The bot template comes with five built-in tasks.

Task List.png

1.welcome_message

The default task triggered when the user greets the chatbot. You should train this task based on how you’re asking your users to begin interacting with the chatbot. For example, the task in the template has been trained on phrases like ‘Start’, ‘Hello’ and ‘Begin’, so some samples you could train it on could include ‘Let’s start', ‘Hey there’, 'Time to begin', etc. See Step 4 for more details on training.

Greeting the bot isn’t mandatory. If the user already knows what they want, like checking their flight time for example, Autopilot will skip this task and directly kick off the get_flight_time task.

2.get_flight_time

Asks the user for their name and departure city to retrieve their reservation details. Note that the departure and arrival times for the flight have been hard-coded for simplicity. This task uses a Collect flow to gather this information from the user before redirecting to a Twilio Function that ‘retrieves’ their flight details and constructs a personalized response for Autopilot to deliver to the user.

Functions provide a serverless environment for writing event-driven code using node.js to build dynamic Twilio applications. Each Function has a unique URL that can be invoked by an HTTP request to run the code.

Get Flight Time.png

You’ll need to create a new Function in your account and point it to the uri attribute.

Go to the Manage Functions page in the Twilio console here and paste the code included below in the editor, and click save:

        
        
        
        

        Finally, point the “uri” attribute in the “on_complete” section of the Collect flow to the path generated by the Function (your Function path will be different as each path is unique to a user):

        flight-details.png

        Hybrid Tasks

        In a hybrid task, the bot handles a portion of the request before handing off to an agent. This guide doesn’t discuss implementing hybrid tasks. Refer to How to hand-off messaging conversations from Autopilot to your Contact Center to see how to implement hybrid tasks. 

        3.book_flight

        Uses a Collect flow to ask the user for departure city, destination city, departure date and whether this is a round-trip before handing off to an agent to complete the booking. This is an example of a hybrid task — starts off being handled by a chatbot but is ultimately completed by the agent. This task is discussed in the guide How to hand-off messaging conversations from Autopilot to your Contact Center.

        4.change_flight

        Automatically hands the user off to an agent to process changing their flight. This task is also discussed in the guide How to hand-off messaging conversations from Autopilot to your Contact Center.

        5.send_to_agent

        Triggered when Autopilot recognizes that the user wants to skip the chatbot and talk directly to an agent. It is also used by the two hybrid tasks above - book_flight and change_flight to complete handing off the conversation to an agent. This task is also discussed in more detail in the guide How to hand-off messaging conversations from Autopilot to your Contact Center.

        Default Behaviors

        Defaults determine your bot's behavior in three different situations:

        • Assistant Initiation: the bot is responsible for beginning a conversation. Only used for inbound phone calls.
        • Fallback: the natural language engine cannot map human input to an existing task and needs to provide the user with additional direction.
        • Collect on Failure: the bot needs to know which task to use if there is a failure when collecting data.

        default behaviors.png

        Defaults should point either to:

        • An existing task. With our airline reservation bot, the assistant_initiation default points to the welcome_message task.
        • A publicly accessible URL that responds with Actions. With our bot, the fallback points to a Twilio Function.

        Learn more about Defaults in the documentation.

        Stylesheets

        StyleSheets enable you to give your bot a style by specifying its voice, error messages, success messages, and data collection validation behavior.

        Learn more about Stylesheets in the documentation.

        stylesheet.png

        4. Add Tasks

        We’re going to add two simple tasks using the console to our bot to allow the user to check their loyalty status with the airline and explore dining options at the terminal they are departing from.

        Add Tasks

        5. Program Tasks

        6.check_loyalty_status

        Click the Program button on the check_loyalty_status task and paste the JSON included below in the text editor, and click Save.

        For the sake of simplicity, we’re programming this task to respond with a set of hard-coded values. However, you could easily generate a dynamic response like we’re doing with the next task below.

              
              
              
              

              7.explore_dining_options

              We’ll program this task with a Collect flow that asks the user which terminal they are departing from to retrieve dining options. Click the Program button on the explore_dining_options task. Paste the Collect flow included below in the text editor and click Save.

                    
                    
                    
                    

                    This flow uses the Validate feature in the Collect Action to ensure the user provides a valid terminal number. Learn more about Validating information provided by users in the documentation.

                    This task redirects the conversation to a Function to dynamically provide dining options based on the terminal the user is departing from. These options have been hardcoded for simplicity. To create the Function, go to the Manage Functions page in the console here and paste the code included below in the editor:

                          
                          
                          
                          

                          Finally, point the uri attribute in the on_complete section of the Collect flow in the explore_dining_options task in Autopilot to the path generated by the Function.

                          6. Train Tasks

                          Next, we need to train these tasks using example phrases your users might say to the bot to check their loyalty status or check dining options. Training is an essential part of building a bot powered by machine learning. Under the hood, each bot uses a number of different machine learning models to process what the user is saying. These models need to be ‘trained’ with real examples of what your users might say when interacting with it. These examples are referred to as Samples in Autopilot.

                          We recommend starting with at least ten Samples, but the more you add, the more accurately your assistant will be able to match what the user said to the right task.

                          Click on the Train button next to the task to open up the training menu and add your Samples.

                          check_loyalty_status

                          training.png

                          You can train this task with samples like:

                          • What is my status this year?
                          • Mileage information
                          • How many miles did I do this year?
                          • What is my status this year?
                          • How many miles do I have left?
                          • Status
                          • Miles
                          • What is my mileage for the year?
                          • How many miles did I fly this year?
                          • Status information

                          explore_dining_options

                          training.png

                          You can train this task with samples like:

                          • What are my dining options?
                          • Where should I get food?
                          • Where can I get a bite?
                          • Dinner options
                          • Eat
                          • Where should I eat?
                          • Where should we eat lunch at the airport?
                          • What are some good places to eat at the airport?
                          • Food
                          • Food options

                          7. Build a Model

                          build a model.png

                          Next, hit the Build model button that will pop up in an alert. When you make changes to your training data, like adding and deleting samples and fields, or add new Tasks or change Task names, remember to build a new model each time so these changes take effect. The alert will automatically be displayed when you make changes to your bot's configuration.

                          Congratulations! You’ve successfully programmed and trained your bot to perform new tasks for the user. You can now test it using the Simulator in the console.

                          autopilot_simulatorpng

                          8. Configure Messaging Channels

                          Autopilot’s omni-channel capabilities allow you to deploy your bot to the messaging channel of your choice without writing additional code for each channel. There are two ways you can do this — directly configuring your bot with the messaging channel or using the Autopilot Studio Widget.

                          If you’re using one or more messaging channels through Flex, you should use the Autopilot Studio Widget to connect messaging channels to your bot. Refer to the guide How to hand-off messaging conversations from Autopilot to your Contact Center for how to do that.

                          Programmable Chat

                          chat config.png

                          Direct Configuration

                          1. Go to the Channels page in the navigation menu in the console.
                          2. Select Programmable Chat.
                          3. Copy the Chat URL automatically generated for your bot. This URL is unique to each bot.
                          4. Conversations in Programmable Chat take place within channels. The Programmable Chat API allows you to set a webhook on each channel to be notified of new activity within the channel. Configure the Chat URL copied in step 3 as the webhook URL on the channels you want your bot to join.
                          POST /Services/ISXXX/Channels/CHXXX/Webhooks/
                          

                          request parameters

                          属性

                          Type

                          Webhook

                          Configuration.Url

                          {Your Autopilot Programmable Chat URL}

                          Configuration.Method

                          POST

                          Configuration.Filters

                          onMessageSent

                          Example API Request

                          curl -X POST 'https://chat.twilio.com/v2/Services/{ChatServiceSid}/Channels/{ChannelSid}/Webhooks/' \
                          -d "Type=webhook" \
                          -d "Configuration.Url={ProgrammableChatURL}" \
                          -d "Configuration.Method=POST" \
                          -d "Configuration.Filters=onMessageSent" \
                          -u {AccountSid}:{token}
                          

                          Make sure to replace:

                          {ChatServiceSid} - with the Chat Service Instance Sid you are using

                          {ChannelSid} - with the Channel you created for the user

                          {AccountSid} - with the Account Sid

                          {Assistant Sid} - with the Autopilot Assistant Sid

                          {ProgrammableChatURL} - with your Assistant's Programmable Chat URL (Channels -> Programmable Chat in Console)

                          You can also learn more about configuring Programmable Chat in the documentation.

                          Studio Widget

                          studio dashboard.png

                          1. Copy the Flow SID of the Studio flow that contains your Autopilot Studio Widget.
                          2. Similar to step 4 in the Direct Configuration approach, configure the webhook on each channel to point to the Studio flow so that your bot can receive new messages.
                          POST /Services/ISXXX/Channels/CHXXX/Webhooks/
                          

                          request parameters

                          属性

                          Type

                          studio

                          Configuration.FlowSid

                          FWxxxxxxxxx

                          Example API Request

                          curl -X POST 'https://chat.twilio.com/v2/Services/{ChatServiceSid}/Channels/{ChannelSid}/Webhooks/' \
                          -d "Type=studio" \
                          -d "Configuration.FlowSid={FlowSid}" \
                          -u {AccountSid}:{token}
                          

                          Make sure to replace:

                          {ChatServiceSid} - with the Chat Service Instance Sid you are using

                          {ChannelSid} - with the Channel you created for the user

                          {AccountSid} - with the Account Sid

                          {Assistant Sid} - with the Autopilot Assistant Sid

                          {Flow Sid} - with the Studio Flow Sid

                          New messages posted in the Chat Channel will create a new Studio Execution, enabling the Studio Flow to interact with the Chat user.

                          SMS

                          SMS config.png

                          Direct Configuration

                          1. Go to the Channels page in the navigation menu in the console.
                          2. Select Programmable Messaging.
                          3. Copy the Messaging URL automatically generated for your bot. This URL is unique to each bot.
                          4. Go to the Phone Numbers page in the console and select the phone number you want to use, or buy a new one.
                          5. In the configuration menu for the phone number, under Messaging, select Webhook for ‘A Message Comes In’ and paste the URL you just copied.
                          6. Start testing your bot!

                          Studio Widget

                          studio widget.png

                          (Refer to the Hand-off messaging conversations from Autopilot to your Contact Center guide for step-by-step instructions on using Autopilot in Studio)

                          1. Open the Studio flow containing your Autopilot bot.
                          2. Click on the Trigger widget and copy the Webhook URL.
                          3. Similar to step 4 in the Direct Configuration approach above, navigate to the phone numbers page and paste the Webhook URL. Alternatively, you can select Studio Flow in the drop down instead of Webhook and select the right flow
                          4. Start testing your bot!

                          WhatsApp

                          The process for deploying your bot on WhatsApp is nearly identical to the one for SMS, with the only difference being that instead of pointing the Messaging URL or Studio Webhook to an SMS-enabled phone number, you need to point them to your WhatsApp Sender.

                          Learn how to use WhatsApp with Autopilot here.

                          Facebook Messenger

                          The process for deploying your bot on Facebook Messenger is nearly identical to the one for SMS, with the only difference being that instead of pointing the Messaging URL or Studio Webhook to an SMS-enabled phone number, you need to point them to the Facebook Messenger Channel you’ve configured in the Twilio Console.

                          Learn how to use Facebook Messenger with Autopilot here.

                          Slack

                          The process for deploying your bot on Slack is nearly identical to the one for SMS, with the only difference being that instead of pointing the Messaging URL or Studio Webhook to an SMS-enabled phone number, you need to create a custom integration in your Slack instance and point the Messaging URL or Studio Webhook to it.

                          Learn how to use Slack with Autopilot here.

                          Keep Building!

                          • Add some more tasks, like a customer satisfaction survey or the ability to check in to your flight.
                          • Learn how to hand-off tasks to a Flex agent.
                          • Explore the Autopilot documentation.

                          Pranav Deshpande Lizzie Siegle Nico Acosta Kat King
                          Rate this page:

                          ヘルプが必要ですか?

                          誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。