在Google Assistant Action中访问自有日历失败,求排查方案
问题排查与修复方案
嘿,我瞅了下你的代码,发现几个关键坑导致它没法正常运行,咱们一个个来解决:
1. 异步操作顺序搞反了!
jwtClient.authorize() 是异步操作,你现在在它还没完成认证的时候就直接调用了 calendar.events.list(),这时候授权还没完成,API调用肯定会失败。得把日历API的调用放到认证成功的回调里,等拿到有效token后再执行。
2. 服务账号没权限访问你的个人日历
服务账号是独立的Google身份,它默认只能访问自己的primary日历(这个日历是空的),根本碰不到你的个人日历。你得做两步:
- 把你的个人日历共享给服务账号的邮箱(就是你
privatekey.json里的client_email字段),权限至少设为「查看者」; - 调用API时别用
calendarId: 'primary',换成你个人日历的ID(可以在Google日历的「设置和共享」里找到)。
3. 边界情况没处理,容易崩
比如如果日历里没事件,events[0].summary会直接报错;还有API调用出错时,也得给用户返回友好提示,不能只在控制台打日志。
修正后的完整代码片段
//Specific action corresponding to the read Calendar intent. function readCalendarAction (assistant) { function finalResponse(response){ assistant.ask(response); //final response from fullfillment } let google = require('googleapis'); let privatekey = require("./mynewpk.json"); // 替换成你的个人日历ID const YOUR_CALENDAR_ID = 'xxxxxx@group.calendar.google.com'; // configure a JWT auth client let jwtClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, ['https://www.googleapis.com/auth/calendar.readonly'] // 建议用只读权限,更安全 ); //authenticate request jwtClient.authorize(function (err, tokens) { if (err) { console.log(err); finalResponse('抱歉,现在没法访问日历信息,请稍后再试'); return; } console.log("Successfully connected!"); // 认证成功后再调用日历API let calendar = google.calendar('v3'); calendar.events.list({ auth: jwtClient, calendarId: YOUR_CALENDAR_ID, maxResults: 1, // 只取第一个事件,和你原来的逻辑一致 singleEvents: true, orderBy: 'startTime' }, function (err, response) { if (err) { console.log('The API returned an error: ' + err); finalResponse('抱歉,获取日历信息时出问题了'); return; } var events = response.items; if (events.length === 0) { finalResponse('你的日历里目前没有事件哦'); } else { var responseText = `最近的事件是:${events[0].summary}`; finalResponse(responseText); } }); }); }
内容的提问来源于stack exchange,提问作者JSnoobie
相关产品推荐
相关产品推荐

