Python Quickstart: Connect Call to a Second Person

Now, let's also ask the caller if she wants to talk to a real monkey. If she does, connect her to Koko, the famous Gorilla, whose phone number we happen to know is 310-555-1212 :)

Here is our server file. We're going to add a second method to handle requests at http://example.com/handle-key. In the file below, add the highlighted lines to gather input from the caller.

This tutorial assumes you are running Flask on a server available over the Internet, and have the twilio-python library installed. If not, see our guide to setting up your local development environment.
run.py
from __future__ import with_statement   # Only necessary for Python 2.5
from flask import Flask, request, redirect
from twilio.twiml.voice_response import VoiceResponse, Gather

app = Flask(__name__)

callers = {
    "+14158675309": "Curious George",
    "+14158675310": "Boots",
    "+14158675311": "Virgil",
    "+14158675312": "Marcel"
}

@app.route("/", methods=['GET', 'POST'])
def hello_monkey():
    from_number = request.values.get('From', None)
    if from_number in callers:
        caller = callers[from_number]
    else:
        caller = "Monkey"

    resp = VoiceResponse()
    # Greet the caller by name
    resp.say("Hello " + caller)
    # Play an mp3
    resp.play("http://demo.twilio.com/hellomonkey/monkey.mp3")

    # Say a command, and listen for the caller to press a key. When they press
    # a key, redirect them to /handle-key.
    g = Gather(numDigits=1, action="/handle-key", method="POST")
    g.say("To speak to a real monkey, press 1. Press any other key to start over.")
    resp.append(g)

    return str(resp)

@app.route("/handle-key", methods=['GET', 'POST'])
def handle_key():
    """Handle key press from a user."""

    # Get the digit pressed by the user
    digit_pressed = request.values.get('Digits', None)
    if digit_pressed == "1":
        resp = VoiceResponse()
        # Dial (310) 555-1212 - connect that number to the incoming caller.
        resp.dial("+13105551212")
        # If the dial fails:
        resp.say("The call failed, or the remote party hung up. Goodbye.")

        return str(resp)

    # If the caller pressed anything but 1, redirect them to the homepage.
    else:
        return redirect("/")

if __name__ == "__main__":
    app.run(debug=True)

The output of a request to your server at example.com will look like this:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello Curious George</Say>
    <Play>http://demo.twilio.com/hellomonkey/monkey.mp3</Play>
    <Gather action="/handle-key" method="POST" numDigits="1">
        <Say>To speak to a real monkey, press 1. Press any other key to start over.</Say>
    </Gather>
</Response>

When Twilio sees a <Gather> block, it starts looking for input from the caller's key pad. Because the <Say> is nested inside the <Gather>, Twilio will detect if the caller presses a key, even if the key is pressed while the <Say> is still running.

When the caller presses a key, the pressed key is POSTed to the URL specified by the 'action' handler attribute of the <Gather> verb. In this case, the URL is /handle-key.

You can read more about TwiML verbs and acceptable parameters in our TwiML Documentation.


Next: Record a message »

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.