Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

IVR: Phone Tree with Python and Flask


ET Phone Home: IVR Python & Flask Example.

This Python Flask(link takes you to an external page) sample application is modeled after a typical call center experience, but with more Reese's Pieces(link takes you to an external page).

Stranded aliens can call a phone number and receive instructions on how to get out of earth safely, or call their home planet(link takes you to an external page) directly. In this tutorial, we'll show you the critical bits of code that make this work.

(information)

Info

To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page). You can also look at this GitHub repository(link takes you to an external page) to see how we've structured our application's file structure.

Read how Livestream(link takes you to an external page) and others(link takes you to an external page) built Interactive Voice Response with Twilio. Find source code for many web frameworks on our IVR tutorial page.


Answering a Phone Call

answering-a-phone-call page anchor

To initiate the phone tree, we need to configure one of our Twilio numbers to send our web application an HTTP request when we get an incoming call.

Click on one of your numbers(link takes you to an external page) and configure the Voice URL to point to our app. In our code, the route will be /ivr/welcome.

IVR Webhook Configuration.

If you don't already have a server configured to use as your webhook, ngrok(link takes you to an external page) is an excellent tool for testing webhooks locally.

With our Twilio number configured, we are prepared to respond to the Twilio request.


Respond to the Twilio request with TwiML

respond-to-the-twilio-request-with-twiml page anchor

Our Twilio number is now configured to send HTTP requests to this controller method on any incoming voice calls. Our app responds with TwiML to tell Twilio what to do in response to the message.

In this case, we tell Twilio to Gather the input from the caller and then Play a welcome message.

You may have noted we're using an unknown method, ``` TwiML` ``. This method comes from a custom view helper that takes a TwiML Response and transforms it into a valid HTTP Response. Check out the implementation:


_10
import flask
_10
_10
def twiml(resp):
_10
resp = flask.Response(str(resp))
_10
resp.headers['Content-Type'] = 'text/xml'
_10
return resp

Respond with TwiML to gather an option from the caller

respond-with-twiml-to-gather-an-option-from-the-caller page anchor

ivr_phone_tree_python/views.py


_97
from flask import (
_97
flash,
_97
render_template,
_97
redirect,
_97
request,
_97
session,
_97
url_for,
_97
)
_97
from twilio.twiml.voice_response import VoiceResponse
_97
_97
from ivr_phone_tree_python import app
_97
from ivr_phone_tree_python.view_helpers import twiml
_97
_97
_97
@app.route('/')
_97
@app.route('/ivr')
_97
def home():
_97
return render_template('index.html')
_97
_97
_97
@app.route('/ivr/welcome', methods=['POST'])
_97
def welcome():
_97
response = VoiceResponse()
_97
with response.gather(
_97
num_digits=1, action=url_for('menu'), method="POST"
_97
) as g:
_97
g.say(message="Thanks for calling the E T Phone Home Service. " +
_97
"Please press 1 for directions." +
_97
"Press 2 for a list of planets to call.", loop=3)
_97
return twiml(response)
_97
_97
_97
@app.route('/ivr/menu', methods=['POST'])
_97
def menu():
_97
selected_option = request.form['Digits']
_97
option_actions = {'1': _give_instructions,
_97
'2': _list_planets}
_97
_97
if option_actions.has_key(selected_option):
_97
response = VoiceResponse()
_97
option_actions[selected_option](response)
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
@app.route('/ivr/planets', methods=['POST'])
_97
def planets():
_97
selected_option = request.form['Digits']
_97
option_actions = {'2': "+19295566487",
_97
'3': "+17262043675",
_97
"4": "+16513582243"}
_97
_97
if selected_option in option_actions:
_97
response = VoiceResponse()
_97
response.dial(option_actions[selected_option])
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
# private methods
_97
_97
def _give_instructions(response):
_97
response.say("To get to your extraction point, get on your bike and go " +
_97
"down the street. Then Left down an alley. Avoid the police" +
_97
" cars. Turn left into an unfinished housing development." +
_97
"Fly over the roadblock. Go past the moon. Soon after " +
_97
"you will see your mother ship.",
_97
voice="Polly.Amy", language="en-GB")
_97
_97
response.say("Thank you for calling the E T Phone Home Service - the " +
_97
"adventurous alien's first choice in intergalactic travel")
_97
_97
response.hangup()
_97
return response
_97
_97
_97
def _list_planets(response):
_97
with response.gather(
_97
numDigits=1, action=url_for('planets'), method="POST"
_97
) as g:
_97
g.say("To call the planet Broh doe As O G, press 2. To call the " +
_97
"planet DuhGo bah, press 3. To call an oober asteroid " +
_97
"to your location, press 4. To go back to the main menu " +
_97
" press the star key.",
_97
voice="Polly.Amy", language="en-GB", loop=3)
_97
_97
return response
_97
_97
_97
def _redirect_welcome():
_97
response = VoiceResponse()
_97
response.say("Returning to the main menu", voice="Polly.Amy", language="en-GB")
_97
response.redirect(url_for('welcome'))
_97
_97
return twiml(response)

To see the full layout of this app, you can check out its file structure in the GitHub repository(link takes you to an external page).

After playing the audio and retrieving the caller's input, Twilio will send this input to our application.


Where to send the caller's input

where-to-send-the-callers-input page anchor

The gather's action parameter takes an absolute or relative URL as a value - in our case, this is the menu endpoint.

When the caller finishes entering digits, Twilio will make a GET or POST request to this URL and include a Digits parameter with the number our caller chose.

After making its request, Twilio will continue the current call using the TwiML received in your response. Note that any TwiML verbs occurring after a <Gather> are unreachable unless the caller does not enter any digits.

Send caller input to the intended route

send-caller-input-to-the-intended-route page anchor

ivr_phone_tree_python/views.py


_97
from flask import (
_97
flash,
_97
render_template,
_97
redirect,
_97
request,
_97
session,
_97
url_for,
_97
)
_97
from twilio.twiml.voice_response import VoiceResponse
_97
_97
from ivr_phone_tree_python import app
_97
from ivr_phone_tree_python.view_helpers import twiml
_97
_97
_97
@app.route('/')
_97
@app.route('/ivr')
_97
def home():
_97
return render_template('index.html')
_97
_97
_97
@app.route('/ivr/welcome', methods=['POST'])
_97
def welcome():
_97
response = VoiceResponse()
_97
with response.gather(
_97
num_digits=1, action=url_for('menu'), method="POST"
_97
) as g:
_97
g.say(message="Thanks for calling the E T Phone Home Service. " +
_97
"Please press 1 for directions." +
_97
"Press 2 for a list of planets to call.", loop=3)
_97
return twiml(response)
_97
_97
_97
@app.route('/ivr/menu', methods=['POST'])
_97
def menu():
_97
selected_option = request.form['Digits']
_97
option_actions = {'1': _give_instructions,
_97
'2': _list_planets}
_97
_97
if option_actions.has_key(selected_option):
_97
response = VoiceResponse()
_97
option_actions[selected_option](response)
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
@app.route('/ivr/planets', methods=['POST'])
_97
def planets():
_97
selected_option = request.form['Digits']
_97
option_actions = {'2': "+19295566487",
_97
'3': "+17262043675",
_97
"4": "+16513582243"}
_97
_97
if selected_option in option_actions:
_97
response = VoiceResponse()
_97
response.dial(option_actions[selected_option])
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
# private methods
_97
_97
def _give_instructions(response):
_97
response.say("To get to your extraction point, get on your bike and go " +
_97
"down the street. Then Left down an alley. Avoid the police" +
_97
" cars. Turn left into an unfinished housing development." +
_97
"Fly over the roadblock. Go past the moon. Soon after " +
_97
"you will see your mother ship.",
_97
voice="Polly.Amy", language="en-GB")
_97
_97
response.say("Thank you for calling the E T Phone Home Service - the " +
_97
"adventurous alien's first choice in intergalactic travel")
_97
_97
response.hangup()
_97
return response
_97
_97
_97
def _list_planets(response):
_97
with response.gather(
_97
numDigits=1, action=url_for('planets'), method="POST"
_97
) as g:
_97
g.say("To call the planet Broh doe As O G, press 2. To call the " +
_97
"planet DuhGo bah, press 3. To call an oober asteroid " +
_97
"to your location, press 4. To go back to the main menu " +
_97
" press the star key.",
_97
voice="Polly.Amy", language="en-GB", loop=3)
_97
_97
return response
_97
_97
_97
def _redirect_welcome():
_97
response = VoiceResponse()
_97
response.say("Returning to the main menu", voice="Polly.Amy", language="en-GB")
_97
response.redirect(url_for('welcome'))
_97
_97
return twiml(response)

Now that we have told Twilio where to send the caller's input, we can look at how to process that input.


The Main Menu: Processing the caller's selection

the-main-menu-processing-the-callers-selection page anchor

This route handles processing the caller's input.

If our caller chooses '1' for directions, we use the _give_instructions(link takes you to an external page) method to respond with TwiML that will Say directions to our caller's extraction point.

If the caller chooses '2' to call their home planet, then we need to gather more input from them. We wrote another method to handle this, _list_planets(link takes you to an external page), which we'll cover in the next step.

If the caller enters anything else, we respond with a TwiML Redirect to the main menu.


The Planet Directory: Collecting more input from the caller

the-planet-directory-collecting-more-input-from-the-caller page anchor

If our callers choose to call their home planet, we will read them the planet directory. Our planet directory is similar to a typical "company directory" feature of most IVRs.

In our TwiML response, we again use a Gather verb to get our caller's input. This time, the action verb points to the planets route, which will map our response to what the caller chooses.

Let's look at that route next. The TwiML response we return for that route uses a Dial verb with the appropriate phone number to connect our caller to their home planet.

Collect more input from the caller via the Planet Directory

collect-more-input-from-the-caller-via-the-planet-directory page anchor

ivr_phone_tree_python/views.py


_97
from flask import (
_97
flash,
_97
render_template,
_97
redirect,
_97
request,
_97
session,
_97
url_for,
_97
)
_97
from twilio.twiml.voice_response import VoiceResponse
_97
_97
from ivr_phone_tree_python import app
_97
from ivr_phone_tree_python.view_helpers import twiml
_97
_97
_97
@app.route('/')
_97
@app.route('/ivr')
_97
def home():
_97
return render_template('index.html')
_97
_97
_97
@app.route('/ivr/welcome', methods=['POST'])
_97
def welcome():
_97
response = VoiceResponse()
_97
with response.gather(
_97
num_digits=1, action=url_for('menu'), method="POST"
_97
) as g:
_97
g.say(message="Thanks for calling the E T Phone Home Service. " +
_97
"Please press 1 for directions." +
_97
"Press 2 for a list of planets to call.", loop=3)
_97
return twiml(response)
_97
_97
_97
@app.route('/ivr/menu', methods=['POST'])
_97
def menu():
_97
selected_option = request.form['Digits']
_97
option_actions = {'1': _give_instructions,
_97
'2': _list_planets}
_97
_97
if option_actions.has_key(selected_option):
_97
response = VoiceResponse()
_97
option_actions[selected_option](response)
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
@app.route('/ivr/planets', methods=['POST'])
_97
def planets():
_97
selected_option = request.form['Digits']
_97
option_actions = {'2': "+19295566487",
_97
'3': "+17262043675",
_97
"4": "+16513582243"}
_97
_97
if selected_option in option_actions:
_97
response = VoiceResponse()
_97
response.dial(option_actions[selected_option])
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
# private methods
_97
_97
def _give_instructions(response):
_97
response.say("To get to your extraction point, get on your bike and go " +
_97
"down the street. Then Left down an alley. Avoid the police" +
_97
" cars. Turn left into an unfinished housing development." +
_97
"Fly over the roadblock. Go past the moon. Soon after " +
_97
"you will see your mother ship.",
_97
voice="Polly.Amy", language="en-GB")
_97
_97
response.say("Thank you for calling the E T Phone Home Service - the " +
_97
"adventurous alien's first choice in intergalactic travel")
_97
_97
response.hangup()
_97
return response
_97
_97
_97
def _list_planets(response):
_97
with response.gather(
_97
numDigits=1, action=url_for('planets'), method="POST"
_97
) as g:
_97
g.say("To call the planet Broh doe As O G, press 2. To call the " +
_97
"planet DuhGo bah, press 3. To call an oober asteroid " +
_97
"to your location, press 4. To go back to the main menu " +
_97
" press the star key.",
_97
voice="Polly.Amy", language="en-GB", loop=3)
_97
_97
return response
_97
_97
_97
def _redirect_welcome():
_97
response = VoiceResponse()
_97
response.say("Returning to the main menu", voice="Polly.Amy", language="en-GB")
_97
response.redirect(url_for('welcome'))
_97
_97
return twiml(response)

Again, we show some options to the caller and instruct Twilio to collect the caller's choice.


The Planet Directory: Connect the caller to another number

the-planet-directory-connect-the-caller-to-another-number page anchor

In this route, we grab the caller's digit selection from the HTTP request and store it in a variable called selected_option. We then use a Dial verb with the appropriate phone number to connect our caller to their home planet.

The current numbers are hardcoded, but you could update this code to read phone numbers from a database or a file.

Connect to another number based on caller input

connect-to-another-number-based-on-caller-input page anchor

ivr_phone_tree_python/views.py


_97
from flask import (
_97
flash,
_97
render_template,
_97
redirect,
_97
request,
_97
session,
_97
url_for,
_97
)
_97
from twilio.twiml.voice_response import VoiceResponse
_97
_97
from ivr_phone_tree_python import app
_97
from ivr_phone_tree_python.view_helpers import twiml
_97
_97
_97
@app.route('/')
_97
@app.route('/ivr')
_97
def home():
_97
return render_template('index.html')
_97
_97
_97
@app.route('/ivr/welcome', methods=['POST'])
_97
def welcome():
_97
response = VoiceResponse()
_97
with response.gather(
_97
num_digits=1, action=url_for('menu'), method="POST"
_97
) as g:
_97
g.say(message="Thanks for calling the E T Phone Home Service. " +
_97
"Please press 1 for directions." +
_97
"Press 2 for a list of planets to call.", loop=3)
_97
return twiml(response)
_97
_97
_97
@app.route('/ivr/menu', methods=['POST'])
_97
def menu():
_97
selected_option = request.form['Digits']
_97
option_actions = {'1': _give_instructions,
_97
'2': _list_planets}
_97
_97
if option_actions.has_key(selected_option):
_97
response = VoiceResponse()
_97
option_actions[selected_option](response)
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
@app.route('/ivr/planets', methods=['POST'])
_97
def planets():
_97
selected_option = request.form['Digits']
_97
option_actions = {'2': "+19295566487",
_97
'3': "+17262043675",
_97
"4": "+16513582243"}
_97
_97
if selected_option in option_actions:
_97
response = VoiceResponse()
_97
response.dial(option_actions[selected_option])
_97
return twiml(response)
_97
_97
return _redirect_welcome()
_97
_97
_97
# private methods
_97
_97
def _give_instructions(response):
_97
response.say("To get to your extraction point, get on your bike and go " +
_97
"down the street. Then Left down an alley. Avoid the police" +
_97
" cars. Turn left into an unfinished housing development." +
_97
"Fly over the roadblock. Go past the moon. Soon after " +
_97
"you will see your mother ship.",
_97
voice="Polly.Amy", language="en-GB")
_97
_97
response.say("Thank you for calling the E T Phone Home Service - the " +
_97
"adventurous alien's first choice in intergalactic travel")
_97
_97
response.hangup()
_97
return response
_97
_97
_97
def _list_planets(response):
_97
with response.gather(
_97
numDigits=1, action=url_for('planets'), method="POST"
_97
) as g:
_97
g.say("To call the planet Broh doe As O G, press 2. To call the " +
_97
"planet DuhGo bah, press 3. To call an oober asteroid " +
_97
"to your location, press 4. To go back to the main menu " +
_97
" press the star key.",
_97
voice="Polly.Amy", language="en-GB", loop=3)
_97
_97
return response
_97
_97
_97
def _redirect_welcome():
_97
response = VoiceResponse()
_97
response.say("Returning to the main menu", voice="Polly.Amy", language="en-GB")
_97
response.redirect(url_for('welcome'))
_97
_97
return twiml(response)

That's it! We've just implemented an IVR phone tree that will help get ET back home.


If you're a Python/Flask developer working with Twilio, you might want to check out these other tutorials:

Appointment Reminders

Use Twilio to automate the process of reaching out to your customers in advance of an upcoming appointment.

Two-Factor Authentication with Authy

Use Twilio and Twilio-powered Authy OneTouch to implement two-factor authentication (2FA) in your web app

Did this help?

did-this-help page anchor

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Connect with us on Twitter(link takes you to an external page) and let us know what you build!


Rate this page: