0

On Twilio I have a very simple solution to play an audio file to an incoming call. I want to configure such that it will play a different Mp3 dependant on the day of week. e.g. Mon-Friday = first mp3 file Sat-Sun = second mp3 file

Currently I have to change on a friday evening

I am not a coder so struggling

Current Function below

exports.handler = function (context, event, callback) {
    let twiml = new Twilio.twiml.VoiceResponse();

    twiml.say(
        { voice: 'alice', language: 'en-GB' },
        'Welcome to xxxx.');
    twiml.play("url of mp3 file");
    callback(null, twiml);
};

Alex Baban
  • 11,312
  • 4
  • 30
  • 44

1 Answers1

0

You could use getDay() to get an index (a number between 0 and 6) representing the day of the week. For example 0 for Sunday, 1 for Monday and so on until 6 for Saturday.

getDay() docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay

As such code for your function would become:

const date = new Date();

exports.handler = function (context, event, callback) {
    let twiml = new Twilio.twiml.VoiceResponse();

    twiml.say({ voice: 'alice', language: 'en-GB' }, 'Welcome to xxxx.');

    switch (date.getDay()) {
        case 0:
        case 6:
            // Sunday and Saturday
            twiml.play("url of second mp3 file");
            break;
        default:
            // Monday to Friday
            twiml.play("url of first mp3 file");
    }

    callback(null, twiml);
};

The above code would work with times in UTC if run with Twilio Functions' runtime.


If you want to make this work for another timezone, for example Los Angeles, then you'll want to use the moment-timezone module.

The module needs to be added in the "Configuration/Dependencies" section of Twilio Functions where you "import NPM modules into your application" (https://www.twilio.com/console/functions/configure).

The code for the function would then be:

let moment = require("moment-timezone");
const date = moment().tz("America/Los_Angeles");

exports.handler = function (context, event, callback) {
    let twiml = new Twilio.twiml.VoiceResponse();

    twiml.say({ voice: 'alice', language: 'en-GB' }, 'Welcome to xxxx.');

    switch (date.day()) {
        case 0:
        case 6:
            // Sunday and Saturday
            twiml.play("url of second mp3 file");
            break;
        default:
            // Monday to Friday
            twiml.play("url of first mp3 file");
    }

    callback(null, twiml);
};

Alex Baban
  • 11,312
  • 4
  • 30
  • 44