Skip to content

Instantly share code, notes, and snippets.

@NickHolcombe
Last active April 3, 2020 11:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save NickHolcombe/435fc8c7b7ef919e635e2077b465a1ea to your computer and use it in GitHub Desktop.
Twilio function to turn a JSON object into menu options that play a podcast - from https://www.brightec.co.uk/blog/podcasting-to-those-without-internet-access
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
var fetch = require('node-fetch');
// Define the list of sermons and fetch the data
const url = '<enter the URL of the json object to read>';
fetch(url)
.then(response => response.json())
.then(function(data) {
// Validate we have some sermon data
const sermons = data.sermons;
if (data === undefined || sermons === undefined || sermons.length === 0) {
twiml.say({voice: 'alice', language: 'en-gb'}, 'Sorry an error occurred fetching the sermons');
callback(null, twiml);
twiml.hangup();
}
// Produce a menu based, on the sermons found, if no phone key(digit) was pressed...
if (event.Digits === undefined || event.Digits > sermons.length) {
const sermonMenu = sermons.map(sermon => 'Press '+sermon.id+' for '+sermon.title).join(",");
twiml.gather({numDigits: 1})
.say({voice: 'alice', language: 'en-gb'}, 'Welcome to Dial A Sermon, '+sermonMenu)
} else {
// ... otherwise, get the right sermon based on the key pressed.
const sermonIndex = event.Digits - 1;
const sermon = sermons[sermonIndex];
if (sermon === undefined) {
twiml.say({voice: 'alice', language: 'en-gb'}, 'Sorry an error occurred fetching the sermons');
callback(null, twiml);
twiml.hangup();
}
twiml.say({voice: 'alice', language: 'en-gb'}, 'Please wait whilst we fetch the sermon.');
twiml.play(sermon.url);
twiml.hangup();
}
callback(null, twiml);
})
.catch(function(error) {
callback(error)
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment