# Route Inbound Sales Leads with Twilio Studio

Route inbound sales leads to the right person with Twilio Studio and Twilio Functions. In this example, you'll build a system that routes callers to representatives based on how large their company is. The application will do the following:

* Respond to an incoming phone call from a potential customer
* Collect input from the caller about the number of employees at their company
* Send that number to a Twilio Function, which will then fetch the contact information for the correct representative based on the user's input
* Connect the caller to correct representative over the phone

## Prerequisites

Before you get started, you'll need:

* A Twilio Account. If you are new to Twilio [create a free account](https://www.twilio.com/try-twilio). You can review the [features and limitations of a free Twilio account here](/docs/usage/tutorials/how-to-use-your-free-trial-account).
* A Twilio Phone Number. View instructions for [purchasing a Twilio Phone Number here](/docs/usage/tutorials/how-to-use-your-free-trial-account#get-your-free-twilio-phone-number).

## Create your Flow

You'll start with a new Twilio Studio Flow. A Flow is an individual workflow you create to handle your use case. For example, in this case we're going to be creating an autoresponder workflow, which responds to an incoming message with another message. All the logic for this will exist in the Twilio Studio Flow you create.

To create a new Flow:

1. Log into your Twilio account in the Twilio Console
2. Navigate to the [Studio Dashboard](https://www.twilio.com/console/studio/) in the Console
3. Click the **+** icon underneath the **Flows** heading to create a new Flow

   ![Create new flow button in the Console.](https://docs-resources.prod.twilio.com/e729f0ac27ddd1b6852efb67c4f6bf5a9f578e8a110d7623b8509fed17f37d7e.png)
4. Next, you'll name your Flow. You can name it anything you like. In this example, we're calling it "Lead Routing". Then, click **Next**.
5. After you've named your Flow, you'll see a list of possible templates you can use. In this case, you'll start with an empty Flow and build all the logic for it yourself, so you should select the **Start from scratch** option. Then, click **Next**.

After you've created the Flow, you'll see the Flow's Canvas. The Canvas is where you will build out the rest of the logic for the autoresponder.

### Navigate the Canvas

To build this Flow, you're going to be adding widgets onto the Canvas. A widget is an individual item that performs a specific task. There are widgets for actions like sending text messages, making a phone call, playing a sound file, making an HTTP request, and more. You can see the [full list of available widgets here.](/docs/studio/widget-library)

#### Trigger widget

The Canvas starts with a [Trigger widget](/docs/studio/widget-library/trigger-start) already in place. This widget kicks off the Flow when the trigger you specify happens. In this case, the trigger is going to be an Incoming Call.

In a later step, you'll configure a specific Twilio phone number to connect to this Studio Flow. Then, whenever a call comes into that Twilio number, this Flow will run because you specified that the trigger should be an Incoming Call.

#### Widget Library and widget Configuration

On the right-hand side of the Canvas, you'll see the Widget Library. This menu contains all the possible widgets you can add to your Canvas to build your Studio Flow.

![Widget library.](https://docs-resources.prod.twilio.com/8d96ff308e50a9d14ef370e8472f128f9e97e709740fcb1a241abae2777515c7.png)

When you click onto a specific widget (for example, if you click onto the Trigger widget that's already on the Canvas), this menu on the right will switch to the specific widget's configuration menu. This is where you can edit the widget.

![Lead Routing Flow configuration.](https://docs-resources.prod.twilio.com/43c46707dfa1b8284b621ba44786512dfe57400278a200560921151dfeb4e30a.png)

To get back to the Widget Library, you can click on any empty space on the Canvas, and the menu will switch back to the list of available widgets. You can then click back onto a widget to get into its configuration menu.

## Gather input from a caller

The first widget you'll add to the page is the **[Gather Input on Call widget](/docs/studio/widget-library/gather-input-call)**. This widget can collect input from a caller either via speech recognition or [DTMF](/docs/glossary/what-is-dtmf) keypresses (when the user presses number keys on their phone).

From the Widget Library on the right side of the page, click and hold the Gather Input on Call widget, drag it onto the Canvas, and drop it anywhere. Once it's on the Canvas, you can move it wherever you'd like by clicking and dragging it.

### Connect the Incoming Call trigger to the new widget

First, you'll connect the Gather Input on Call widget to the Incoming Call trigger, so that when a call comes in, the Studio Flow knows to run this first widget.

Click and hold the red dot under **Incoming Call** in the Trigger widget. While clicking and holding, drag that red dot onto the Gather Input on Call widget you just placed. This will create a line connecting the two widgets, with an arrow showing the direction that the workflow logic goes. In this case, the Canvas shows that when an incoming call comes in, it triggers the Flow and runs the Send Message widget.

### Configure the Gather Input on Call widget

With this widget, you'll prompt the user to enter the number of employees in their company, so that you can route the call to the correct representative.

Click on the widget on the Canvas to open its configuration menu. You can change the default widget name to something meaningful, for example, `get_company_size`. Then, under the **Say or Play a Message** dropdown, select "Say a Message". Type your question into the **Text To Say** field. This example will use the following question:

```text
How many employees does your company have? (Say or type a number)
```

You can optionally select the language that this message is in (the default is English) and the voice to speak this voice message with. The widget uses Text-to-Speech to speak the message to the caller. [Learn more Text-to-Speech and the different available voices and languages here.](/docs/voice/twiml/say/text-speech)

At this point, your Canvas should look like this.

![Twilio Studio Tutorial Route Leads Gather input on call widget on canvas named get\_company\_size.](https://docs-resources.prod.twilio.com/63d92973e3d08a45bf49047311c4747124eda59792b9b31001d40b47aff2262d.png)

### Handle user input

Callers can respond to the Gather Input on Call widget in two ways:

* Saying a number
* Pressing a number key

You'll handle both cases in the next steps.

### Handling speech input on the call

#### Retrieve Input

First, you'll handle the case where the user says something in response to the widget's prompt.

It's possible that someone might say something that isn't a number, so you'll have to handle the case where the user says something that does not match what you asked. To do this, you can use the **[Split Based On… widget](/docs/studio/widget-library/split-based-on)**. This widget can check a value (in this case, what the user said) and perform different actions based on specific conditions you define.

1. Open the Widget Library by clicking on an empty space on the Canvas, and then drag the Split Based On... widget onto the Canvas.
2. Click on the new Split Based On... widget you added to open its configuration menu. You can change the default name to something that makes more sense for the widget; for example, `check_for_number`.
3. Then, set the **Variable To Test** to the `SpeechResult` from your Gather Input on Call widget — in this case, that would be `{{widgets.get_company_size.SpeechResult}}`

> \[!NOTE]
>
> Twilio Studio uses the Liquid templating language to allow you to add dynamic content to your widgets. The curly braces `{{...}}` indicate that you are referencing a variable from the Studio Flow. See more in the [Liquid Template Language documentation](/docs/studio/user-guide/liquid-template-language).

The condition match we'll be checking for answers the question "is this a number?" so we'll use a regex to check this. A regex checks that the provided input conforms to a pattern that is specified. Create a new Transition, select Regex from the dropdown, and enter `^[0-9]*$` in the next field. This regex pattern checks if the provided input is a numeric digit.

![Twilio Studio Route leads using Split Based On... widget to check SpeechResult from get\_company\_size widget.](https://docs-resources.prod.twilio.com/a679810f53e905fa87f154d498a213748e2e368b447f28765f4b5aaac5a48808.png)

First, handle the "not a number" case. Drag a new **[Say/Play widget](/docs/studio/widget-library/sayplay)** onto the Canvas and connect it to the `No Condition Matches` transition from the Split Based On... widget. Enter a message of your choosing, then connect the Audio Complete dot back to the Gather widget from earlier so the user is re-prompted to say or type a number. This example will use the following message:

```text
I'm sorry, I don't understand what you said. I'm looking for a number.
```

![Twilio Studio Tutorial Route Leads Say/Play widget added to canvas.](https://docs-resources.prod.twilio.com/a3fde6dce4f621afc7b4dafefa954001dc5b18ebd66eb5705858e885e30e1412.png)

The next step is to handle things in the expected case — when the user says a valid number. In order to route the call to the representative, you'll need to use some logic to determine which representative should take the call and then pass the representative's phone number to the Flow. You can do this with a Twilio Function.

#### Create a Twilio Function

1. Navigate to the [Functions](https://www.twilio.com/console/runtime/functions/) section of the Twilio Console and create a new Service by pressing on **Create Service**. Name the service. This example will use `RouteLeads`.
2. Add a Function by clicking on **Add +** and selecting **Add Function**. Name the path `get-phone-number`.
3. Paste the following code into your new Function, modifying the result numbers and size criteria to fit your organization's needs.

```javascript
exports.handler = (context, event, callback) => {
    const size = event.size;
    let result = "";


    switch (true) {
        case (size < 50):
            result = '555-867-5310';
            break;
        case (size < 100):
            result = '555-867-5311';
            break;
        case (size < 1000):
            result = '555-867-5312';
            break;
        case (size > 1000):
            result = '555-867-5313';
            break;
        default:
            result = '555-867-5309';
    }

    callback(null, result);
};

```

Your Function should look somewhat like this:

![Twilio Studio Tutorial Route Leads Twilio Function in console.](https://docs-resources.prod.twilio.com/b59c953910d3e3465d347e83e450f71ff3ee62bfc360ca42476568dea7b6962c.png)

Click **Save** to save your Function. Deploy the function by clicking on **Deploy All**. You can now return to your Studio Flow.

#### Calling the Twilio Function

Drag a new **[Run Function widget](/docs/studio/widget-library/run-function)** onto the Canvas, and connect it to the dangling regex dot from the Split Based On... widget. You'll need to pass one parameter to the Function — the size that we gathered from the `SpeechResult`. Click **+** in the Function Parameters section of the right sidebar to create a new parameter and set the key to `size` and the value to the `SpeechResult` — in this sample, it's `{{widgets.get_company_size.SpeechResult}}`. Save your new parameter.

![Twilio Studio Tutorial Route Leads Run Function widget with configuration panel to the right showing function parameters.](https://docs-resources.prod.twilio.com/0bde59799b7be3d4677c2f0083f0bd153ac7cd6d3cfe492ac607403a44f4f90a.png)

#### Connecting to the retrieved phone number

Now it's time to connect the call to the rep. The Function will return a phone number for the correct rep, and you can use the **[Connect Call To widget](/docs/studio/widget-library/connect-call)** to transfer the current call to that phone number. Drag the Success dot from the Run Function widget to the new widget to connect them.

Choose a **Single Number** from the dropdown and set the next field to the result of your Function widget — in this case, `{{widgets.match_speech_to_rep.body}}`. When the Function returns a phone number, this widget will then open up a call to that number, connecting the original caller to the most appropriate rep for their company size.

![Twilio Studio Tutorial Route Leads Connect Call widget with configuration panel on the right.](https://docs-resources.prod.twilio.com/c23d783a89990f25b5d74c21f27f2a210cebcbc635f99b747ddbe8b84508ef2c.png)

### Handling keypress input on the call

Now, you need to handle keypress inputs if the user chooses to type a number instead of using the voice functionality. It's going to work mostly the same way as voice input, but since we know the user is going to be typing numbers, we don't need the Split Based On... widget.

Instead, you can go directly to the Function call. Drag another Run Function and Connect Call To widget onto the Canvas, this time setting the **size** parameter to the keypress result from your Gather widget — in this case `{{widgets.get_company_size.Digits}}`.

![Twilio Studio Tutorial Route Leads Connect To Rep From Digits using Run Function and Connect Call To widgets On Canvas.](https://docs-resources.prod.twilio.com/9013841159d2858e3ea4a79dc44138b9912fab051d9c927b43628140ee247435.png)

Your final Canvas should look something like this:

![Twilio Studio Tutorial Route Leads Full Flow.](https://docs-resources.prod.twilio.com/abe205987c2b8fe641b26c6625545d9d33b5525535cae59c06dc4a12adf43ccc.png)

### Connect the Flow to your Twilio phone number

Once you're happy with your Flow and you've published all changes, you can connect it to a Twilio Number so people can start interacting with it.

Navigate to the [Active Numbers section of the Twilio Console](https://www.twilio.com/console/phone-numbers/incoming) and click on the number you'd like to connect to the Flow. (If you do not have any phone numbers, you can [purchase one from the Console](https://help.twilio.com/hc/en-us/articles/223135247-How-to-Search-for-and-Buy-a-Twilio-Phone-Number-from-Console).)

After clicking on the number, you will see its configuration menu where you can connect the number to your Studio Flow.

To configure this number to trigger your Studio Flow from an Incoming Call, scroll down to the Voice & Fax section of the configuration menu. Under **Configure With**, select the dropdown option "Webhook, TwiML Bin, Function, Studio Flow, Proxy Service". Then, under **A Call Comes In**, select the dropdown option "Studio Flow". You'll see another dropdown menu appear where you can select the Studio Flow you'd like to connect to when a call comes in to this number.

![Voice configuration with active US1 region routing and Studio Flow selection options.](https://docs-resources.prod.twilio.com/05253aabb0c3f6c6a85836a9dd41a1804aaf525f98e31d7f2f86110b3b3b6232.png)

Choose the Flow you'd like to connect the number to, and then press **Save** to save these changes. Your Flow is now connected to your Twilio number!

You're ready to test out your Flow! Give your Twilio number a call, follow the prompt to say or enter a number, then get routed to the rep that matches the company size you stated. Ready to take things to the next level? Try modifying the Function further — accept additional inputs beyond numbers, return more information, or try this routing flow with SMS.
