我正在开发一个 Google 日历项目,通过该项目我将删除旧的“事件”并用新的“事件”替换它们。 Tanaike 慷慨地帮助我利用 Google Calendar API 和他的 Google Apps 脚本库,以便能够在单个批量请求中添加事件此处,大大加快了流程。
由于多人以多种方式编辑多个条目相关的复杂性,我决定通过这种方式来处理它。
我有一个脚本,可以成功地迭代定义的开始日期和结束日期之间的每个 Google 日历事件。 我现在正在努力解决的是以与将事件添加到 Google 日历相同的方式删除两个日期内的所有事件,即单个批量请求。 有这个可能吗?
这是我当前的脚本(可以工作,但需要优化):
function deleteEvents() {
var today = new Date();
var startDate = new Date(today.getFullYear(),today.getMonth(),today.getDate()-14);
var endDate = new Date(today.getFullYear()+1,today.getDate());
// ID of the Calendar to access
var calendarID = 'xxxxxxxxxx';
// get the Calendar
var calendar = CalendarApp.getCalendarById(calendarID);
// get all existing events between date range
var existingEvents = calendar.getEvents(startDate, endDate);
// count and log the number of found events
var numEvents = existingEvents.length;
// loop through found events ***************
for (var i = 0; i < numEvents; i++) {
// create variable for current event
var event = existingEvents[i];
// delete the event
event.deleteEvent();
}
}
我相信您的目标如下。
既然如此,下面的修改如何?
为了使用批量请求,需要创建请求体。 参考但是,我认为这可能有点困难。因此,我将其创建为 Google Apps 脚本库。 Ref 在这个答案中,使用了这个库。
请安装 Google Apps 脚本库的 BatchRequest。您可以在此处查看如何安装它。
请在高级 Google 服务中启用日历 API。 参考
当使用上述库和日历API修改你的脚本时,它会变成如下所示。
function deleteEvents() {
var calendarID = "###"; // Please set your calendar ID.
var today = new Date();
var startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 14);
var endDate = new Date(today.getFullYear() + 1, today.getDate());
var calendar = CalendarApp.getCalendarById(calendarID);
var existingEvents = calendar.getEvents(startDate, endDate);
// Create a request body for the batch request.
var requests = existingEvents.map(e => ({
method: "DELETE",
endpoint: `https://www.googleapis.com/calendar/v3/calendars/${calendarID}/events/${e.getId().split("@")[0]}`,
}));
// Request the batch request using the created request body.
var result = BatchRequest.EDo({ batchPath: "batch/calendar/v3", requests });
console.log(result);
}
existingEvents
的事件将随批量请求一起删除。请注意这一点。因此,我建议使用示例事件和日历来测试此脚本。