Skip to contentSkip to navigationSkip to topbar
On this page

Use the Run Function widget in Studio


With their lightweight nature and ability to execute JavaScript, Functions are an excellent companion to Studio Flows. Whether you need to gather some data from an API or run any other custom code to fit your business logic, Functions help to fill in the gaps in your application that existing Studio widgets may not cover.

In order to ease the integration of Functions into your Studio Flows, Studio provides the Run Function widget. This widget, as the name implies, allows you to run a Twilio Function; you may pass in any desired parameters, and leverage any generated values later on in your Studio Flow.

To test this out we'll create a Studio Flow that accepts incoming text messages, prompts the user for their desired dog breed, and returns an MMS containing some text and an image of their requested breed (assuming they provided a valid breed). The finished flow would look like this:

Completed Studio Flow for Run Function example.

Create a Studio Flow and a user prompt

create-a-studio-flow-and-a-user-prompt page anchor

If you haven't created a Flow before, we suggest following the Create Your Flow steps in the chatbot tutorial to get one established.

Once you are inside of your newly created Studio Flow, create the prompt for dog breed by dragging a Send & Wait For Reply widget onto the Studio canvas. Name it and provide some text to prompt the user; the text can be anything you'd like for this example, something along the general lines of "which dog breed would you like to see?"

Here, we'll name the widget request-breed, and provide the following prompt:

Hello! Please respond with your requested dog breed to receive a photo! 🐶

Before we can proceed any further, we must first create the Function that we'll be calling in the next step of the Flow.


Create and host a Function

create-and-host-a-function page anchor

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page). If you need an account, you can sign up for a free Twilio account here(link takes you to an external page)!
  2. Functions are contained within Services. Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function.
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world.

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!


Install Dependencies and define the Function body

install-dependencies-and-define-the-function-body page anchor

Studio Widgets can handle the elements of gathering user input and sending back a response text. However, custom logic like handling breed names that contain spaces lives best inside of a Function.

Let's add some code to this Function. Install axios as a Dependency, copy the following code example into your Function, save, and deploy your Service so that we can look more closely at how to integrate the Run Widget into a Studio Flow.

Note that this Function expects an input of breed, and returns JSON that includes some text and an image url.

(information)

Info

If you're curious about why we're using axios and keywords such as async and await, be sure to read up on how to make API requests in Functions.

Return JSON to a Studio Flow based on input parameters

return-json-to-a-studio-flow-based-on-input-parameters page anchor
1
const axios = require('axios');
2
3
exports.handler = async (context, event, callback) => {
4
// Any parameters provided to the Function will be accessible from `event`.
5
// In Function Parameters, we defined `breed` as the inbound Body from
6
// our Send & Wait For Reply Widget. We can access that via `event.breed`.
7
// To minimize the potential for errors, lowercase and trim the user input.
8
let dogBreed = event.breed.toLowerCase().trim();
9
10
// The Dog API also supports sub-breeds, so we need to handle that case.
11
// For example, if the user requests "Golden Retriever", we need to format
12
// the breed as "retriever/golden".
13
if (dogBreed.includes(' ')) {
14
const [subBreed, breed] = dogBreed.split(' ');
15
dogBreed = `${breed}/${subBreed}`;
16
}
17
18
const dogApiUrl = `https://dog.ceo/api/breed/${dogBreed}/images/random`;
19
20
try {
21
// Make the request to the Dog API. Remember to use `await` since this
22
// is an asynchronous request!
23
const response = await axios.get(dogApiUrl);
24
// Return the response to the Send & Wait For Reply Widget.
25
return callback(null, {
26
text: `Here's an image of a ${event.breed}! 🐶`,
27
// The `message` property of the response is the URL of the dog image.
28
url: response.data.message,
29
});
30
} catch (error) {
31
// Remember to handle any errors that may occur!
32
// In the case of a 404, the breed was not found.
33
if (error.response && error.response.status === 404) {
34
return callback(null, {
35
text: `Sorry, we couldn't find any ${event.breed}s 🥲`,
36
});
37
}
38
// Otherwise, there may have been a network or server error.
39
return callback(error);
40
}
41
};

Use the Run Function widget

use-the-run-function-widget page anchor

Once your prompt is complete, drag a Run Function widget onto the canvas, and connect it to the Reply condition of the request-breed widget.

You'll be able to provide a name for the widget (get-doge-image), a configuration that will point this widget at your intended Function, and any parameters or arguments that you'd like to pass from the Flow to the Function when it's executed.

For this example, we'll point the Run Function widget at our Function, which was deployed to the doge Service in a production environment, and the path to the Function is /get-doge. Replace the Service, Environment, and Function configuration options with the values specific to the Function you created earlier.

Configuration for the Run Function widget to call the get-doge function with breed as an input parameter.

The final important configuration to note is the section labeled Function Parameters. Here, we define the parameters that we will pass to the Function's event object.

Here, we want to provide a variable called breed which is equal to the user's response to the prompt. We can do this by creating a new parameter, naming it breed, and setting the value to the user's response to the request-breed widget.

(information)

Info

We are using the Liquid template language to set a variable to the value gathered by the request-breed widget. Read the Studio guide on Liquid to learn more about this syntax and what else you can do with these expressions!


Consume the output of the Run Function widget

consume-the-output-of-the-run-function-widget page anchor

With our prompt and Run Function widgets in place, the last step is to generate a response to the user which incorporates the Function's result.

Drag a Send Message widget onto the canvas, and connect it to the Success condition of the get-doge-image widget.

The configuration for this widget is much shorter, and consists only of a name for the widget, the text body, and any media URL (s) you may want to attach. Luckily, the /get-doge Function returns text and uri values for us, so we can template these values into the config using Liquid.

In order to access the return value of a Run Function widget, you will need to access a special property called parsed. This object will contain any and all contents returned by the targeted Function.

(information)

Info

The general syntax to access a property from the result of a Run Function widget is {{widgets.<widget-name>.parsed.<property>}}.

For example, to access the text and url returned from the get-doge-image widget, the respective Liquid template strings would be the following:

1
{{widgets.get-doge-image.parsed.text}}
2
{{widgets.get-doge-image.parsed.url}}

Once you have set Message Body to {{widgets.get-doge-image.parsed.text}} and Media URL to {{widgets.get-doge-image.parsed.url}} on the Send Message widget, your configuration should look like this:

Define the configuration of the Send Message widget using liquid template values from the Run Function output.

With the Function deployed and all the widgets in the Studio Flow connected and configured, all that's left is to see this little application in action. To save all your progress on the Flow and ensure that its code is live, click Publish on the Studio canvas.

Next, connect one of your Twilio phone numbers to this Flow.

Once you have published your Flow and connected it to your Twilio phone number, send it a brief message to start the conversation. A simple "Ahoy!" will do. Respond to the incoming prompt with a breed of dog, and you will see an MMS of that breed after a momentary delay.

Flow example with a golden retriever.

Go further with loops and failure flows

go-further-with-loops-and-failure-flows page anchor

So far, while the Function code does contain some catch logic, it otherwise doesn't really have any resilience to missing breed types or even network errors, and it definitely doesn't show that to the user. To improve the experience, let's see what happens if we expand our flow to handle the fail condition of get-doge-image.

To get started, drag a new Send Message widget onto the canvas, give it a name such as send-fail-message, and connect it to the Fail transition from get-doge-image. By doing this, we're introducing an alternative flow of logic for our application in case the Function runs into an error.

To take this a step further, connect the Sent condition of the newly made send-fail-message to get-doge-image. In doing so, you've just created a loop! If the Function fails to get a dog image, the flow will send the user a message then try to re-run the Function, and will do so until it succeeds.

Set the message body to {{widgets.get-doge-image.body}} Trying again!, click Save, and finally click Publish to publish this update to the flow.

These connections and the configuration for send-fail-message should appear as shown below:

Create a retry loop by connecting the Run Function Fail transition to a Send Message widget.

With the flow updated to handle failures from our Function, let's quickly edit our code to make it artificially error-prone; only for the sake of testing, of course!

Randomly return an error instead of JSON

randomly-return-an-error-instead-of-json page anchor
1
const axios = require('axios');
2
3
exports.handler = async (context, event, callback) => {
4
// In Function Parameters, we defined `breed` as the inbound Body from
5
// our Send & Wait For Reply Widget. We can access that via `event.breed`.
6
// To minimize the potential for errors, lowercase and trim the user input.
7
let breed = event.breed.toLowerCase().trim();
8
9
// The Dog API also supports sub-breeds, so we need to handle that case.
10
// For example, if the user requests "Golden Retriever", we need to format
11
// the breed as "retriever/golden".
12
if (breed.includes(' ')) {
13
const [first, second] = breed.split(' ');
14
breed = `${second}/${first}`;
15
}
16
17
const dogApiUrl = `https://dog.ceo/api/breed/${breed}/images/random`;
18
19
try {
20
// Let's introduce some inconsistency by randomly throwing an error
21
if (Math.random() > 0.3) throw new Error('No doge~');
22
// Make the request to the Dog API. Remember to use `await` since this
23
// is an asynchronous request!
24
const response = await axios.get(dogApiUrl);
25
// Return the response to the Send & Wait For Reply Widget.
26
return callback(null, {
27
text: `Here's an image of a ${event.breed}! 🐶`,
28
// The `message` property of the response is the URL of the dog image.
29
url: response.data.message,
30
});
31
} catch (error) {
32
// Remember to handle any errors that may occur!
33
// This error message will be accessible as `widgets.get-doge-image.body`
34
return callback(`Sorry, we couldn't find any ${event.breed}s 🥲`);
35
}
36
};
(information)

Info

To get access to a returned error message, you will need to access the body property returned by the Run Function Widget. This will look like {{widgets.<widget-name>.body}} if used in a liquid template.

Deploy your Function with this updated code, and once completed, send a new message to your Twilio phone number. Between this code change and the new widget in the Studio flow, you will (most likely, this is random, of course) see one or more error messages, ultimately followed by an image of your requested dog breed!

Error recovery loop and message.

This is a very brief introduction to what is possible! Instead of a retry loop with a message, you could create an entirely new, logical flow of widgets where you ask the user for other information; your imagination is the only true limit here.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.