Skip to contentSkip to navigationSkip to topbar

Twilio Notify


1
// Description
2
// Twilio Notify API to send bulk SMS with the same message (body) as one API request
3
// Upload notifyList.txt as a private Twilio asset
4
// notifyList.txt format (comma separated numbers w/wo spaces): +15105550100, +15105550101, +15105550102, +15105550103
5
// Execute Syntax: https://x.x.x.x/<path>?queryParamPasscode=8675309
6
// (change passcode below, replace this method with a secure auth method in production)
7
// Make sure under Functions Global Config tab:
8
// "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" is CHECKED
9
10
const fs = require('fs');
11
12
// Add node-fetch 2.6.0 as a dependency under Settings, Dependencies
13
const fetch = require('node-fetch');
14
15
//** START NECESSARY CONFIGURATION**
16
// You must define your unique Twilio Notify SID - https://www.twilio.com/console/notify/services below
17
// Notify will make use of a Twilio Messaging Service which you also need to define with a Twilio number(s)
18
// https://www.twilio.com/console/sms/services
19
const notifySid = 'IS076575.....';
20
const passCode = '8675309'; // CHANGE THIS
21
// Notify Bulk Message Body to Send
22
const bulkMsgBody = '😸 Hello from Winston 😸';
23
//** END NECESSARY CONFIGURATION**
24
25
exports.handler = function (context, event, callback) {
26
const params = new URLSearchParams();
27
const queryParamPasscode = event.queryParamPasscode;
28
29
const fileName = '/notifyList.txt';
30
const file = Runtime.getAssets()[fileName].path;
31
const numbers = fs.readFileSync(file, 'utf8').trim();
32
33
// Must pass a URL query parameter of queryParamPasscode with the value of passCode to execute
34
if (queryParamPasscode != passCode) return callback('invalid operation'); // You can change the error message
35
36
params.append('Body', bulkMsgBody);
37
38
numbers.split(',').forEach((number) => {
39
number.trim();
40
params.append(
41
`ToBinding`,
42
`{ "binding_type": "sms", "address": "${number}" }`
43
);
44
});
45
46
const headers = {
47
Authorization:
48
'Basic ' +
49
new Buffer.from(`${context.ACCOUNT_SID}:${context.AUTH_TOKEN}`).toString(
50
'base64'
51
),
52
};
53
54
fetch(`https://notify.twilio.com/v1/Services/${notifySid}/Notifications`, {
55
method: 'POST',
56
headers,
57
body: params,
58
})
59
.then((res) => res.json())
60
.then((json) => {
61
console.log(json);
62
return callback(null, { result: 'success' });
63
})
64
.catch((error) => {
65
console.error(error);
66
return callback({ result: 'error' });
67
});
68
};
69