Working with TwiML

TwiML controls live phone calls and respond to text messages in real time through Twilio’s API.

When an SMS or incoming call is received, Twilio asks your web application for instructions by making an HTTP request. Your application decides how the call should proceed by returning a Twilio Markup XML (TwiML) document telling Twilio to say text to the caller, send an SMS message, play audio files, get input from the keypad, record audio, connect the call to another phone and more.

You can create TwiML documents in Apex using the verb classes defined inside the TwilioTwiML class.

Generating TwiML in Apex

TwiML creation begins with the TwilioTwiML.Response class. Each successive TwiML command is created by adding additional verb classes such as Say or Play to the response using append(). When your instruction set is complete, call Response.toXML() to produce a TwiML document.

TwilioTwiML.Response r = new TwilioTwiML.Response();
r.append(new TwilioTwiML.Say('Hello'));

Sometimes you’ll want to set properties beyond what’s covered in the constructor. In these cases, assign the verb class to its own variable and set its properties before appending it to the response.

TwilioTwiML.Response r = new TwilioTwiML.Response();
TwilioTwiML.Play p = new TwilioTwimL.Play('');
  <Play loop="3"></Play>

You can provide multiple actions in sequence simply by appending more verbs to the response. Some verbs can be nested inside other verbs, like Say inside of Gather.

TwilioTwiML.Response r = new TwilioTwiML.Response();
r.append(new TwilioTwiML.Say('Hello'));
TwilioTwiML.Gather g = new TwilioTwiML.Gather();
g.append(new TwilioTwiML.Say('World');
  <Gather finishOnKey="4"><Say>World</Say></Gather>

Serving TwiML Requests from a Site

  1. Create the following Apex page controller MyTwiMLController:
public class MyTwiMLController {

  public MyTwiMLController() {}

  public String getTwiml() {
    TwilioTwiML.Response res = new TwilioTwiML.Response();
    res.append(new TwilioTwiML.Say('Hello, Monkey!'));
      new TwilioTwiML.Play(''));
    res.append(new TwilioTwiML.Hangup());
    return res.toXML();
  1. Create the following Visualforce page TwiMLPage:
<apex:page controller="TwiMLPage"
  >{! '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' }
  1. In Salesforce, go to Setup | App Setup | Develop | Sites and create a new site. Set the home page to TwiMLPage to the list of Site Visualforce Pages. Ensure you activate the site.
  2. Log into your Twilio account. Go to Numbers, buy a phone number, and set the Voice Request URL to the URL of your Visualforce page on your Site – for example,
  3. Test your app by calling the phone number.

Now you have the sample page working, you have a starting point for a TwiML app running on Examine TwilioSamplePage and TwilioSampleController to see how the sample app is put together.

More Information

The complete list of TwiML verbs and attributes is available in the Twilio Markup Language documentation.