Using Twilio Functions to Enhance Studio Voice Calls with Custom TwiML

Studio and Functions Together

Studio is Twilio's visual application builder for communication workflows. It provides built-in widgets that you can drag, drop, and connect together to quickly develop robust applications without manually building TwiML.

But for some unique use cases, Studio's widgets alone aren't sufficient to meet all the requirements. That's where Twilio Functions can help.

Functions are small units of server-side code that you write in Node.js and run directly in our cloud, and they natively integrate with Studio Flows so you can add fully customized TwiML responses to your Voice calls.

Returning Custom TwiML with Run Function

To return custom TwiML in your Studio Flow, add the Run Function widget and select the Function from the drop-down that generates your desired TwiML.

Example Function Returning TwiML:

exports.handler = function(context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
twiml.say('Hello World');
callback(null, twiml);
}

Studio will automatically detect that this Function returned TwiML, and it will pass that TwiML directly to Programmable Voice for handling the live call.

Passing Control to a Function and Redirecting Back

After Studio returns custom TwiML from a Function, Studio needs to regain control and continue processing the rest of your widgets.

To regain control, first add a Say/Play widget as a placeholder after the Run Function widget (the message itself will be skipped).

Then, when your custom TwiML is finished, use the <Redirect> verb to return control back to the Studio Flow's Webhook URL with ?FlowEvent=audioComplete appended.

Example Function with Redirect TwiML:

exports.handler = function(context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
twiml.say('Hello World');
twiml.redirect('https://webhooks.twilio.com/v1/Accounts/ACxxxx/Flows/FWxxxx?FlowEvent=audioComplete');
callback(null, twiml);
}

When Studio receives the ?FlowEvent=audioComplete redirect, it will trigger the Audio Complete transition of the placeholder Say/Play widget (without actually playing the message), and continue with the rest of your Flow's widgets.

Example Flow for Redirecting Back from Custom TwiML:

Using this technique, you can temporarily hand off control of the call to a Function, a TwiML Bin or another Twilio Voice application and then return control back to your Studio Flow.

Note: To avoid stuck Executions when using custom TwiML, be sure to set the Studio Flow Webhook URL as the Status Callback and Fallback URL in your Twilio Phone Number configuration.

 

 

Have more questions? Submit a request
Powered by Zendesk