Menu

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Twilio Notify

// Description
// Twilio Notify API to send bulk SMS with the same message (body) as one API request
// Upload notifyList.txt as a private Twilio asset
// notifyList.txt format (comma separated numbers w/wo spaces): +15105550100, +15105550101, +15105550102, +15105550103
// Execute Syntax: https://x.x.x.x/<path>?queryParamPasscode=8675309
// (change passcode below, replace this method with a secure auth method in production)
// Make sure under Functions Global Config tab:
// "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" is CHECKED

const fs = require('fs');

// Add node-fetch 2.6.0 as a dependency under Settings, Dependencies
const fetch = require('node-fetch');

// ** START NECESSARY CONFIGURATION **
// You must define your unique Twilio Notify SID - https://www.twilio.com/console/notify/services below
// Notify will make use of a Twilio Messaging Service which you also need to define with a Twilio number(s)
// https://www.twilio.com/console/sms/services
const notifySid = 'IS076575.....';
const passCode = '8675309'; // CHANGE THIS
// Notify Bulk Message Body to Send
const bulkMsgBody = '😸 Hello from Winston 😸';
// ** END NECESSARY CONFIGURATION **

exports.handler = function (context, event, callback) {
  const params = new URLSearchParams();
  const queryParamPasscode = event.queryParamPasscode;

  let fileName = '/notifyList.txt';
  let file = Runtime.getAssets()[fileName].path;
  let numbers = fs.readFileSync(file, 'utf8').trim();

  // Must pass a URL query parameter of queryParamPasscode with value of passCode to execute
  if (queryParamPasscode != passCode) return callback('invalid operation'); // You can change the error message

  params.append('Body', bulkMsgBody);

  numbers.split(',').forEach((number) => {
    number.trim();
    params.append(
      `ToBinding`,
      `{ "binding_type": "sms", "address": "${number}" }`
    );
  });

  let headers = {
    Authorization:
      'Basic ' +
      new Buffer.from(context.ACCOUNT_SID + ':' + context.AUTH_TOKEN).toString(
        'base64'
      ),
  };

  fetch(`https://notify.twilio.com/v1/Services/${notifySid}/Notifications`, {
    method: 'POST',
    headers: headers,
    body: params,
  })
    .then((res) => res.json())
    .then((json) => {
      console.log(json);
      return callback(null, { result: 'success' });
    })
    .catch((err) => {
      console.log(err);
      return callback({ result: 'error' });
    });
};
Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.