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

Receive an incoming phone call


When someone calls your Twilio number, Twilio can invoke a webhook that you've created to determine how to respond using TwiML. On this page, we will be providing some examples of Functions that can serve as the webhook of your Twilio number.

A Function that responds to webhook requests will receive details about the incoming phone call as properties on the event parameter. These include the phone number of the caller (event.From), the phone number of the recipient (event.To), and other relevant data such as geographic metadata about the phone numbers involved. You can view a full list of potential values at Twilio's request to your application.

Once a Function has been invoked on an incoming phone call, any number of actions can be taken. Below are some examples to inspire what you will build.


Create and host a Function

create-and-host-a-function page anchor

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page) . If you need an account, you can sign up for a free Twilio account here(link takes you to an external page) !
  2. Functions are contained within Services . Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function .
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world .

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!


Set a Function as a webhook

set-a-function-as-a-webhook page anchor

In order for your Function to react to incoming SMS and/or voice calls, it must be set as a webhook for your Twilio number. There are a variety of methods to set a Function as a webhook, as detailed below:

Twilio ConsoleTwilio CLITwilio SDKs

You can use the Twilio Console(link takes you to an external page) UI as a straightforward way of connecting your Function as a webhook:

  1. Log in to the Twilio Console's Phone Numbers page(link takes you to an external page) .
  2. Click on the phone number you'd like to have connected to your Function.
  3. If you want the Function to respond to incoming SMS, find the A Message Comes In option under Messaging . If you want the Function to respond to Voice, find the A Call Comes In option under Voice & Fax .
  4. Select Function from the A Message Comes In or A Call Comes In dropdown.
  5. Select the Service that you are using, then the Environment (this will default to ui unless you have created custom domains ), and finally Function Path of your Function from the respective dropdown menus.
    Connect a Function as a Messaging webhook using the Function dropdowns.
  • Alternatively, you could select Webhook instead of Function, and directly paste in the full URL of the Function.
    Setting a Function as a Messaging webhook using the webhook dropdown option.
  1. Click the Save button.

Respond with a static message

respond-with-a-static-message page anchor

For the most basic possible example, one can reply to the incoming phone call with a hardcoded message. To do so, you can create a new VoiceResponse and declare the intended message contents using the say method. Once your voice content has been set, you can return the generated TwiML by passing it to the callback function as shown and signaling a successful end to the function.

Respond to an incoming phone call

respond-to-an-incoming-phone-call page anchor

_10
exports.handler = (context, event, callback) => {
_10
// Create a new voice response object
_10
const twiml = new Twilio.twiml.VoiceResponse();
_10
// Use any of the Node.js SDK methods, such as `say`, to compose a response
_10
twiml.say('Ahoy, World!');
_10
// Return the TwiML as the second argument to `callback`
_10
// This will render the response as XML in reply to the webhook request
_10
return callback(null, twiml);
_10
};


Respond dynamically to an incoming phone call

respond-dynamically-to-an-incoming-phone-call page anchor

Because information about the incoming phone call is accessible from event object, it's also possible to tailor the response to the call based on that data. For example, you could respond with the city of the caller's phone number, or the number itself. The voice used to respond can also be modified, and pre-recorded audio can be used and/or added as well.

Read the in-depth <Say> documentation for more details about how to configure your response.

Respond dynamically to an incoming phone call

respond-dynamically-to-an-incoming-phone-call-1 page anchor

_15
exports.handler = (context, event, callback) => {
_15
// Create a new voice response object
_15
const twiml = new Twilio.twiml.VoiceResponse();
_15
// Webhook information is accessible as properties of the `event` object
_15
const city = event.FromCity;
_15
const number = event.From;
_15
_15
// You can optionally edit the voice used, template variables into your
_15
// response, play recorded audio, and more
_15
twiml.say({ voice: 'alice' }, `Never gonna give you up, ${city || number}`);
_15
twiml.play('https://demo.twilio.com/docs/classic.mp3');
_15
// Return the TwiML as the second argument to `callback`
_15
// This will render the response as XML in reply to the webhook request
_15
return callback(null, twiml);
_15
};


Forward an incoming phone call

forward-an-incoming-phone-call page anchor

Another common use case is call forwarding. This could be handy in a situation where perhaps you don't want to share your real number while selling an item online, or as part of an IVR tree.

In this example, the Function will accept an incoming phone call and generate a new TwiML response that both notifies the user of the call forwarding and initiates a transfer of the call to the new number.

Read the in-depth <Dial>documentation for more details about connecting calls to other parties.

Forward an incoming phone call

forward-an-incoming-phone-call-1 page anchor

_13
const NEW_NUMBER = "+15095550100";
_13
_13
exports.handler = (context, event, callback) => {
_13
// Create a new voice response object
_13
const twiml = new Twilio.twiml.VoiceResponse();
_13
_13
twiml.say('Hello! Forwarding you to our new phone number now!');
_13
// The `dial` method will forward the call to the provided E.164 phone number
_13
twiml.dial(NEW_NUMBER);
_13
// Return the TwiML as the second argument to `callback`
_13
// This will render the response as XML in reply to the webhook request
_13
return callback(null, twiml);
_13
};

(information)

Info

In this example, the number for call forwarding is hardcoded as a string in the Function for convenience. For a more secure approach, consider setting NEW_NUMBER as an Environment Variable in the Functions UI instead. It could then be referenced in your code as context.NEW_NUMBER, as shown in the following example.

Forward an incoming phone call

forward-an-incoming-phone-call-2 page anchor

Use environment variables to store sensitive values


_13
exports.handler = (context, event, callback) => {
_13
// Create a new voice response object
_13
const twiml = new Twilio.twiml.VoiceResponse();
_13
// Environment variables that you define can be accessed from `context`
_13
const forwardTo = context.NEW_NUMBER;
_13
_13
twiml.say('Hello! Forwarding you to our new phone number now!');
_13
// The `dial` method will forward the call to the provided E.164 phone number
_13
twiml.dial(forwardTo);
_13
// Return the TwiML as the second argument to `callback`
_13
// This will render the response as XML in reply to the webhook request
_13
return callback(null, twiml);
_13
};


Record an incoming phone call

record-an-incoming-phone-call page anchor

Another common use case would be recording the caller's voice as an audio recording which can be retrieved later. Optionally, you can generate text transcriptions of recorded calls by setting the transcribe attribute of <Record> to true.

Read the in-depth <Record> documentation for more details about recording and/or transcribing calls.

Record an incoming phone call

record-an-incoming-phone-call-1 page anchor

_13
exports.handler = (context, event, callback) => {
_13
// Create a new voice response object
_13
const twiml = new Twilio.twiml.VoiceResponse();
_13
_13
twiml.say('Hello! Please leave a message after the beep.');
_13
// Use <Record> to record the caller's message
_13
twiml.record();
_13
// End the call with <Hangup>
_13
twiml.hangup();
_13
// Return the TwiML as the second argument to `callback`
_13
// This will render the response as XML in reply to the webhook request
_13
return callback(null, twiml);
_13
};

Record and transcribe an incoming phone call

record-and-transcribe-an-incoming-phone-call page anchor

Use extra options to configure your recording


_14
exports.handler = (context, event, callback) => {
_14
// Create a new voice response object
_14
const twiml = new Twilio.twiml.VoiceResponse();
_14
_14
twiml.say('Hello! Please leave a message after the beep.');
_14
// Use <Record> to record the caller's message.
_14
// Provide options such as `transcribe` to enable message transcription.
_14
twiml.record({ transcribe: true });
_14
// End the call with <Hangup>
_14
twiml.hangup();
_14
// Return the TwiML as the second argument to `callback`
_14
// This will render the response as XML in reply to the webhook request
_14
return callback(null, twiml);
_14
};


Creating a moderated conference call

creating-a-moderated-conference-call page anchor

For something more exciting, Functions can also power conference calls. In this example, a "moderator" phone number of your choice will have control of the call in a couple of ways:

  • startConferenceOnEnter will keep all other callers on hold until the moderator joins
  • endConferenceOnExit will cause Twilio to end the call for everyone as soon as the moderator leaves

Incoming calls will be checked based on the incoming event.From value. If it matches the moderator's phone number, the call will begin and then end once the moderator leaves. Any other phone number will join normally and have no effect on the call's beginning or end.

Read the in-depth <Conference> documentation to learn more details.

Create a moderated conference call

create-a-moderated-conference-call page anchor

_24
exports.handler = (context, event, callback) => {
_24
// Create a new voice response object
_24
const twiml = new Twilio.twiml.VoiceResponse();
_24
_24
// Start with a <Dial> verb
_24
const dial = twiml.dial();
_24
// If the caller is our MODERATOR, then start the conference when they
_24
// join and end the conference when they leave
_24
// The MODERATOR phone number MUST be in E.164 format such as "+15095550100"
_24
if (event.From === context.MODERATOR) {
_24
dial.conference('My conference', {
_24
startConferenceOnEnter: true,
_24
endConferenceOnExit: true,
_24
});
_24
} else {
_24
// Otherwise have the caller join as a regular participant
_24
dial.conference('My conference', {
_24
startConferenceOnEnter: false,
_24
});
_24
}
_24
// Return the TwiML as the second argument to `callback`
_24
// This will render the response as XML in reply to the webhook request
_24
return callback(null, twiml);
_24
};


Rate this page: