1

在电子表格中,我有一个用于在谷歌日历中计算小时数的应用脚本,并且输出被复制到电子表格中。

几天前,一切正常。

但是今天(2013 年 7 月 1 日星期一),当我尝试运行脚本时,每次都会收到“需要授权”的消息。

http://cl.ly/Q0bd

我按下“授权”按钮,然后重新运行,再次收到“需要授权”消息。

要点中的代码

// add menu
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{name:"Calcular Horas", functionName: "calculateHours"}];
ss.addMenu("Hours", menuEntries);
// calcular al iniciar
//calculateHours();
}
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("calendar");
var scope = "https://www.googleapis.com/auth/calendar";
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
}

/*
* Count hours of events with same name
*/
function countHours(calId, eventName){
authorize();
var cal = CalendarApp.getCalendarById(calId);
var key = "...";
var query = encodeURIComponent(eventName);
calId = encodeURIComponent(calId);
var params = {
method: "get",
oAuthServiceName: "calendar",
oAuthUseToken: "always",
};
var url = "https://www.googleapis.com/calendar/v3/calendars/"+
calId+"/events?q=" + query + "&key=" + key;
var request = UrlFetchApp.fetch(url, params);
//Logger.log(url);
var response = Utilities.jsonParse(request.getContentText());
var items = response.items;
var start, end;
var hours = 0;
for ( i = 0 ; i < items.length ; i++){
if ( items[i].status != "cancelled" ){
if ( items[i].summary == eventName ){
start = items[i].start.dateTime;
end = items[i].end.dateTime;
start = new Date(start.replace(/-/g,'/').replace(/[A-Z]/,' ').substr(0,19) );
end = new Date(end.replace(/-/g,'/').replace(/[A-Z]/,' ').substr(0,19));
hours = hours + ( end - start ) / ( 1000 * 60 * 60 );
}
}
}
return hours;
}

function calculateHours(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheets()[0];
var rows = s.getDataRange();
var nRows = rows.getNumRows();
var values = rows.getValues();
// from second row
for ( var i = 1; i < nRows ; i ++){
var row = values[i];
var h = countHours(row[0], row[1]);
s.getRange(i+1, 3).setValue(h);
}
}

编辑

当我换线时

var url = "https://www.googleapis.com/calendar/v3/calendars/"+
calId+"/events?q=" + query + "&key=" + key;

var url = "https://www.googleapis.com/calendar/v3/calendars/"+
"primary"+"/events?q=" + query + "&key=" + key;

这项工作,但仅对主日历有效。

4

1 回答 1

0

最后,我将日历 API 的访问更改为 CalendarApp 服务.getEvents

var cal = CalendarApp.getCalendarById(cal_id);
var this_year = new Date(2013,0,1);
var now = new Date()
var events = cal.getEvents(this_year, now, {search: event_name});
于 2013-07-07T16:22:19.603 回答