Twilio is launching a new Console. Some screenshots on this page may show the Legacy Console and therefore may no longer be accurate. We are working to update all screenshots to reflect the new Console experience. Learn more about the new Console.
In this guide we'll show you how to use Twilio Programmable Voice to record phone calls with your Python web application.
We'll learn how to record both inbound and outbound calls. In both examples we'll use Twilio's Python SDK.
When a phone number you have bought through Twilio receives an incoming call, Twilio will send an HTTP request to your web application asking for instructions on how to handle the call. Your server will respond with an XML document containing TwiML that instructs Twilio on what to do with the call. Those instructions can direct Twilio to read out a message, play an MP3 file, make a recording and much more.
To start answering phone calls, you must:
If you are sending SMS messages to the U.S. or Canada, before proceeding further please be aware of updated restrictions on the use of Toll-Free numbers for messaging, including TF numbers obtained by purchasing them. These restrictions do not apply to Voice or other uses outside of SMS messaging. Please click here for details.
In the Twilio Console, you can search for and buy phone numbers in countries around the world. Numbers that have the Voice capability can make and receive voice phone calls from just about anywhere on the planet.
Once you purchase a number, you'll need to configure that number to send a request to your web application. This callback mechanism is called a webhook. This can be done in the number's configuration page.
Webhooks are user-defined HTTP callbacks. They are usually triggered by some event, such as receiving an SMS message or an incoming phone call. When that event occurs, Twilio makes an HTTP request (usually a POST
or a GET
) to the URL configured for the webhook.
To handle a webhook, you only need to build a small web application that can accept the HTTP requests. Almost all server-side programming languages offer some framework for you to do this. Examples across languages include ASP.NET MVC for C#, Servlets and Spark for Java, Express for Node.js, Django and Flask for Python, and Rails and Sinatra for Ruby. PHP has its own web app framework built in, although frameworks like Laravel, Symfony and Yii are also popular.
Whichever framework and language you choose, webhooks function the same for every Twilio application. They will make an HTTP request to a URI that you provide to Twilio. Your application performs whatever logic you feel necessary - read/write from a database, integrate with another API or perform some computation - then replies to Twilio with a TwiML response with the instructions you want Twilio to perform.
TwiML is the Twilio Markup Language, which is just to say that it's an XML document with special tags defined by Twilio to help you build your SMS and voice applications. TwiML is easier shown than explained. Here's some TwiML you might use to respond to an incoming phone call:
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Say>Thanks for calling!</Say>4</Response>
And here's some TwiML you might use to respond to an incoming SMS message:
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Message>We got your message, thank you!</Message>4</Response>
Every TwiML document will have the root <Response> element and within that can contain one or more verbs. Verbs are actions you'd like Twilio to take, such as <Say> a greeting to a caller, or send an SMS <Message> in reply to an incoming message. For a full reference on everything you can do with TwiML, refer to our TwiML API Reference.
Now comes the fun part — writing Python that will handle an incoming HTTP request from Twilio!
In this example we'll use the Flask web framework to respond to Twilio's request. We'll then use TwiML to tell Twilio how to handle the call.
1from flask import Flask2from twilio.twiml.voice_response import VoiceResponse34app = Flask(__name__)567@app.route("/record", methods=['GET', 'POST'])8def record():9"""Returns TwiML which prompts the caller to record a message"""10# Start our TwiML response11response = VoiceResponse()1213# Use <Say> to give the caller some instructions14response.say('Hello. Please leave a message after the beep.')1516# Use <Record> to record the caller's message17response.record()1819# End the call with <Hangup>20response.hangup()2122return str(response)2324if __name__ == "__main__":25app.run()
This code is generating the \<Record>
TwiML verb, check the documentation for additional options and configuration. You can find all recordings in your console. In addition, you can make use of callbacks to be notified when a recording is ready for use.
Next up, we'll record an outgoing call by writing a little Python. First, we'll need to retrieve the credentials for our Twilio account.
First, you'll need to get your Twilio account credentials. They consist of your AccountSid and your Auth Token. They can be found on the home page of the console.
Just pass an extra argument, record
, to the client.calls.create
method and Twilio will record the entire phone call.
1# Download the helper library from https://www.twilio.com/docs/python/install2import os3from twilio.rest import Client45# Find your Account SID and Auth Token at twilio.com/console6# and set the environment variables. See http://twil.io/secure7account_sid = os.environ["TWILIO_ACCOUNT_SID"]8auth_token = os.environ["TWILIO_AUTH_TOKEN"]9client = Client(account_sid, auth_token)1011call = client.calls.create(12record=True,13url="http://demo.twilio.com/docs/voice.xml",14to="+14155551212",15from_="+15017122661",16)1718print(call.sid)
1{2"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",3"annotation": null,4"answered_by": null,5"api_version": "2010-04-01",6"caller_name": null,7"date_created": "Tue, 31 Aug 2010 20:36:28 +0000",8"date_updated": "Tue, 31 Aug 2010 20:36:44 +0000",9"direction": "inbound",10"duration": "15",11"end_time": "Tue, 31 Aug 2010 20:36:44 +0000",12"forwarded_from": "+141586753093",13"from": "+15017122661",14"from_formatted": "(415) 867-5308",15"group_sid": null,16"parent_call_sid": null,17"phone_number_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",18"price": "-0.03000",19"price_unit": "USD",20"sid": "CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",21"start_time": "Tue, 31 Aug 2010 20:36:29 +0000",22"status": "completed",23"subresource_uris": {24"notifications": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications.json",25"recordings": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Recordings.json",26"payments": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Payments.json",27"events": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Events.json",28"siprec": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Siprec.json",29"streams": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Streams.json",30"transcriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Transcriptions.json",31"user_defined_message_subscriptions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UserDefinedMessageSubscriptions.json",32"user_defined_messages": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/UserDefinedMessages.json"33},34"to": "+14155551212",35"to_formatted": "(415) 867-5309",36"trunk_sid": null,37"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Calls/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json",38"queue_time": "1000"39}
Once the call is complete, you can listen to your recordings in your Twilio Console or access them directly through Twilio's REST API.
You can also receive a Webhook request when your recording is ready by passing a RecordingStatusCallback
URL with your client.calls.create
command. Twilio will send a request to the URL you specified, and that request will include a link to the recording's audio file: look for the RecordingUrl
field.
You can learn more about the RecordingStatusCallback
parameter in the Making Calls reference docs.
We just learned to record inbound and outbound phone calls using Twilio Programmable voice and Python. If you'd like to learn more about how you can use Twilio and Python, check out these handy guides: