Menu

Expand
Rate 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 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

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

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:

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. If you need an account, you can sign up for a free Twilio account here!
  2. Functions are contained within Services. Create a Service by clicking the Create Service 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 accesible from:
    https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>​
    For example: test-function-3548.twil.io/hello-world.

The Serverless Toolkit enables you with local development, project deployment, and other functionality via the Twilio CLI. To get up and running with these examples using Serverless Toolkit, follow this process:

  1. From the CLI, run twilio serverless:init <your-service-name> --empty to bootstrap your local environment.
  2. Navigate into your new project directory using cd <your-service-name>
  3. In the /functions directory, create a new JavaScript file that is named respective to the purpose of the Function. For example, sms-reply.protected.js for a Protected Function intended to handle incoming SMS.
  4. Populate the file using the code example of your choice and save.
    Note A Function can only export a single handler. You will want to create separate files if you want to run and/or deploy multiple examples at once.

Once your Function(s) code is written and saved, you can test it either by running it locally (and optionally tunneling requests to it via a tool like ngrok), or by deploying the Function and executing against the deployed url(s).

Run your Function in local development

Run twilio serverless:start from your CLI to start the project locally. The Function(s) in your project will be accesible from http://localhost:3000/sms-reply

  • If you want to test a Function as a Twilio webhook, run:
    twilio phone-numbers:update <your Twilio phone number> --sms-url "http://localhost:3000/sms-reply"​
    This will automatically generate an ngrok tunnel from Twilio to your locally running Function, so you can start sending texts to it. You can apply the same process but with the voice-url flag instead if you want to test with Twilio Voice.
  • If your code does not connect to Twilio Voice/Messages as a webhook, you can start your dev server and start an ngrok tunnel in the same command with the ngrok flag. For example: twilio serverless:start --ngrok=""

Deploy your Function

To deploy your Function and have access to live url(s), run twilio serverless:deploy from your CLI. This will deploy your Function(s) to Twilio under a development environment by default, where they can be accessed from:

https://<service-name>-<random-characters>-dev.twil.io/<function-path>

For example: https://incoming-sms-examples-3421-dev.twil.io/sms-reply

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

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.

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.

        
        
        

        Use the Run Function widget

        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), 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.

        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!

        Consuming the output of the Run Function widget

        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.

        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 uri returned from the get-doge-image widget, the respective Liquid template strings would be the following:

        {{widgets.get-doge-image.parsed.text}}
        {{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

        Test it

        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. If you haven't already, click the Publish button on the Studio canvas to save all your progress on the Flow and ensure that its code is live.

        Next, you'll want to connect this Flow to one of your Twilio phone numbers. You can follow these directions in order to do so.

        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

        Rate this page:

        Need some help?

        We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.

              
              
              

              Thank you for your feedback!

              We are always striving to improve our documentation quality, and your feedback is valuable to us. Please select the reason(s) for your feedback or provide additional information about how we can improve:

              Sending your feedback...
              🎉 Thank you for your feedback!
              Something went wrong. Please try again.

              Thanks for your feedback!

              Refer us and get $10 in 3 simple steps!

              Step 1

              Get link

              Get a free personal referral link here

              Step 2

              Give $10

              Your user signs up and upgrade using link

              Step 3

              Get $10

              1,250 free SMSes
              OR 1,000 free voice mins
              OR 12,000 chats
              OR more