twiliotwilio-functions

Business hours Twilio Funtion


I want to create business hours for everyday of the week, rather than Monday through Friday and Saturday and Sunday. I'm using Twilio functions and Twilio Studio, however everything I've found online is not working. Currently I'm using the example they provide and I was wondering if someone can help me figured it out. Here is the code I'm using:

exports.handler = function(context, event, callback) {
    // With timezone:
    // In Functions/Configure, add NPM name: moment-timezone, version: 0.5.14
    // Timezone function reference: https://momentjs.com/timezone/
    let moment = require('moment-timezone');
    //
    // timezone needed for Daylight Saving Time adjustment
    let timezone = event.timezone || 'America/New_York';
    console.log("+ timezone: " + timezone);
    //
    const hour = moment().tz(timezone).format('H');
    const dayOfWeek = moment().tz(timezone).format('d');
    if ((hour >= 7 && hour < 19) && (dayOfWeek >= 1 && dayOfWeek <= 5)) {
        // "open" from 7am to 7pm, PST.
        response = "open";
    } else {
        response = "after";
    }
    theResponse = response + " : " + hour + " " + dayOfWeek;
    console.log("+ Time request: " + theResponse);
    callback(null, theResponse);
};

Thank you in advance!


Solution

  • Ok, so still the same place of code mentioned earlier, that this block of code will need to be updated to fit your needs.

    if ((hour >= 7 && hour < 19) && (dayOfWeek >= 1 && dayOfWeek <= 5)) {
        // "open" from 7am to 7pm, PST.
        response = "open";
    } else {
        response = "after";
    }
    

    Needs changing to:
    (As you gave 2 examples in your last comment, I show those below as the first two conditions.)

    if ((hour >= 7 && hour < 15) && dayOfWeek == 1) { // Monday, 7am to 3pm
        response = "open";
    } else if ((hour >= 11 && hour < 20) && dayOfWeek == 2) { // Tuesday, 11am to 8pm
        response = "open";
    } else if ((/* Wednesday's hour range */) && dayOfWeek == 3) { // Wednesday
        response = "open";
    } else if ((/* Thursday's hour range */) && dayOfWeek == 4) { // Thursday
        response = "open";
    } else if ((/* Friday's hour range */) && dayOfWeek == 5) { // Friday
        response = "open";
    } else if ((/* Saturday's hour range */) && dayOfWeek == 6) { // Saturday
        response = "open";
    } else if ((/* Sunday's hour range */) && dayOfWeek == 0) { // Sunday
        response = "open";
    } else {
        response = "after";
    }
    

    Then simply update the hour ranges for Wednesday to Sunday. Note that dayOfWeek for Sunday is 0, not 7, so that is not a typo.