Using Twilio Functions to Add Custom JavaScript Code in Studio Flows

June 11, 2018
Written by

Twilio Studio

Twilio Studio makes it easy to manage voice call flows with its visual user interface. A Studio flow typically starts with a trigger event such as an incoming call to your Twilio phone number. The tutorial Forward Call with Studio has an Incoming Call as the trigger followed by a Connect Call To (forward_call) widget that forwards the call to a person’s phone number (see following screen print). The above flow, adds logic in between the trigger and the forward_call widget. This article is how to add logic using a Studio Run Function widget to call a Twilio Function, followed by a Split widget.

Building logic into the flow gives Studio more power to route calls to various destinations. The example here, is to choose between routing a call to the main office phone during business hours, or to voicemail after business hours.

In the my example flow, Business_hours is a Studio Run Function widget that calls a Twilio Function. The Function compares the current time of day with the company’s business hours, and returns the result: “open” or “after”. If the result equals “open”, then the Split widget (split_1), routes to the call to the foward_call widget. If the result is not “open” (“after”), then split over to the say_after_hours widget. Rather than the simple call forwarding flow of the tutorial, Forward Call with Studio, the Function’s logic and the Split widget make this new example an intelligent call forward.

To create a forward with logic:

  • Create a Twilio Function to Check if the current time is during business hours.
  • Build a Studio flow that uses the Function.
  • Configure your Twilio phone number to use the flow.
  • Test by calling the number.

 

Create a Twilio Function to check if the current time is during business hours

First, include the moment-timezone module for Daylight Saving Time. In Twilio Console, go to Functions → Configuration. In the Dependencies section, click the circle icon (circle with a ‘+‘ in the middle) to import a new NPM module. Enter, NAME: moment-timezone, and VERSION: 0.5.14, as shown in the screen print:


Then create a new Twilio Function in Functions → Manage.
Click the circle icon (circle with a ‘+‘ in the middle) to create a Blank function. Give the function a name “Business hours” and set the /path to /businesshours. Paste the following code into the Function, and then click Save.
exports.handler = function(context, event, callback) {
    // With timezone:
    // In Functions/Configure, add NPM name: moment-timezone, version: 0.5.14
    // Timezone function reference: https://momentjs.com/timezone/
    let moment = require('moment-timezone');
    //
    // timezone needed for Daylight Saving Time adjustment
    let timezone = event.timezone || 'America/Los_Angeles';
    console.log("+ timezone: " + timezone);
    //
    const hour = moment().tz(timezone).format('H');
    const dayOfWeek = moment().tz(timezone).format('d');
    if ((hour >= 9 && hour < 17) && (dayOfWeek >= 1 && dayOfWeek <= 5)) {
        // "open" from 9am to 5pm, PST.
        response = "open";
    } else {
        response = "after";
    }
    theResponse = response + " : " + hour + " " + dayOfWeek;
    console.log("+ Time request: " + theResponse);
    callback(null, theResponse);
};

The Function use the default timezone (America/Los_Angeles), or the timezone given as a parameter, to determine the current time of day. Then, the if statement checks if the current time is within the business hours (hour >= 9 && hour < 17), Monday to Friday (dayOfWeek <= 5). If the current time is, then return “open”, else return “after”.

As a quick test, copy the Function’s URL(example: https://about-time-1235.twil.io/businesshours) and paste it into a new browser tab. Hit enter and see the result, example: “open : 16 5”, which means that the time is within the business hours (“open”) and the local time is 4pm, on day 5, which is Friday. Also, log information is listed below the code, in the Business hours Manage Function page.

Build a Studio flow that uses the Function

To re-create the sample Studio flow, first, create the Business hours Twilio function, steps following. Then, go to the Studio dashboard , click the Create new Flow icon. Name the flow, Business hours, click Next. Keep the default, Start from Scratch, and click Next. In Studio flow canvas, drag in a Run Function widget. Connect the Trigger’s Incoming Call to the Run Function. For the widget, set the Name to, Business_hours; and select the Business hours Function. Beside Function Parameters, click the plus sign to add a parameter. Enter, timezone, as the Key. Enter, America/Los_Angeles, as the value. Click Add Parameter. When the Function is called, the name value pair, timezone and America/Los_Angeles, will be passed to the Function.

Drag a Split widget onto the canvas, below the Run Function widget. Connect the Run Function widget’s Success transition, to the Split widget. In the Split widget, set the to Business_hours.body. For the Split Transitions, add a New Condition: Starts with, “open”. Click Set condition. Click Rename, and rename the transition condition to “open”. Click Set condition.

Drag a Connect Call To widget onto the canvas, below the Split widget. Connect the Split widget’s open transition, to the Connect Call To widget. Set the widget name to: forward_call. For testing, set the Connect Call to: Single Number, and your mobile phone number.

Drag a Say/Play widget onto the canvas, beside the Connect Call To widget. Connect the Connect Call To widget’s No Condition Matches transition, to the Say/Play widget. Set the Say/Play widget name to: say_after_hours. Set the text to, “You have called after hours. Please call back during our business hours: 9 am to 5 pm, Monday to Friday.”

Now, if the response is “open”, as in, “Open for business at this time,” then the business_hours widget is call. If the response is “after”, as in, “It’s after business hours at this time,” then the After_hours widget is call.

When you call your Twilio phone number, Twilio check the number’s configuration and passes the control to the Studio flow. The Run Function widget calls the Business hours Function, which returns the string: “open”, because it’s 4pm, on Friday, still within business hours. The Split widget uses the Function’s result to decide the flow path. Since the result is “open”, the Split send the call to the Business_hours widget.

It’s straightforward to integrate a Twilio Function into a Studio flow which give the flow programming decision logic power.

Configure your Twilio phone number to use the flow

In the Twilio Console, go to your list of phone numbers:
https://www.twilio.com/console/phone-numbers/incoming
Click on one of the numbers. In the Configuration page, as shown in the following screen print, set Voice & Fax, A call comes in, to: Studio Flow, Business hours. Click Save.

Test by calling the number

Use a phone with number that is not used in the Business hours flow. Call your Twilio phone number. If you are outside the business hours, you will hear the message, “You have called after hours. Please call back during our business hours: 9 am to 5 pm, Monday to Friday.” Otherwise you will be connected to the forward_call widget’s phone number.

Summary

Now you can create a Studio flow with complex logic. The combination of a Run Function widget followed by Split widget is a powerful combination. A Twilio Function gives you full programming capabilities to add decision making into your Studio flow. And since the Spit widget is the equivalent of an if-statement, you can branch your Studio flow in the directions you require.