React on Google Calendar change with Apps Script and EventUpdated trigger

Stéphane Giron
2 min readApr 10, 2020

--

Update 2022/04/27 : I have updated the code as the sync token is not present automatically in the first page you need to browse all pages.

A quick post as I had to deal with a script that run when a new event or an event is updated in my Google Calendar. Hopefully in Apps Script we have an EventUpdated trigger.

First the name of this trigger is a bit confusing as it will react for any change on your calendar event created or updated not only update as the name could suggest.

How it works

You have full documentation there : view page

Steps to perform are :

  1. Enable the Calendar advanced service.
  2. Run Events.list() method.
  3. Retrieve nextSyncToken and store it for later use.
  4. Create EventUpdated trigger
  5. When trigger is fired, perform Events.list() request with the syncToken previously stored
  6. Examine the answer
  7. Retrieve new nextSyncToken
  8. Store this token for newt run

Apps Script code for Google Calendar EventUpdated trigger

function init() {
var syncToken ; var nextPageToken ;
var now = new Date();
do{
var page = Calendar.Events.list('primary', {
timeMin: now.toISOString(),
pageToken:nextPageToken}) ;
if(page.items && page.items.length > 0){
syncToken= page.nextSyncToken;
}
nextPageToken = page.nextPageToken;
}while(nextPageToken)
PropertiesService.getUserProperties().setProperty('SYNC_TOKEN', syncToken)

ScriptApp.newTrigger('calendarSync')
.forUserCalendar(Session.getEffectiveUser().getEmail())
.onEventUpdated()
.create()
}
function calendarSync(e){
var syncToken = PropertiesService.getUserProperties().getProperty('SYNC_TOKEN')
var page = Calendar.Events.list('primary', {syncToken:syncToken}) ;
if(page.items && page.items.length > 0){
for(var i = 0; i< page.items.length ; i++){
var item = page.items[i]
console.log(JSON.stringify(item))
// Do what you want
}
syncToken= page.nextSyncToken;
}
PropertiesService.getUserProperties().setProperty('SYNC_TOKEN', syncToken)
}

Get the code on GitHub : link

It is really amazing how it is simple to made this script and have an app that run on each change perform in your Google Calendar.

--

--