简体   繁体   English

如何使用 Google 日历 API 和 Apps 脚本找到与多个参与者开会的时间?

[英]How to find a time for a meeting with several participants using Google Calendar API and Apps Script?

I am working on a chatbot project using Dialogflow API, Apps Script, Calendar API.我正在使用 Dialogflow API、Apps 脚本、日历 API 进行聊天机器人项目。 The chatbot should be able to organize a meeting between two or more participants directly from the chat.聊天机器人应该能够直接从聊天中组织两个或更多参与者之间的会议。 For example, the user says something like "organize a meeting with john.smith@mail.com for tomorrow at 5 pm" and the chatbot should go to both my and John's calendars, check availability for this time frame and book the meeting.例如,用户说“明天下午 5 点与 john.smith@mail.com 组织一次会议”,聊天机器人应该 go 到我和约翰的日历,检查此时间范围的可用性并预订会议。 So far so good.到目前为止,一切都很好。 I already have the solution up to this stage (check the code snippet below).我已经有了这个阶段的解决方案(检查下面的代码片段)。 My question is if the users are busy for this time frame, how can I get the suggested time where all the participants are free.我的问题是,如果用户在这个时间范围内很忙,我怎样才能获得所有参与者都空闲的建议时间。 I am using the Free/Busy call but it only returns when the users are busy.我正在使用空闲/忙碌呼叫,但它仅在用户忙碌时返回。

//the function search in spreadshet containing all timezones and selects the corresponding offset
function setCorrectTimeZone(rawTime,rawDate){
  var spreadSheet = SpreadsheetApp.openById("10tJCi5bRHs3Cl8Gvw8NGMeHhfRBDnvPD338peH2MWyg"); //the timezones sheed ID stored in CEE Google Assistant shared drive
  var sheet = spreadSheet.getSheetByName("timezones");
  var timezoneRange = sheet.getRange(2, 1, 513, 2).getValues();
 
  //getting the user's timezone
  var userTimeZone = CalendarApp.getDefaultCalendar().getTimeZone();
  Logger.log("User time zone: " + userTimeZone);
  
  var userTimeZoneOffset = "";
  var correctDateTimeAndZone = "";

  //iterating over the timezones from the sheet and comparing with user's to find the correct offset
  for(var i = 0; i<timezoneRange.length; i++){
    if(timezoneRange[i][1] == userTimeZone){
      userTimeZoneOffset = timezoneRange[i][0];
    }
  }
  
  //taking the date only
  var date = rawDate.split('T')[0];
  //taking the time only
   var timeNoTimeZone = rawTime.split('+')[0].split('T')[1];
  //concatenating the date, time and the correct timezone together
  correctDateTimeAndZone = date + 'T' + timeNoTimeZone + userTimeZoneOffset;
  return correctDateTimeAndZone;
}


function organizeMeeting(dialogflowRawResponse, email) {  
  var guestEmail = dialogflowRawResponse.queryResult.parameters.email; //the list of all guests
  var rawDate = dialogflowRawResponse.queryResult.parameters.date; 
  var rawTime = dialogflowRawResponse.queryResult.parameters.time;
  var eventTitle = dialogflowRawResponse.queryResult.parameters.meetingName;
  var hasAllParams = dialogflowRawResponse.queryResult.hasOwnProperty('allRequiredParamsPresent'); //checker for all parameters
  var correctedTimezone = setCorrectTimeZone(rawTime,rawDate);
  Logger.log("Has all required parameters? " + hasAllParams);
  
  //check if all parameters are passed
  while(hasAllParams == false){
    Logger.log("Parameters are missing");
    Logger.log(dialogflowRawResponse.queryResult.fulfillmentText);
    return { text: dialogflowRawResponse.queryResult.fulfillmentText };
  }
  
  Logger.log("Guests email list detected: " + JSON.stringify(guestEmail) + "\nDate-time detected: " + rawTime + "\nCorrect date-time timezone: " + correctedTimezone +"\nTitle detected: " + eventTitle);

  //setting the date-time for the start and the end of the event
  var dateTimeStart = new Date(correctedTimezone);
  var dateTimeEnd = new Date(correctedTimezone);
  dateTimeEnd.setHours(dateTimeEnd.getHours() + 1);
  dateTimeStart = dateTimeStart.toISOString();
  dateTimeEnd = dateTimeEnd.toISOString();
  Logger.log("ISO dateTimeStart: " + dateTimeStart);
  Logger.log("ISO dateTimeEnd: " + dateTimeEnd);
  
  
  var participants = [{"id": email}]; //array of objects. Each object is a particpant for the event
  for(var i = 0; i < guestEmail.length; i++){
    participants.push({"id": guestEmail[i]}); //filling the participant array
  }
 
  //preparing the body for the Calendar API free-busy request
  var requestBody = {
    "timeMin": dateTimeStart,
    "timeMax": dateTimeEnd,
    "items": participants
  }
  
  //Calendar freebusy request to check if the slot is available for all particiaptns
  var response = Calendar.Freebusy.query(requestBody);
  
  for(var i = 0; i < participants.length; i++){
    var calendarId = participants[i].id;
    if(response.calendars[calendarId]['busy'].length != 0){
      Logger.log(calendarId + " is busy at this time");
      return { text: calendarId + " is busy at this time" };
      break;
    }
  } 
  
  //guest array of objects for each participant
  var guestsArr = [{"email":email}];
  for(var i = 0; i < guestEmail.length; i++){
    guestsArr.push({"email": guestEmail[i]});
  }
  
  //preparing the event details for the Calendar API call
  var event = {
    "summary": eventTitle,
    "end": {
      "dateTime": dateTimeEnd
    },
    "start": {
      "dateTime": dateTimeStart
    },
    "attendees": guestsArr
  }
  
  //preapring the event options for the Calendar API call
  var eventOptions = {
    "sendNotifications": true,
    "sendUpdates": "all"
  }
  
  //Calendar API call
  var calendarEventRequest = Calendar.Events.insert(event, "primary",eventOptions);
  
  //logs the Calendar API response to the logs
  Logger.log(JSON.stringify(calendarEventRequest));
  
  
  return { text: "Done! Check you calendar." };
}

The code above takes the parameters from Dialogflow API - date, time, meeting title, and participants and uses this information to make free/busy call and then Calendar API call eventually.上面的代码从 Dialogflow API 中获取参数 - 日期、时间、会议标题和参与者,并使用此信息进行忙/闲通话,然后最终调用日历 API。 It is also using spreadsheet db to find the correct user timezone based on the user location.它还使用电子表格数据库根据用户位置查找正确的用户时区。

Any help will be highly appreciated if someone has already done such feature to get available time slots.如果有人已经完成了此类功能以获得可用的时间段,我们将不胜感激。

You can check each one-hour timeslot if everyone is free, if they are all free, then send the invitations in Calendar.如果每个人都有空,您可以检查每个一小时的时间段,如果他们都有空,然后在日历中发送邀请。

Sample Code:示例代码:

    var dateTimeStart = new Date(correctedTimezone);
    var dateTimeEnd = new Date(correctedTimezone);

do {

    dateTimeEnd.setHours(dateTimeStart.getHours() + 1);
    dateTimeStart = dateTimeStart.toISOString();
    dateTimeEnd = dateTimeEnd.toISOString();
    Logger.log("ISO dateTimeStart: " + dateTimeStart);
    Logger.log("ISO dateTimeEnd: " + dateTimeEnd);
  
  
    var participants = [{"id": email}]; //array of objects. Each object is a particpant for the event
    for(var i = 0; i < guestEmail.length; i++){
        participants.push({"id": guestEmail[i]}); //filling the participant array
    }
 
  //preparing the body for the Calendar API free-busy request
    var requestBody = {
        "timeMin": dateTimeStart,
        "timeMax": dateTimeEnd,
        "items": participants
    }
  
  //Calendar freebusy request to check if the slot is available for all particiaptns
    var response = Calendar.Freebusy.query(requestBody);
  
    for(var i = 0; i < participants.length; i++){
        var calendarId = participants[i].id;
        if(response.calendars[calendarId]['busy'].length != 0){
           dateTimeStart.setHours(dateTimeStart.getHours() + 1);
           Logger.log(calendarId + " is busy at this time");
           //return { text: calendarId + " is busy at this time" };
        break;
    }
  } 

}
while (response.calendars[calendarId]['busy'].length != 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未订阅时如何使用Google Apps日历邀请某人参加会议 - How do I invite someone to a meeting using google apps calendar when I am not subscribed to it Google Apps Script:使用 Calendar API 设置事件的颜色 - Google Apps Script: Setting color of an event using Calendar API 日历 API 仅使用 Google Apps 脚本修改以下事件 - Calendar API to modify the following events only using Google Apps Script 如何将组织中所有用户的 Google 日历会议/活动信息从 Google 日历导入 Google 表格(使用 API) - How to import Google calendar meeting/events information of all users in the organisation from Google Calendar to Google sheets (using API) 如何使用Google Apps脚本读取日历事件重复设置 - How to Read Calendar Event Recurrence Settings Using Google Apps Script 如何使用Apps脚本获取Google日历事件附件 - How to get Google calendar event attachment using Apps Script 如何在 Google Apps Script for Google Calendar 中相对于现有事件调整开始和结束时间 - How to adjust start and end time in Google Apps Script for Google Calendar relative to existing event 使用Apps脚本更改Google日历中单个日历事件的颜色 - Change color of an individual Calendar Event in Google Calendar using Apps Script 使用Google Apps脚本响应Google Calendar API的推送通知 - Responding to Google Calendar API's push notifications with Google Apps Script 将Google Apps配置文件API与Apps脚本一起使用 - Using Google Apps Profiles API with Apps Script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM