Set up a Calendar Trigger immediately after creating the calendar

68 Views Asked by At

So I'm trying to set up an onEventUpdated trigger on a recently created calendar. The function creates a Sheet, a Calendar and a Trigger for that calendar, but the trigger can't be created due to the recent creation of the calendar and I get an error "Exception: No tienes acceso al calendario" (I'm sorry my native language is Spanish, but this can be translated as "Exception: You don't have access to the calendar").

I tried to solve this with a Utilities.sleep, but it has to wait like 15 secs to function properly, I think that's too much time. U have any other solution for this? I'll paste my code

const ui = SpreadsheetApp.getUi();
const SS = SpreadsheetApp.getActiveSpreadsheet();

function addPerson() {
  const personPrompt = ui.prompt('TITLE','Por favor ingrese el nombre de la persona a añadir.', ui.ButtonSet.OK_CANCEL);
  const personName = personPrompt.getResponseText();
  const calendar = CalendarApp.createCalendar(personName);
  const calendarID = calendar.getId();
  const sheet = SS.insertSheet(personName, SS.getSheets().length);
  Utilities.sleep(15000); //Here is the workaround that I found
  ScriptApp.newTrigger('masterFunction')
    .forUserCalendar(calendarID)
    .onEventUpdated()
    .create();
}

I removed some of the lines that doesn't have anything to do with the problem, I hope u can help. Thx

1

There are 1 best solutions below

3
Cooper On

This worked for me:

Create this:

function myfunk() {
  Logger.log("I am here.");//Just something to catch the trigger
}

Run First:

function createACalendar() {
  const ui = SpreadsheetApp.getUi();
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const calendar = CalendarApp.createCalendar("Calendar1");
  const calendarID = calendar.getId();
  PropertiesService.getScriptProperties().setProperty("calid",calendarID);
}

Run Next:

function createTheTrigger() {
  let calendarID = PropertiesService.getScriptProperties().getProperty("calid");
  ScriptApp.newTrigger('myfunk')
    .forUserCalendar(calendarID)
    .onEventUpdated()
    .create();
}

Then this:

function myfunction() {
  let calendarID = PropertiesService.getScriptProperties().getProperty("calid");
  let cal = CalendarApp.getCalendarById(calendarID);
  let st = new Date();
  let ed = new Date();
  ed.setHours(23);//this may not work for you
  cal.createEvent("Event1",st,ed);
}