M Cib
M Cib

Reputation: 11

twilio Reject Incoming Calls with a Phone Number Blacklist

First of all. I'm sorry English is my second language so I apologize for any mistakes. Second. I'm new with Twilio.

Thank you in advance for all your help.

I have multiple phone numbers with Twilio and I am trying to implement a number blacklist to all my phone numbers. Currently, I use the function bellow individually with all my Twilio numbers. So ideally I would like to create a file with all the phone numbers that I want to be blacklist and I could read this file in the function and don't need to write the blacklisted numbers in individual functions.

exports.handler = function(context, event, callback) {
  // List all blocked phone numbers in quotes and E.164 formatting, separated by a comma
  let blacklist = event.blacklist || [ "blacklist numbers","XXXXXXXXXX","XXXXXXXXX" ];  
  let twiml = new Twilio.twiml.VoiceResponse();
  let blocked = true;
  if (blacklist.length > 0) {
    if (blacklist.indexOf(event.From) === -1) {
      blocked = false;
    }
  }
  if (blocked) {
    twiml.reject();
  }
  else {
  // if the caller's number is not blocked, redirect to your existing webhook
  twiml.redirect("XXXXXX");
  }
  callback(null, twiml);
};

Thank you very much.

Upvotes: 1

Views: 487

Answers (2)

Vasseurth
Vasseurth

Reputation: 6496

Another way to do this is using Twilio Studio's Split Based On... widget. You can condition on event.From and either call different functions (or do noth

Upvotes: 0

Alan
Alan

Reputation: 10791

You could have something like the code below. You would then upload the blacklist.json to your Twilio Assets as a private asset. The code to read a private asset is shown under the Twilio documentation, Read the Contents of an Asset.

The format of blacklist.json is just a JSON array: ["+14071234567", "+18021234567"]

const fs = require('fs');

exports.handler = function(context, event, callback) {
    let fileName = 'blacklist.json';
    let file = Runtime.getAssets()[fileName].path;
    let text = fs.readFileSync(file);
    let blacklist = JSON.parse(text);
    console.log(blacklist);

    let twiml = new Twilio.twiml.VoiceResponse();

    let blocked = true;
    if (blacklist.length > 0) {
        if (blacklist.indexOf(event.From) === -1) {
        blocked = false;
    }
  }
  if (blocked) {
    twiml.reject();
  }
  else {
  // if the caller's number is not blocked, redirect to your existing webhook
    twiml.redirect("XXXXXX");
  }
  callback(null, twiml);
};

Upvotes: 1

Related Questions