TwiML CreationΒΆ

TwiML creation begins with the Response verb. Each successive verb is created by calling various methods on the response, such as say() or play(). These methods return the verbs they create to ease creation of nested TwiML. To finish, call the toxml() method on the Response, which returns raw TwiML.

To get started with TwiML, read the TwiML documentation on our website.

The following code block creates a simple TwiML Response.

from twilio import twiml

r = twiml.Response()
r.say("Hello")
print str(r)

The output is perfectly formatted XML:

<?xml version="1.0" encoding="utf-8"?>
<Response><Say>Hello</Say></Response>

The verb methods (outlined in the complete reference) take the body (only text) of the verb as the first argument. All attributes are keyword arguments.

from twilio import twiml

r = twiml.Response()
r.play("https://api.twilio.com/cowbell.mp3", loop=5)
print str(r)
<?xml version="1.0" encoding="utf-8"?>
<Response>
    <Play loop="3">https://api.twilio.com/cowbell.mp3</Play>
</Response>

The Message and Sms verbs are slightly special: because from is a Python keyword, use the sender parameter to specify the number the message should come from:

from twilio import twiml

r = twiml.Response()
m = r.message("Hello MMS Monkey!", sender="+14155551234")
print str(r)
<?xml version="1.0" encoding="utf-8"?>
<Response>
    <Message from="+14155551234">Hello MMS Monkey!</Message>
</Response>

Python 2.6+ added the with statement for context management. Using with, the module can almost emulate Ruby blocks.

from twilio import twiml

r = twiml.Response()
r.say("hello")
with r.gather(finishOnKey=4) as g:
    g.say("world")
print str(r)

which returns the following

<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Say>Hello</Say>
  <Gather finishOnKey="4"><Say>World</Say></Gather>
</Response>

If you don’t want the XML declaration in your output, use the toxml() method

from twilio import twiml

r = twiml.Response()
r.say("hello")
with r.gather(finishOnKey=4) as g:
    g.say("world")
print r.toxml(xml_declaration=False)
<Response>
  <Say>Hello</Say>
  <Gather finishOnKey="4"><Say>World</Say></Gather>
</Response>