IVR: Phone Tree with Python and Flask

ET Phone Home

This Python Flask sample application is modeled after a typical call center experience, but with more Reese's Pieces.

Stranded aliens can call a phone number and receive instructions on how to get out of earth safely, or call their home planet directly. In this tutorial, we'll show you the key bits of code to make this work.

To run this sample app yourself, download the code and follow the instructions on GitHub.

Read how Livestream used Twilio to build custom call routing logic and IVR messages.

Answering a Phone Call

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 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 is a great 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

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 we Play a welcome message.

You may have noted we're using an unknown method TwiML. This is a custom view helper that takes a TwiML Response and transforms it into a valid HTTP Response. It's super easy, check out the implementation:

import flask

def twiml(resp):
    resp = flask.Response(str(resp))
    resp.headers['Content-Type'] = 'text/xml'
    return resp
Loading Code Samples...
Language
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
ivr_phone_tree_python/views.py
Respond with TwiML to gather an option from the caller

ivr_phone_tree_python/views.py

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

Where to send the caller's input

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 has finished entering digits, Twilio will make a GET or POST request to this URL including a Digits parameter with the number our caller chose.

After making this request, Twilio will continue the current call using the TwiML received in your response. Any TwiML verbs occurring after a <Gather> are unreachable, unless the caller enters no digits.

Loading Code Samples...
Language
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
ivr_phone_tree_python/views.py
Send caller input to the intended route

ivr_phone_tree_python/views.py

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

This route handles processing the caller's input.

If our caller chooses '1' for directions, we use the _give_instructions 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, which we'll cover in the next step.

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

Loading Code Samples...
Language
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
ivr_phone_tree_python/views.py
Main menu and return instructions

ivr_phone_tree_python/views.py

If the caller chooses '2', we will take them to the Planet Directory in order to collect more input.

The Planet Directory: Collecting more input from the caller

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

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

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

Loading Code Samples...
Language
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
ivr_phone_tree_python/views.py
Collect more input from the caller via the Planet Directory

ivr_phone_tree_python/views.py

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

In this route, we grab the caller's selection off the 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 they could also be read from a database or from a file.

Loading Code Samples...
Language
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
ivr_phone_tree_python/views.py
Connect to another number based on caller input

ivr_phone_tree_python/views.py

That's it! We've just implemented an IVR phone tree that will delight and serve your customers.

Where to Next?

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?

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 and let us know what you build!

Kevin Whinnery
Agustin Camino
Samuel Mendes
Kat King
Andrew Baker

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)
from flask import render_template, redirect, url_for, request, session, flash
from ivr_phone_tree_python import app
from twilio.twiml.voice_response import VoiceResponse

from ivr_phone_tree_python.view_helpers import twiml


@app.route('/')
@app.route('/ivr')
def home():
    return render_template('index.html')


@app.route('/ivr/welcome', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(numDigits=1, action=url_for('menu'), method="POST") as g:
        g.play(url="http://howtodocs.s3.amazonaws.com/et-phone.mp3", loop=3)
    return twiml(response)


@app.route('/ivr/menu', methods=['POST'])
def menu():
    selected_option = request.form['Digits']
    option_actions = {'1': _give_instructions,
                      '2': _list_planets}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        option_actions[selected_option](response)
        return twiml(response)

    return _redirect_welcome()


@app.route('/ivr/planets', methods=['POST'])
def planets():
    selected_option = request.form['Digits']
    option_actions = {'2': "+12024173378",
                      '3': "+12027336386",
                      "4": "+12027336637"}

    if option_actions.has_key(selected_option):
        response = VoiceResponse()
        response.dial(option_actions[selected_option])
        return twiml(response)

    return _redirect_welcome()


# private methods

def _give_instructions(response):
    response.say("To get to your extraction point, get on your bike and go down " +
                 "the street. Then Left down an alley. Avoid the police cars. Turn left " +
                 "into an unfinished housing development. Fly over the roadblock. Go " +
                 "passed the moon. Soon after you will see your mother ship.",
                 voice="alice", language="en-GB")

    response.say("Thank you for calling the ET Phone Home Service - the " +
                 "adventurous alien's first choice in intergalactic travel")

    response.hangup()
    return response


def _list_planets(response):
    with response.gather(numDigits=1, action=url_for('planets'), method="POST") as g:
        g.say("To call the planet Broh doe As O G, press 2. To call the planet " +
              "DuhGo bah, press 3. To call an oober asteroid to your location, press 4. To " +
              "go back to the main menu, press the star key ",
              voice="alice", language="en-GB", loop=3)

    return response


def _redirect_welcome():
    response = VoiceResponse()
    response.say("Returning to the main menu", voice="alice", language="en-GB")
    response.redirect(url_for('welcome'))

    return twiml(response)