Business hours Twilio Funtion

241 Views Asked by At

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!

3

There are 3 best solutions below

2
Paul T. On BEST ANSWER

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.

0
tcbeaton On

I know somebody already answered this question, but this might be helpful to you or others in the future. This is adapted from a tutorial on Twilio and runs as one of their serverless functions.

There is a JSON object containing holidays, office hours, and partial days. The function returns an object with a handful of flags (open, holiday, etc.), the greeting (morning, afternoon, evening), and the reason if it's a holiday or partial day.

const Moment = require( 'moment-timezone' );
const MomentRange = require( 'moment-range' );
const moment = MomentRange.extendMoment( Moment );
const timezone = "America/New_York";

exports.handler = async function(context, event, callback) {

  let response = new Twilio.Response();
  let client = context.getTwilioClient();

  response.setStatusCode( 200 );
  response.appendHeader('Access-Control-Allow-Origin', '*');
  response.appendHeader('Access-Control-Allow-Methods', 'OPTIONS, POST, GET');
  response.appendHeader('Access-Control-Allow-Headers', 'Content-Type');
  response.appendHeader('Content-Type', 'application/json');

  let body = getCalendarInfo();

  response.setBody(body);
  callback(null, response);

};

function checkIfInRange( begin, end, timezone ) {
  const currentDate = moment().tz( timezone ).format( 'MM/DD/YYYY' );
  const now = moment().tz( timezone );

  const beginMomentObject = moment.tz( `${currentDate} ${begin}`, 'MM/DD/YYYY HH:mm:ss', timezone );
  const endMomentObject = moment.tz( `${currentDate} ${end}`, 'MM/DD/YYYY HH:mm:ss', timezone );
  const range = moment.range( beginMomentObject, endMomentObject );

  return now.within( range );
}

function getCalendarInfo() {
  let body = {
    isOpen: false,
    isHoliday: false,
    isPartialDay: false,
    isRegularDay: false,
    greeting: '',
    reason: '',
    date: '',
    time: ''
  };

  //load JSON with schedule
  const schedule = {
    "holidays": {
      "01/03/2023": {
        "reason": "the New Year Holiday"
      },
      "01/16/2023": {
        "reason": "Martin Luther King Jr Day"
      }
    },
    "partialDays": {
    //    "12/26/2019": {
    //      "begin": "10:00:00",
    //      "end": "14:00:00",
    //      "reason": "the Day after Christmas"
    //    }
    },
    "regularHours": {
      "Monday": {
        "begin": "08:00:00",
        "end": "18:00:00"
      },
      "Tuesday": {
        "begin": "08:00:00",
        "end": "18:00:00"
      },
      "Wednesday": {
        "begin": "08:00:00",
        "end": "18:00:00"
      },
      "Thursday": {
        "begin": "08:00:00",
        "end": "18:00:00"
      },
      "Friday": {
        "begin": "08:00:00",
        "end": "23:59:00"
      },
      "Saturday": {
        "begin": null,
        "end": null
      },
      "Sunday": {
        "begin": null,
        "end": null
      }
    }
  }

  body.date = moment().tz( timezone ).format( 'MM/DD/YYYY' );
  body.time = moment().tz( timezone ).format( 'HH:mm:ss' );

  if ( body.time < "12:00:00" ) {
    body.greeting = "morning";
  } else if ( body.time < "18:00:00" ) {
    body.greeting = "afternoon";
  } else {
    body.greeting = "evening";
  }
  
  const currentDate = moment().tz( timezone ).format( 'MM/DD/YYYY' );

  const isHoliday = currentDate in schedule.holidays;
  const isPartialDay = currentDate in schedule.partialDays;

  if ( isHoliday ) {
    body.isHoliday = true;

    if ( typeof( schedule.holidays[ currentDate ].reason ) !== 'undefined' ) {
      body.reason = schedule.holidays[ currentDate ].reason;
    }

  } else if ( isPartialDay ) {
    body.isPartialDay = true;

    if ( typeof( schedule.partialDays[ currentDate ].reason ) !== 'undefined' ) {
      body.reason = schedule.partialDays[ currentDate ].reason;
    }

    if ( checkIfInRange( schedule.partialDays[ currentDate ].begin,
         schedule.partialDays[ currentDate ].end, timezone ) === true ) {
      body.isOpen = true;
    }
  } else {
    //regular hours
    const dayOfWeek = moment().tz( timezone ).format( 'dddd' );

    body.isRegularDay = true;
    
    if ( checkIfInRange( schedule.regularHours[ dayOfWeek ].begin,
        schedule.regularHours[ dayOfWeek ].end, timezone ) === true ) {
      body.isOpen = true;
    }
  }
  return body;
}
2
BOCASTEVE On
exports.handler = function(context, event, callback) {
let newyork_datetime_str = new Date().toLocaleString("en-US", { 
timeZone: "America/New_York" });
const currentDay = new Date(newyork_datetime_str).getDay();
const currentHour = new Date(newyork_datetime_str).getHours();
const operatingHours = {
0: { start: 11, end: 16 }, // Sunday: 11am to 4pm
1: { start: 7, end: 20 }, // Monday: 7am to 8pm
2: { start: 7, end: 20 }, // Tuesday: 7am to 8pm
3: { start: 7, end: 20 }, // Wednesday: 7am to 8pm
4: { start: 7, end: 20 }, // Thursday: 7am to 8pm
5: { start: 7, end: 20 }, // Friday: 7am to 8pm
6: { start: 8, end: 16 } // Saturday: 8am to 8pm
};
if (operatingHours[currentDay] && currentHour >= 
operatingHours[currentDay].start && currentHour < 
operatingHours[currentDay].end) {
// Perform allowed action 
callback(null, "open");
} else {
// Return an error or take some other action
callback(null, "closed"); }
};