Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Set the ID of the team calendar to add events to. You can find the calendar's
// ID on the settings page.
var TEAM_CALENDAR_ID = '*****@group.calendar.google.com';
// Set the email address of the Google Group that contains everyone in the team.
// Ensure the group has less than 500 members to avoid timeouts.
var GROUP_EMAIL = '***@****.com';
var MONTHS_IN_ADVANCE = 1;
// If your imported the holiday calendars past their ID's here
var CALENDER_IDS = [
"****@import.calendar.google.com",
"****@group.v.calendar.google.com",
"****@group.v.calendar.google.com",
]
var gxCalendar = CalendarApp.getCalendarById(TEAM_CALENDAR_ID);
/**
* Setup the script to run automatically every hour.
*/
function setup() {
var triggers = ScriptApp.getProjectTriggers();
if (triggers.length > 0) {
throw new Error('Triggers are already setup.');
}
ScriptApp.newTrigger('sync').timeBased().everyHours(1).create();
// Run the first sync immediately.
sync();
}
/**
* Look through the group members' public calendars and add any
* 'vacation' or 'out of office' events to the team calendar.
*/
function sync() {
// Define the calendar event date range to search.
var today = new Date();
var maxDate = new Date();
maxDate.setMonth(maxDate.getMonth() + MONTHS_IN_ADVANCE);
// Determine the time the the script was last run.
var lastRun = PropertiesService.getScriptProperties().getProperty('lastRun');
lastRun = lastRun ? new Date(lastRun) : null;
// Get all events of calenadrs
for (var i = 0, clen = CALENDER_IDS.length; i < clen; i++) {
var cal = CalendarApp.getCalendarById(CALENDER_IDS[i]);
var events = cal.getEvents(today, maxDate);
for(var i=0; i<events.length;i++) {
var event = events[i];
importEvent(cal.getName(), event);
}
}
PropertiesService.getScriptProperties().setProperty('lastRun', today);
}
/**
* Imports the given event from the user's calendar into the shared team
* calendar.
* @param {string} username The team member that is attending the event.
* @param {Calendar.Event} event The event to import.
*/
function importEvent(calendarname, event) {
console.log('Importing: %s', event.summary);
try {
gxCalendar.createAllDayEvent('[' + calendarname + '] ' + ' -> ' + event.getTitle(), event.getAllDayStartDate(), event.getAllDayEndDate());
} catch (e) {
console.error('Error attempting to import event: %s. Skipping.',
e.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment