Google Apps Script snippets ᕦʕ •ᴥ•ʔᕤ

Delete specific events from Google Calendar series

Snippet of Delete specific events from Google Calendar series

Note: For bulk operations please use Google Calendar API Batch Requests. See: Sending Batch Requests  |  Calendar API  |  Google Developers, tanaikech/BatchRequest: This is a library for running Batch Requests using Google Apps Script (GAS).

Snippet

index.js
/**
 *
 * Deletes only specific events from series that match by date and search term
 * Retuns affected events
 *
 * @param {string} calendarId
 * @param {Date} start
 * @param {Date} end
 * @param {string} search
 * @returns {GoogleAppsScript.Calendar.Schema.Event[]}
 */
function deleteEventFromSeries(calendarId, start, end, search) {
  const timeMin = start.toISOString();
  const timeMax = end.toISOString();
  const events = Calendar.Events.list(calendarId, {
    timeMin,
    timeMax,
    q: search,
    singleEvents: true,
    fields: 'items',
  });
  return events.items.length
    ? events.items
        .filter((event) => event.recurringEventId)
        .map(
          (event) => (
            (event.status = 'cancelled'),
            Calendar.Events.patch(event, calendarId, event.id)
          )
        )
    : [];
}

Run it

run.js
/* global deleteEventFromSeries */

/**
 * Run the snippet
 */
function run() {
  const calendar = CalendarApp.getCalendarById(
    'jllt2nf095qf4ea1pfl1qm1o4o@group.calendar.google.com'
  );
  const now = new Date();
  now.setDate(now.getDate());
  const start = new Date(now);
  start.setHours(0, 0, 0, 0);
  const end = new Date(now);
  end.setHours(23, 59, 59, 999);
  end.setDate(end.getDate() + 2);
  console.log(deleteEventFromSeries(calendar.getId(), start, end, 'event'));
}

Manifest

appsscript.json
{
  "timeZone": "Europe/Moscow",
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Calendar",
        "version": "v3",
        "serviceId": "calendar"
      }
    ]
  }
}

#calendar