使用Google Apps Script复制日历事件时获取附件报错
解决日历事件复制时的"Not Found"错误及附件/颜色保留问题
嘿,我看你在复制日历事件时遇到了"Not Found"的报错,核心问题其实是Calendar.Events.get()的参数用错了——这个方法的第一个参数需要传日历ID字符串,而不是CalendarApp返回的Calendar对象!我给你修正了代码,还优化了一些细节,确保附件和事件颜色都能正确复制:
修正后的完整代码
function copyCalendarEventsWithAttachmentsAndColor() { const sourceCalendarId = "somecalendarIDhere@group.calendar.google.com"; const destCalendarId = "primary"; const calendarSource = CalendarApp.getCalendarById(sourceCalendarId); const calendarDestination = CalendarApp.getCalendarById(destCalendarId); // 按需调整时间范围 const startDate = new Date("July 21, 2009 EST"); const endDate = new Date("July 22, 2018 EST"); const eventsToCopy = calendarSource.getEvents(startDate, endDate); for (const event of eventsToCopy) { try { // 重点修正:传入日历ID字符串而非Calendar对象 const eventDetails = Calendar.Events.get(sourceCalendarId, event.getId(), { fields: "attachments(fileId)" }); // 处理无附件的情况,避免报错 const fileIds = eventDetails.attachments ? eventDetails.attachments.map(att => att.fileId) : []; // 构建事件创建选项 const eventOptions = { description: event.getDescription(), location: event.getLocation(), attachments: fileIds }; // 创建新事件并同步颜色 const newEvent = calendarDestination.createEvent( event.getTitle(), event.getStartTime(), event.getEndTime(), eventOptions ); newEvent.setColor(event.getColor()); console.log(`成功复制事件:${event.getTitle()}`); } catch (error) { console.error(`复制事件「${event.getTitle()}」失败:${error.message}`); } } }
关键问题解析与优化点
参数类型错误(报错根源):
原来的代码里把calendarSource(Calendar对象)传给了Calendar.Events.get(),但这个方法要求第一个参数是纯日历ID字符串(比如你定义的somecalendarIDhere@group.calendar.google.com),这就是导致"Not Found"的直接原因。空附件容错处理:
加了判断逻辑,如果事件没有附件,就返回空数组,避免出现Cannot read property 'map' of undefined的新错误。循环方式优化:
把for (var i in eventToCopy)改成了for...of循环,这种方式更适合数组遍历,不会意外遍历到数组原型上的额外属性,代码更安全。错误捕获机制:
新增try...catch块,就算某个事件复制失败,脚本也会继续处理剩下的事件,还能在控制台看到具体哪个事件出了问题,方便排查。
额外注意事项
- 权限检查:确保脚本有访问源日历、目标日历,以及附件对应Drive文件的权限(如果附件是Drive文件,需要授权Drive API访问)。
- 颜色兼容性:如果发现事件颜色没有同步成功,可能是不同日历的颜色ID不兼容,可以尝试用
CalendarApp.EventColor常量(比如CalendarApp.EventColor.BLUE)替代event.getColor()返回的ID。 - API启用确认:你已经提到激活了Google API,这一步没问题,但如果还是有问题,可以再检查一遍Calendar API是否在你的Google Cloud项目中正确启用。
内容的提问来源于stack exchange,提问作者Riccardo
相关产品推荐
相关产品推荐

