Calendar cannot be unsubscribed from. Try deleting instead

678 views Asked by At

Trying to understand if I'm doing something wrong here.

I'm trying to unsubscribe from a calendar using Apps Scripts, but it won't let me, I receive the error

Calendar [email protected] cannot be unsubscribed from. Try deleting instead.

Code:

function anotherTest(){
  var cal = CalendarApp.getCalendarById('[email protected]');
  cal.unsubscribeFromCalendar(); 
}

I don't own the calendar, but I do have rights to it. I tried issuing the cal.deleteCalendar() but it said "action not allowed".

1

There are 1 answers

0
Employee On

I ran in to the exact same problem. It seems like the Google Apps Script Calendar service produces those errors because it's trying to delete the actual calendar, rather than just unsubscribe from it.

My working solution involves using the CalendarList: delete method of the Google Calendar API instead of the Apps Script Calendar Service.

That deletes an entry from your list of calendars in the Google Calendar sidebar, which is the same thing as "unsubscribing". Also, it does not simply "hide" it from the list, it removes it altogether.

const calendarList = CalendarApp.getAllCalendars();

for (var i = 0; i < calendarList.length; i++) {
  const calendar = calendarList[i];

  // calendar.unsubscribeFromCalendar(); // results in "...cannot be unsubscribed from. Try deleting instead"
  // calendar.deleteCalendar(); // results in "...Action not allowed"

  Logger.log(`will remove calendar: ${calendar.getName()}`);

  const url = `https://www.googleapis.com/calendar/v3/users/me/calendarList/${encodeURIComponent(calendar.getId())}`;
    
  try {
    const response = UrlFetchApp.fetch(url, {
      headers: { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
      method: 'DELETE',
      muteHttpExceptions: false
    });

    const responseStatusCode = response.getResponseCode();
    Logger.log(`responseStatusCode: ${responseStatusCode}`);

    if (responseStatusCode === 200) {
      Logger.log('removed calendar');
    }
  } catch(e) {
    Logger.log(`failed to remove calendar: ${e.message}`);
  }
}