Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martinamps/7168ec5cfaf861aa2f29afbca2549073 to your computer and use it in GitHub Desktop.
Save martinamps/7168ec5cfaf861aa2f29afbca2549073 to your computer and use it in GitHub Desktop.
Twilio Functions blacklist example
const got = require('got');
const crypto = require('crypto');
const blacklist = [
'cnn is isis',
'side of beef',
];
const blacklist_replies = [
"Message: GOTO is not allowed in a stored procedure handler",
...
];
exports.handler = function(context, event, callback) {
const signature = getSignature(context.AUTH_TOKEN, context.URL, event);
if (blacklist.some(v => { return event.Body.toLowerCase().indexOf(v) >= 0; })) {
console.log('filtering: ' + event.Body);
let twiml = new Twilio.twiml.MessagingResponse();
const idx = Math.floor(Math.random() * blacklist_replies.length);
twiml.message(blacklist_replies[idx]);
slackUrl = 'https://hooks.slack.com/services/' + context.SLACK_SERVICE;
slackMessage = "Filtered: " + event.Body + "\n";
slackMessage = slackMessage + "SmsSid: " + event.SmsSid + "\n";
slackMessage = slackMessage + "From: " + event.From;
slackPayload = JSON.stringify({ text: slackMessage });
got.post(slackUrl, {
body: slackPayload
})
.then(response => callback(null, twiml))
.catch(error => {
console.err('error from slack: ' + error.response.body);
return callback(null, twiml);
});
} else {
got.post(context.URL, {
body: event,
headers: {
'X-Twilio-Signature': signature
}
}).then(response => {
callback(null, response.body);
}).catch(error => callback(error, null));
}
};
function getSignature(authToken, url, params) {
Object.keys(params).sort().forEach((key) => {
url = url + key + params[key];
});
return crypto.createHmac('sha1', authToken).update(Buffer.from(url, 'utf-8')).digest('Base64');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment