Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - Adding guests to calendar event

I have a script which adds guests to an event from a spreadsheet, but it is only adding the first guest from the loop. Logger shows the list of people, yet only one gets added in the calendar. Here is my code:

for (var i = 0; i < registrationData.length; i++)  {  
   var session = registrationData[i][0]; 
   var email = registrationData[i][2];
   var eventId = session.toString().replace("@google.com","");
   var event = Calendar.Events.get(sharedCalendar, eventId);
   var add = calendarApp.getCalendarById(sharedCalendar).getEventSeriesById(session).addGuest(email);  

I also create a link with new calendar advanced services which goes out in an email, yet I just get the message that the event was deleted from the users calendar. Could this be because they aren't being added properly as a guest first?

var link = Calendar.Events.get(usersCalendar, eventId).htmlLink;

Thanks to anyone who can help!

Edit: New working loop with Serge's fabulous help

    for (var i = 0; i < registrationData.length; i++) {
         var guestEmail = registrationData[i][2];  
         var eventId = registrationData[i][0]; 
         var session = eventId.toString().replace("@google.com","");
         var event = CalendarApp.getCalendarById(sharedCalendar).getEventSeriesById(eventId);
         var link = Calendar.Events.get(sharedCalendar, session).htmlLink;
         event.addGuest(guestEmail);
         Logger.log('guest for i='+i+' is '+guestEmail);
      }      
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT : following your edit :

try it like this :

for (var i = 0; i < registrationData.length; i++)  {  
  var session = registrationData[i][0]; 
  var eventId = session.toString().replace("@google.com","");// is that really the event Id ?
  var event = sharedCalendar.getEventSeriesById(session);
  var inviteList = registrationData[i][2].split(',');//assuming your guestlist is comma separated
  if (inviteList.length>0){ 
    for(var n in inviteList){
      event.addGuest(email);
    }
  }  
}

EDIT 2 adding Logs and adapting your code

try to add a few Logs to check your data, modified code below :

for (var i = 0; i < registrationData.length; i++)  {
var email = registrationData[i][2];  
var session = registrationData[i][0]; 
var event = CalendarApp.getCalendarById(sharedCalendar).getEventSeriesById(session);
var inviteList = email.split(',');//assuming your guestlist is comma separated
Logger.log('email='+email+'  ID='+session);
if (inviteList.length>0){ 
  for(var n in inviteList){
    var link = event.htmlLink;// I don't know this method ... where is it documented ?
    Logger.log('event Title='+event.getTitle()+' - guest='+inviteList[n]);
    event.addGuest(inviteList[n]);
  }
} 

check the log in menu/view/logs to see if your data is right (or not)


why are you using 2 calls, one to calendarApp and another to Calendar (advanced) ? you could write calendarApp.getCalendarById(sharedCalendar).getEventSeriesById(session).addGuest??(email)

below is the script that I wrote some time ago that invites all people who's emails are in the description automatically. it has a loop that actually adds the guests. And it works nicely.

A spreadsheet example (read only, make a copy to use)

// update the ID below to your copy ID and run the Callist() function to get the calendars ID on first sheet.
//set up an onOpen trigger for the myOnOpen function
var ss = SpreadsheetApp.openById('1xDOaoSl3HbkS95cj8Jl-82rdiui7G0sFz96PIO6iVF4');// this spreadsheet
var calNamesSheet = ss.getSheetByName('calNames');
var calList = calNamesSheet.getDataRange().getValues();

function MyOnOpen() {
  var menuEntries = [ {name: "Lauch autoInvite on all listed calendars", functionName: "autoInviteAllCals"},
                      {name: "delete created sheets", functionName: "delsheets"}
                     ];
  ss.addMenu("Tracking utilities",menuEntries);//
}

function autoInviteAllCals(){
  var today =  new Date(); // now
  var startDate = new Date(today.setHours(0,0,0,0));// today @ 0 AM
  var endDate = new Date(new Date(startDate).setDate(startDate.getDate()+7)); // adjust time frame to read here = 7 days
  for(var nn=0;nn<calList.length;nn++){
    var logArray = new Array();
    logArray.push(['Calendar + Title','Description','Start','End','Location','Creators','Date Created','Duration','Guests']);
    var calName = calList[nn][0];
    var calId = calList[nn][1];   
    var Calendar = CalendarApp.getCalendarById(calId);
    var events = Calendar.getEvents(startDate , endDate);
    if (events[0]) {
      for (var i = 0; i < events.length; i++) {
        var row = new Array();
        row.push(calName +' : '+events[i].getTitle());
        row.push(events[i].getDescription());      
        row.push(Utilities.formatDate(events[i].getStartTime(), Session.getScriptTimeZone(), "MMM-dd-yy")+' @ ' +Utilities.formatDate(events[i].getStartTime(), Session.getScriptTimeZone(), "HH:mm"));
        row.push(Utilities.formatDate(events[i].getEndTime(), Session.getScriptTimeZone(), "MMM-dd-yy")+' @ ' +Utilities.formatDate(events[i].getEndTime(), Session.getScriptTimeZone(), "HH:mm"));
        row.push(events[i].getLocation());      
        row.push(events[i].getCreators().join());
        row.push('on '+Utilities.formatDate(events[i].getLastUpdated(), Session.getScriptTimeZone(), "MMM-dd-yyyy"));
        row.push(((events[i].getEndTime() - events[i].getStartTime()) / 3600000)+' hours');//duration
        var inviteList = checkInvites(events[i]);
        if (inviteList.length==0){ // if guests were found in checkInvites() then don't read it from event since checkInvites() added them to the cal but this event is not yet updated
          var list = events[i].getGuestList();
          for(n=0;n<list.length;++n){inviteList.push(list[n].getEmail())};
        }else{
          for(var n in inviteList){
            events[i].addGuest(inviteList[n]);
          }
        }
        row.push(inviteList.join(', '));
        logArray.push(row);
      }
    }    
//    Logger.log(logArray);
    if(logArray.length==0){continue};
    try{
      var sheetToWrite = ss.insertSheet(calName,ss.getNumSheets());// create sheet if doesn't exist
    }catch(err){
      var sheetToWrite = ss.getSheetByName(calName);// else open it
      }
    sheetToWrite.getRange(1,1,logArray.length,logArray[0].length).setValues(logArray).setHorizontalAlignment('left'); // enhance formating
    sheetToWrite.getRange(1,1,1,logArray[0].length).setBackground('#EEA').setBorder(true,true,true,true,true,true).setHorizontalAlignment('left').setFontSize(12);
    for(var w in logArray[0]){
      sheetToWrite.setColumnWidth(Number(w)+1,180);
    }
  }
}

function checkInvites(event){
  var email = [];
  // below are 2 different regex to get emails from the title string.They return an array of valid emails.
  //both work very well, I don't really know why choose one or the other..., make your choice !
  var title = event.getTitle();
  if(title.indexOf('@')==-1){return email};
  email = title.match(/([w-.]+)@((?:[w]+.)+)([a-zA-Z]{2,4})/g);
  Logger.log('email var1 = '+JSON.stringify(email));
  var regex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|\[x01-x09x0bx0cx0e-x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|\[x01-x09x0bx0cx0e-x7f])+)])/gm
  email = title.match(regex);
  Logger.log('email var2 = '+JSON.stringify(email));
  return email;
}

function delsheets(){
  var numSheets = ss.getNumSheets()-1;
  for(var n = numSheets ; n>0 ; n--){
    if(ss.getSheets()[n].getName() != 'calNames'){
      ss.deleteSheet(ss.getSheets()[n]);
      Utilities.sleep(400);
    }
  }
}

// This small function is to get the list of calendar names & Ids that you have access to, please edit the calNames sheet to keep only the ones you want to monitor (without empty rows).
function Callist(){
  calNamesSheet.getDataRange().clearContent();                      
  var list = new Array();
  var store = new Array();
  list = CalendarApp.getAllCalendars()
  for (n=0;n<list.length;++n){
    var name = list[n].getName() ;                     
    var id = list[n].getId() ;                     
    store.push( [name,id])
  }        
  calNamesSheet.getRange(1,1,store.length,store[0].length).setValues(store);  
}

// Serge insas - 08-2014

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...