Skip to content

Instantly share code, notes, and snippets.

@xianny
Last active September 3, 2021 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xianny/024964bb8a4c23d7779b1cee0550d696 to your computer and use it in GitHub Desktop.
Save xianny/024964bb8a4c23d7779b1cee0550d696 to your computer and use it in GitHub Desktop.
Google Apps Script to sync personal calendar with work calendar
/**
Google Drive > New > Apps Script
Paste below into Code.gs file
On the left sidebar, look for triggers menu to add a time-based trigger.
*/
const ID = "" // FILL IN secondary calendar ID
const EVENT_NAME = "busy (autosync)" // change event name
const DAYS_TO_SYNC = [1,2,3,4,5] // add 6, 7 to monitor weekends too
const DAYS_BUFFER = 14 // how many days in advance to monitor
function sync() {
var secondaryCal=CalendarApp.getCalendarById(ID);
var today=new Date();
var enddate=new Date();
enddate.setDate(today.getDate()+DAYS_BUFFER);
var secondaryEvents=secondaryCal.getEvents(today,enddate).filter(e => DAYS_TO_SYNC.includes(e.getStartTime().getDay()));
var primaryCal=CalendarApp.getDefaultCalendar();
var primaryEvents=primaryCal.getEvents(today,enddate);
// delete previously synced events if they no longer exist in the secondary calendar
var previouslySynced = primaryEvents.filter(e => e.getTitle() == EVENT_NAME)
for (const prev of previouslySynced) {
if (!secondaryEvents.includes(se => se.getStartTime() === prev.getStartTime() && se.getEndTime() === prev.getEndTime())) {
prev.deleteEvent();
}
}
for (const se of secondaryEvents)
{
if (primaryEvents.includes(p => p.getStartTime() == se.getStartTime() && p.getEndTime() == se.getEndTime() && p.getTitle() == EVENT_NAME)) continue;
if (se.isAllDayEvent()) continue;
// secondary calendar owner not going
if (se.getGuestByEmail(ID)?.getGuestStatus()?.toString() === "NO") continue;
// no one else going
const guests = se.getGuestList();
if(guests.length > 0 && guests.every(g => g.getGuestStatus().toString() === "NO")) continue;
var newEvent = primaryCal.createEvent(EVENT_NAME,se.getStartTime(),se.getEndTime());
// alternative version below that copies the exact secondary event information into the primary calendar event
// var newEvent = primaryCal.createEvent(se.getTitle(),se.getStartTime(),se.getEndTime(), {location: se.getLocation(), description: se.getDescription()});
newEvent.removeAllReminders(); // so you don't get double notifications. Delete this if you want to keep the default reminders for your newly created primary calendar events
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment