Objective
Learn how to block automated spam calls and high-volume robocalls on your Twilio Programmable Voice phone numbers using a Call Screening Function.
Product
- Programmable Voice
- Twilio Functions
Environment
- Twilio Console
- Legacy Console
User Account Permission/Role(s) Required
Owner, Administrator, or Developer
Procedure
Log in to the Twilio Console.
Navigate to Functions and Assets > Services (or Functions Classic).
Click Create Service and give it a name (e.g.,
call-screening-service), then click Next.Click Add + and select Add Function.
Set the path to
/call-screen.Set the function visibility to Public.
Delete any default code in the editor and paste the following code:
JavaScript
exports.handler = function(context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
const digits = event.Digits;
if (digits) {
if (digits === '1') {
// Replace with your actual target Webhook, TwiML Bin, or SIP URI URL
twiml.redirect("YOUR_DESTINATION_URL_HERE");
} else {
twiml.say({ voice: 'Google.en-US-Standard-C' }, "Invalid input. Goodbye.");
twiml.reject();
}
return callback(null, twiml);
}
const gather = twiml.gather({
numDigits: 1,
action: '',
method: 'POST',
timeout: 5
});
gather.say(
{ voice: 'Google.en-US-Standard-C' },
"Thank you for calling. To prevent automated spam, please press 1 to connect your call."
);
twiml.say({ voice: 'Google.en-US-Standard-C' }, "We didn't receive a response. Goodbye.");
twiml.reject();
callback(null, twiml);
};
Replace
"YOUR_DESTINATION_URL_HERE"in the code with the Webhook URL, TwiML Bin URL, or handler where your legitimate calls should be routed after passing the screen.Click Save and then click Deploy All.
Navigate to Phone Numbers > Manage > Active Numbers.
Click on the phone number receiving spam calls.
Scroll down to the A Call Comes In section under Voice & Fax.
Set the first dropdown to Function.
Select the Service, Environment, and Function Path (
/call-screen) you created.Click Save configuration.
Your number will now prompt callers to press 1 to be connected with you, and will drop the call if the digit 1 is not pressed within 5 seconds.
Additional Information
Cost Consideration: Call screening requires Twilio to answer the call briefly to play the prompt and gather digits. Standard inbound per-minute rates will apply for answered calls, even if the caller hangs up or fails the screening test.
Why Static Blocklists Fail: Automated spammers frequently rotate spoofed caller ID numbers. While static blocklists stop known numbers, Call Screening blocks dynamic spam numbers by targeting the automated nature of robodialers.