Make a Phone Call with a Duration Limit Using Python and Twilio Programmable Voice

August 12, 2021
Written by
Reviewed by

Make a Phone Call with a Duration Limit Using Python and Twilio Programmable Voice

Twilio Programmable Voice allows you to make programmatic voice calls directly from your application. This service was recently expanded to support a call duration limit, which can be a useful way to avoid unexpected expenses from calls that remain connected for a long time.

In this tutorial, you’ll learn how to use Programmable Voice with Python to make a voice call with a predefined maximum duration.

Prerequisites

Setting up your environment

In this section, you are going to set up a brand new Python project. To keep things nicely organized, open a terminal or command prompt, find an appropriate location, and create a new directory where the project you are about to create will live. Then switch to that directory:

mkdir phone-call
cd phone-call

Creating a virtual environment

Following Python best practices, you are now going to create a virtual environment, where you are going to install the Python dependencies needed for this project.

If you are using a Unix or MacOS system, open a terminal and enter the following commands to do the tasks described above:

python3 -m venv venv
source venv/bin/activate
pip install --upgrade twilio

If you are following the tutorial on Microsoft Windows, enter the following commands in a command prompt window:

python -m venv venv
venv\Scripts\activate
$ pip install --upgrade twilio

The only Python package needed by this project is the Twilio Python Helper library, which is used to work with phone calls. Call duration limits are a fairly new addition at the time I’m writing this article. Make sure the version of the Twilio Python helper library is 6.63.0 or newer.

Defining Twilio credentials

To be able to access the Twilio service, the Python application will need your Twilio account credentials to log in and authenticate. The most secure way to define these credentials is to add them as environment variables.

The information that you need is the “Account SID” and the “Auth Token”. You can find both on the main dashboard of the Twilio Console:

Twilio account SID and auth token

In your terminal, define two environment variables called TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN and set them to your account credentials:

export TWILIO_ACCOUNT_SID=xxxxxxxxx
export TWILIO_AUTH_TOKEN=xxxxxxxxx

If you are following this tutorial on a Windows computer, use set instead of export to define your environment variables in the command prompt.

If you want to learn more about other ways to set environment variables for Python applications, check out the Working with Environment Variables in Python tutorial.

Buying a Twilio phone number

To be able to make a phone call, you need to have a phone number associated with your Twilio account to call from. Log in to the Twilio Console, select Phone Numbers, and then click on the red plus sign to buy a Twilio number. If you are using a free account you will be using your trial credit for this purchase.

In the “Buy a Number” screen, select your country and check “Voice” in the capabilities field. If you’d like to request a number from your region, you can enter your area code in the “Number” field.

Buy a Twilio phone number

Click the “Search” button to see what numbers are available, and then click “Buy” for the number that you like from the results. After you confirm your purchase, click the “Close” button.

Making a phone call in Python

Fire up your text editor or IDE and create a new Python file named call.py in the phone-call directory you created at the start of the tutorial.

Enter the following code in this file:

from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse

client = Client()

twiml = VoiceResponse()
twiml.say('Hello, from Python!')

call = client.calls.create(
    from_='<your-twilio-phone-number>',
    to='<your-phone-number>',
    twiml=str(twiml),
)

Make sure you update the following parts of the above code snippet:

  • Replace the value of the from_ argument with your Twilio phone number
  • Replace the value of the to argument with your personal phone number

Both phone numbers should be entered in the E.164 format, which includes a plus sign and country code.

You may be wondering what the twiml variable is for. TwiML is Twilio’s markup language, an extension to XML that is used to specify instructions on how you want certain events to be handled. The Twilio helper library for Python comes with a set of classes and methods that simplify the creation of TwiML.

When a call is made from the Twilio phone number you purchased earlier, Twilio will execute the instructions provided in the TwiML VoiceResponse object. For this example, the say() method tells Twilio to speak the given message using a text-to-speech voice. When Twilio completes all the instructions given as TwiML, the call is ended.

Head back to your terminal, make sure you have defined the environment variables with your Twilio credentials as indicated above, and then run the script as follows:

python call.py

Your personal phone will ring in just a few moments. When you answer the call, you’ll hear “Hello, from Python!”.

Connecting to another number

The TwiML language for Programmable Voice has support for an extensive list of operations. Let’s make the call.py script a bit more interesting. Let’s say we are extremely lazy and want to call someone without having to dial their number. Through TwiML, you can ask Twilio to call you and connect you to the other party as soon as you pick up the phone:


from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse

client = Client()

twiml = VoiceResponse()
twiml.dial('<a-friend's-phone-number>')

call = client.calls.create(
    from_='<your-twilio-phone-number>',
    to='<your-phone-number>',
    twiml=str(twiml),
)

In this updated version of call.py the say() method was replaced with the dial() method, which, as its name implies, dials a number and connects you to it.

Remember to replace the phone number placeholders in the code above before running the application. If you don’t have anybody to call and are located in the United States, you can use the number +13034997111, which is a Telephone Time-Of-Day Service maintained by NIST. If you are of a certain age, this is going to bring back memories!

Give this application a try:

python call.py

When your phone rings, pick up the call and you’ll be automatically connected to the phone number you specified in the TwiML instructions.

Setting a call duration

The call.py application can be used as a lazy person’s dialer, but considering that you will be charged for the Programmable Voice service, it might be a good idea to put a hard limit to the duration of the call.

By default, calls made through the Programmable Voice service have a maximum duration of four hours (for paid accounts). This limit can be extended to 24 hours in the Programmable Voices settings. The call limit for trial accounts is 10 minutes and cannot be extended.

If the maximum duration that applies to your account is too long, you can specify a per-call maximum duration in minutes. Here is a new version of call.py that sets a call duration limit of 5 minutes:


from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse

client = Client()

twiml = VoiceResponse()
twiml.dial('<a-friend's-phone-number>')

call = client.calls.create(
    from_='<your-twilio-phone-number>',
    to='<your-phone-number>',
    twiml=str(twiml),
    time_limit=300,
)

The time_limit argument added to the call will make sure that the call is disconnected at the specified time. The time limit value is given in seconds. You can make sure the time limit is working by setting a short value (for example use 60, for a one minute duration) and waiting on the call until the connection is ended.

Conclusion

In this tutorial you’ve learned how to make a phone call from a Python application and make sure the call does not extend past a predetermined duration. But this is just the beginning. Be sure to check the TwiML reference to find out how you can do lots of other cool things with your phone calls!

Miguel Grinberg is a Principal Software Engineer for Technical Content at Twilio. Reach out to him at mgrinberg [at] twilio [dot] com if you have a cool project you’d like to share on this blog!