This tutorial builds a multi-level interactive voice response (IVR) system using Flask and Twilio's TwiML Gather verb so callers can navigate a phone menu by pressing digits. It targets developers who need to route inbound calls through a structured menu tree, such as separating sales, support, and billing departments. You will implement a main menu and at least two sub-menus with proper fallback handling when no input is received.
Prerequisites and Setup
You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask. The IVR relies on multiple Flask routes, each representing one level of the menu, connected by the action attribute on each Gather verb. Expose the Flask server with ngrok and set your Twilio number's voice webhook to the main menu route. Plan your menu tree before coding: define what digits map to which departments and what audio each level plays.
pip install twilio flask
# IVR menu structure:
# Main: 1 = Sales, 2 = Support, 3 = Billing
# Sales: 1 = New accounts, 2 = Existing accounts
# Support: 1 = Technical, 2 = Account issues
The Complete Code
Each IVR level is a separate Flask route that constructs a Gather with a Say prompt and an action pointing to the next handler route. The handler reads request.form["Digits"] and either dials a number, redirects to a sub-menu, or returns an error prompt. A Redirect verb at the end of a Gather block loops the caller back to the same menu if they do not press anything. The finishOnKey attribute on Gather is left at its default of #, so callers can press their digit immediately without waiting for the prompt to finish.
from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse, Gather, Dial, Redirect
app = Flask(__name__)
AGENTS = {
"sales_new": "+15550001111",
"sales_existing":"+15550002222",
"support_tech": "+15550003333",
"support_acct": "+15550004444",
"billing": "+15550005555",
}
@app.route("/ivr/main", methods=["POST"])
def main_menu():
resp = VoiceResponse()
g = Gather(num_digits=1, action="/ivr/main-handler", timeout=5)
g.say("Welcome. Press 1 for sales. Press 2 for support. Press 3 for billing.", voice="alice")
resp.append(g)
resp.append(Redirect("/ivr/main"))
return str(resp), 200, {"Content-Type": "text/xml"}
@app.route("/ivr/main-handler", methods=["POST"])
def main_handler():
digit = request.form.get("Digits", "")
resp = VoiceResponse()
if digit == "1":
resp.append(Redirect("/ivr/sales"))
elif digit == "2":
resp.append(Redirect("/ivr/support"))
elif digit == "3":
resp.say("Connecting you to billing.", voice="alice")
d = Dial(); d.number(AGENTS["billing"]); resp.append(d)
else:
resp.say("Invalid option.", voice="alice")
resp.append(Redirect("/ivr/main"))
return str(resp), 200, {"Content-Type": "text/xml"}
@app.route("/ivr/sales", methods=["POST"])
def sales_menu():
resp = VoiceResponse()
g = Gather(num_digits=1, action="/ivr/sales-handler", timeout=5)
g.say("For new accounts press 1. For existing accounts press 2.", voice="alice")
resp.append(g)
resp.append(Redirect("/ivr/sales"))
return str(resp), 200, {"Content-Type": "text/xml"}
@app.route("/ivr/sales-handler", methods=["POST"])
def sales_handler():
digit = request.form.get("Digits", "")
resp = VoiceResponse()
key = "sales_new" if digit == "1" else "sales_existing" if digit == "2" else None
if key:
resp.say("Connecting you now.", voice="alice")
d = Dial(); d.number(AGENTS[key]); resp.append(d)
else:
resp.append(Redirect("/ivr/sales"))
return str(resp), 200, {"Content-Type": "text/xml"}
@app.route("/ivr/support", methods=["POST"])
def support_menu():
resp = VoiceResponse()
g = Gather(num_digits=1, action="/ivr/support-handler", timeout=5)
g.say("For technical support press 1. For account issues press 2.", voice="alice")
resp.append(g)
resp.append(Redirect("/ivr/support"))
return str(resp), 200, {"Content-Type": "text/xml"}
@app.route("/ivr/support-handler", methods=["POST"])
def support_handler():
digit = request.form.get("Digits", "")
resp = VoiceResponse()
key = "support_tech" if digit == "1" else "support_acct" if digit == "2" else None
if key:
resp.say("Connecting you now.", voice="alice")
d = Dial(); d.number(AGENTS[key]); resp.append(d)
else:
resp.append(Redirect("/ivr/support"))
return str(resp), 200, {"Content-Type": "text/xml"}
if __name__ == "__main__":
app.run(port=5000, debug=True)
Testing and Debugging
Call your Twilio number and navigate each branch of the menu to confirm every digit maps to the correct next action. If a Redirect loops indefinitely without playing audio, check that the target route is registered in Flask and returns a valid TwiML response. Twilio's Call Logs in the Console show every TwiML fetch with the exact URL, HTTP status, and response body, which makes it straightforward to identify which route is failing. Test the timeout fallback by staying silent after the greeting to ensure the Redirect loops the caller back to the menu prompt rather than hanging up.
Taking It Further
Load the menu structure from a database or JSON configuration file so non-developers can update menu options without touching Python code. Add time-based routing in each handler that checks datetime.now() against business hours and redirects to a voicemail route outside those hours. Use the Play verb instead of Say to play pre-recorded audio files for professional-sounding prompts, which also removes the latency of text-to-speech synthesis. Integrate Twilio's speech recognition by setting input="speech dtmf" on your Gather verbs so callers can say department names instead of pressing digits.
Reach out to Telphi Consulting to architect and deploy a production IVR system with analytics, call recording, and CRM integration.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.