Respond to Incoming Phone Calls
Learn to handle and answer inbound calls with Twilio Programmable Voice by serving a TwiML document in response to the Twilio HTTP webhook request when a call is received. You can use this guide to create self-service automation and build inbound contact centers.
See Related reference documentation to learn more about the TwiML elements used in this guide.
- Create a Twilio account.
- In the Twilio Console, create a compliance profile, then buy a voice-enabled phone number.
- In the legacy Console, buy a voice-enabled phone number. Only Messaging-enabled phone numbers need a compliance profile.
Select your programming language and complete the prerequisites:
- Install Python 3.3 or later.
- Install Flask and the Twilio Python Helper Library. Using pip, run the following command:
pip install flask twilio
- Install and set up ngrok.
Extract your credentials from your Twilio account then save these credentials as environment variables.
-
Go to the Twilio Console. The Let's get building page appears.
-
Click API keys and Auth tokens. The API keys & auth tokens page appears with the Auth Tokens tab selected.
-
Scroll to your Account SID.
-
Click the copy button next to your Account SID.
-
Run the following command, replacing
YOUR_ACCOUNT_SIDwith your Account SID.macOS TerminalWindows command linePowerShellexport TWILIO_ACCOUNT_SID=YOUR_ACCOUNT_SIDThis command creates an environment variable on your development system for your account SID.
-
To display the Auth Token, click the eye button in the Primary auth token box.
-
Highlight and copy the Auth Token.
-
Run the following command, replacing
YOUR_AUTH_TOKENwith your Authentication Token.macOS TerminalWindows command linePowerShellexport TWILIO_AUTH_TOKEN=YOUR_AUTH_TOKENThis command creates an environment variable on your development system for your auth token.
When a Twilio phone number receives an incoming call, Twilio sends an HTTP request to your web app. This request asks for instructions on how you want the call handled. Your web app responds with an TwiML document. Twilio takes the instruction set from that document and performs an action. This might include saying some arbitrary text, playing an MP3 file, or recording the call audio.
To respond to an inbound call, send a response request to Twilio using one of these helper libraries.
Python only requires the Twilio Python helper library as noted in the prerequisites.
1from flask import Flask2from twilio.twiml.voice_response import VoiceResponse34app = Flask(__name__)567@app.route("/voice", methods=['GET', 'POST'])8def voice():9"""Respond to incoming phone calls with a 'Hello world' message"""10# Start our TwiML response11resp = VoiceResponse()1213# Read a message aloud to the caller14resp.say("Hello world!")1516return str(resp)1718if __name__ == "__main__":19app.run(debug=True)
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Say>Hello world!</Say>4</Response>
The previous section provided code that responds to an incoming call with a pre-defined TwiML document. Using the data Twilio sends to your app through webhooks, you can change what gets presented to the user on the other end of the phone call. You can write custom code that gathers additional server-side data that builds your response to your user.
To create a custom response to an inbound call, send a response request to Twilio using one of these helper libraries.
Python only requires the Twilio Python helper library as noted in the prerequisites.
1from flask import Flask, request2from twilio.twiml.voice_response import VoiceResponse34app = Flask(__name__)567@app.route("/voice", methods=['GET', 'POST'])8def voice():9"""Respond to incoming phone calls and mention the caller's city"""10# Get the caller's city from Twilio's request to our app11city = request.values['FromCity']1213# Start our TwiML response14resp = VoiceResponse()1516# Read a message aloud to the caller17resp.say('Never gonna give you up, {}!'.format(city))1819# Play an audio file for the caller20resp.play('https://demo.twilio.com/docs/classic.mp3')2122return str(resp)2324if __name__ == "__main__":25app.run(debug=True)
To use the webhooks in this code sample, Twilio must communicate with your web app. These communications consist of HTTP requests sent between URLs accessible over the internet. Twilio requires access to Internet-addressable, or public, URLs.
Protect your webhooks
Twilio supports HTTP Basic and Digest Authentication. This type of authentication protects your TwiML URLs on your web server with an Auth Token. This limits access to the URLs to you and Twilio. Protect your auth tokens as you would your passwords. To learn more, see HTTP authentication.
Most production systems have a public URL, but development systems might not. To permit Twilio to access your local dev app, use ngrok. To create a public URL for your app, run ngrok at the command line:
ngrok http 3000 --url https://<your-app-name>.ngrok.dev
This command creates a public URL https://<your-app-name>.ngrok.dev. that forwards HTTP requests to your web app listening on localhost:3000.
With your public URL created, configure its connection to Twilio using a webhook.
If you use the new Twilio Console, follow these steps:
- Go to Numbers & senders.
- Click your Twilio phone number you want for your app.
- If you don't have any phone numbers, click Set up a new phone number.
- If Twilio needs your compliance data, create a compliance profile first.
- Click the Configuration details tab.
- Click Messaging > Edit details.
- On the Edit messaging configuration dialog, select the Webhook, TwiML Bin, Function, Studio Flow, Proxy Service option.
- Under How do you want to set up your primary method?, select Webhook.
- Paste your ngrok public URL in the URL box.
If yourngrokconsole showsForwarding https://<your-app-name>.ngrok.dev, pastehttps://<your-app-name>.ngrok.devto the URL box.
This guide teaches the basics required for the following use cases:
You can use this guide to intercept incoming customer calls and immediately present resolution paths. When Twilio triggers a webhook request to your server, you can return a structured TwiML script that handles inquiries without the intervention of human agents, like checking delivery statuses or updating user records.
To learn more advanced features that you can use with self-service automation, see Voice self-service automation.
You can use this guide as the fundamental entry point for routing and managing callers seeking live assistance. By responding to incoming call webhooks dynamically, your backend application can inspect customer details, query your CRM database, and use intelligent call distribution to pass the caller to the correct department queue.
To learn more advanced features that you can use with inbound contact centers, see Voice inbound contact center.
After following this guide, your web application can successfully listen for, receive, and respond to incoming webhooks triggered by inbound phone calls directed to your Twilio numbers. You can verify that your logic is operational by dialing your provisioned Twilio phone number from a mobile device and confirming that your server executes your specific TwiML voice commands.
Explore the following guides to build on what you've learned in this guide:
- Gather user input using Keypad (DTMF Tones): Learn how to extend your inbound call handlers to collect digits pressed on a phone keypad.
- Build an Interactive Voice Response (IVR) phone tree: Construct multi-level menus to intelligently segment and guide your incoming callers.
- How to record phone calls: Capture call audio programmatically for quality assurance, compliance, or storage.
- How to create conference calls: Connect multiple callers together into a centralized, hosted audio conference room.