Google Apps Script使用异常求助:getEvents方法找不到报错
Hey there, let’s troubleshoot that frustrating error you’re seeing with getEvents() in Google Apps Script. I’ll break down the most likely issues and how to fix them step by step:
1. Missing or Incomplete Calendar Authorization
First off, Google Apps Script requires explicit permission to access your Calendar data. If you skipped the authorization prompt when first running the script, or if the authorization didn’t complete successfully, you’ll get misleading errors like "Cannot find method getEvents" (under the hood, it’s a permissions issue blocking the method call).
Fix:
- Re-run your script. You’ll see a prompt asking for permission to access your Google Calendar. Follow the steps to grant access—make sure you select the account associated with the calendar you’re trying to access.
2. Invalid Calendar ID
If the calendar ID you’re using ("aaaaaaaaaaaaaaaaaaaaa@group.calendar.google.com") is incorrect, getCalendarById() will return null. Calling getEvents() on null triggers the "Cannot find method" error because null doesn’t have that method.
Fix:
- Double-check your calendar ID:
- Open Google Calendar.
- Find the target calendar in the left sidebar, click the three dots next to it > Settings and sharing.
- Scroll down to the "Integrate calendar" section and copy the full, correct Calendar ID.
3. Wrong Parameter Type for getEvents()
The getEvents() method requires Date objects as start and end parameters, but you’re passing strings ("2018-04-03" and "2018-04-10"). While some implicit conversion might work in rare cases, this is a common source of errors and violates the official API requirements.
Fix:
Convert those strings to valid Date objects:
var startDate = new Date("2018-04-03"); var endDate = new Date("2018-04-10"); var events = calendar.getEvents(startDate, endDate);
4. Bonus: Date Calculation & doGet() Issues
- Your
twoHoursFromNowcalculation is off:300 * 60 * 60 * 1000equals 300 hours, not 2. For 2 hours later, use2 * 60 * 60 * 1000. doGet()is a special function used for Web Apps—you can’t call it directly from a regular function likemyFunction(). If you want to log events, useLogger.log(events); if you’re building a Web App, restructure your code to handle requests properly.
Corrected Full Code Example
Here’s your script with all the fixes applied:
function myFunction() { var now = new Date(); var twoHoursFromNow = new Date(now.getTime() + (2 * 60 * 60 * 1000)); // Fixed to 2 hours later var calendarId = "your-correct-calendar-id@group.calendar.google.com"; var calendar = CalendarApp.getCalendarById(calendarId); // Check if calendar exists to avoid null errors if (!calendar) { Logger.log("Error: Calendar not found. Verify your calendar ID!"); return; } var startDate = new Date("2018-04-03"); var endDate = new Date("2018-04-10"); var events = calendar.getEvents(startDate, endDate); Logger.log('Number of events: ' + events.length); }
内容的提问来源于stack exchange,提问作者Timothy

