EventGuest getName() method not working - google-apps-script

I just started coding with Google Apps Script.
I tried to write a simple program to pull in events from my calendar and email all the guests in these events.
I have run into 2 problems:
the getName() method returns the guest's email address and not name, even though the name is defined in my Google contacts. (Also, if no name is defined, according to the documentation, it would return null).
I can't seem to use the getCalendarsByName method. getCalendarByID is working correctly, but the getCalendarsByName method doesn't return the calendar wanted. I've also tried getOwnedCalendarsByName, but that doesn't work either.
Would appreciate any help from anyone.
Update at 7/1 3.30pm: Thanks to #Serge insas, the second problem has been solved.
However, the first problem remains. Here's the code:
function myFunction() {
var calendar = CalendarApp.getCalendarsByName('Test Calendar');
Logger.log(calendar[0].getName());
var today = new Date(); // get today's date
Logger.log(today.toLocaleString());
var endDate = new Date();
endDate.setDate(today.getDate() +7); // set nextWeek's date to 7 days from today
Logger.log(endDate.toLocaleString());
var testEvents = calendar[0].getEvents(today, endDate);
Logger.log(testEvents[0].getTitle());
var guests = testEvents[0].getGuestList();
Logger.log(guests[0].getName());
}
Here is the Log output:
Test Calendar
July 1, 2012 3:27:58 PM EDT
July 8, 2012 3:27:58 PM EDT
Test Event 1
duytri.nguyen07#gmail.com
The last line is my email other email address, even though it has been named in my contacts.

The method getCalendarsByName() returns an array (that's why there is an 's' on Calendars), did you take this into account in your code by adding [0] behind it (assuming you have only one Cal with this name or that you want its first occurrence) ?
It would be easier to help you if you provide some code you are using.
(Concerning the guestName, same comment : please provide the code you are using.)
EDIT : thanks for the code. It seems you're right, it looks like an issue ;-/
since the guest must be in the contact list to be able to get his name I guess you could use the contact service to get the guest name... as a workaround... I'll try and let you know...
This should work but - I don't know why - it hangs without any result... maybe you could give it a try ?
var testEvents = calendar[0].getEvents(today, endDate);
Logger.log(testEvents[0].getTitle());
var guests = testEvents[0].getGuestList();
var guestmail = guests[0].getEmail();
Logger.log(guestmail);
var contact = ContactsApp.getContact(guestmail);
var name = contact.getFullName();
Logger.log(guestmail+' '+name);

ContactsApp is tricky, it can only search in Contacts of user running script, not in global one. In administrator account still havn't access to global contact list.

Related

How do I get my google calendar event's ID into the right format for the Calendar API to read in my script?

I'm trying to write a script that will do both: 1) update an existing event's dates and title on my Google calendar, based on the dates provided in my sheet AND 2) send the updated dates by email to the event's guests (so the event on their calendars is updated).
I was able to successfully update my event's dates and title using CalendarApp.getEventById(eventId). However, I'd really like the event notifications to resend to each guest when the dates of the event have updated. This doesn't seem possible to do using CalendarApp (if it's possible, please tell me how!). After struggling with this in this question, I'm now trying to use Calendar.Events.patch to both update the event and send the update to all the event's guests.
The problem I keep encountering is that the eventId, as logged in my sheet by my createEvent script, is in a format ending in "#google.com." This format is read just fine by CalendarApp, but cannot be read by Calendar.Events.patch. I've tried encoding it to base64, since that seeems to be the format looked for by Calendar.Events.patch, but I think I'm still missing something.
When I run the code below, the error returns "API call to calendar.events.get failed with error: Not Found."
function updateEvent(calendarId, eventId, email) {
var vSS = SpreadsheetApp.getActiveSpreadsheet();
var vS = vSS.getActiveSheet();
var eventId = vS.getRange("R2").getValue(); //R2 is the cell where my eventId is logged
//My attempt to encode my eventId to base64
var base64data = eventId;
var encoded = Utilities.base64Encode(base64data,Utilities.Charset.UTF_8);
var vEventName = vS.getRange("M3").getValue();
var newstartTime = vS.getRange("M5").getValue();
var newendTime = vS.getRange("M6").getValue();
var event = Calendar.Events.get('example#gmail.com', encoded);
if(event.attendees) {
event.attendees.push({
email: email
});
} else {
event.attendees = new Array({email: email});
}
event = Calendar.Events.patch(vEventName, encoded, {
start: newstartTime,
end: newendTime,
sendUpdates: "all"});
}
I suspect the encoded eventId is off a few characters or something, since that seems to be the case when I run the #google.com eventId through this encoding tool. I just don't know enough to fix it.
Please understand that I'm extremely new to writing scripts and I've already been struggling with this issue for well over a week. I think I learned a lot after the last question I posted, since now I have a better understanding of my exact problem, but I still don't know the fix. I'm trying to teach myself how to do this by reading the questions on this website, reading Google's information (which I unfortunately largely don't understand), and watching YouTube videos. If I'm asking too much of the script, please let me know.
You want to retrieve an event using event ID.
You want to update an event and send an email to users.
You want to modify the event name, start and end time of the event.
eventId is 1c0tqtn56c1tdo1i0fus66f53g#google.com which is a text value.
vEventName is Ethiopia Limu which is a text value.
newstartTime is 6/10/2019 which is a date object.
newendTime is 7/30/2019 which is a date object.
If my understanding is correct, how about this modification?
Modification points:
In your script, it seems that the scripts for retrieving the event and updating the event are different. So in this modification, there were separated.
You can see the event at the log, when the script is run.
The event is updated.
About the event ID, you can use 1c0tqtn56c1tdo1i0fus66f53g of 1c0tqtn56c1tdo1i0fus66f53g#google.com as the event ID.
When these are reflected to your script, it becomes as follows.
Modified script:
function updateEvent(calendarId, eventId, email) {
var vSS = SpreadsheetApp.getActiveSpreadsheet();
var vS = vSS.getActiveSheet();
var eventId = vS.getRange("R2").getValue();
var vEventName = vS.getRange("M3").getValue();
var newstartTime = vS.getRange("M5").getValue();
var newendTime = vS.getRange("M6").getValue();
var eid = eventId.split("#")[0]; // Added
// Retrieve event
var event = Calendar.Events.get(calendarId, eid);
if(event.attendees) {
event.attendees.push({
email: email
});
} else {
event.attendees = new Array({email: email});
}
Logger.log(event)
// Update event
var resource = {
start: {dateTime: newstartTime.toISOString()},
end: {dateTime: newendTime.toISOString()},
summary: vEventName,
};
Calendar.Events.patch(resource, calendarId, eid, {sendUpdates: "all"})
}
Note:
If an error related to date and time occurs when the event is updated, please confirm whether newstartTime and newendTime are the date object, respectively.
Reference:
Events: patch

Error Cannot convert Array to (class)[] in making a recurring calendar event with Google Apps Script

I am trying to create a recurring event in a Google Calendar but I keep getting the following error: Cannot convert Array to (class)[]
The problem lies in that I am trying to grab data from a cell to fill in the class. The code is the following:
var recur4 = CalendarApp.newRecurrence().addWeeklyRule().onlyOnWeeks([rep]);
var ne4 = c.createAllDayEventSeries(title, start, recur4, options);
Now, the variable rep is equal to cell H2 which has the following text in it: 31,36
When I put Logger.log(rep); it outputs 31,36 so there is no problem there either.
When I take out rep and put in 31,36 in the brackets, the script works perfectly and adds the events to the calendar, so I know that the problem is not anywhere else in the script.
I suppose that the problem has to do with the formatting in the cell, but I have no idea. Any help would be appreciated.
UPDATE
OK so based on the comment below, I changed the script to the following:
var sp = rep.split(",");
for(var i=0; i<sp.length; i++) { sp[i] = +sp[i]; }
var recur4 = CalendarApp.newRecurrence().addWeeklyRule().onlyOnWeeks(sp);
var ne4 = c.createAllDayEventSeries(title, start, recur4, options);
This got rid of the error, BUT now it is adding events every Friday. In the debugger, it now shows that the array is an integer array and comes out like this: [31,36] which should represent the two weeks I need, but something still does not work and the recur4 remains as undefined instead of an object.
UPDATE
Based on the comments that people gave below, the final script that worked fine was the following:
var recur4 = CalendarApp.newRecurrence().addYearlyRule().onlyOnWeeks(rep.split(",")).onlyOnWeekday(CalendarApp.Weekday.FRIDAY);
var ne4 = c.createEventSeries(title, start, stop, recur4, options);
The issue you have with your EventRecurrence specification is that you are specifying that this event should repeat weekly, but then use a restriction that is incompatible with a weekly restriction.
If you describe your condition with words, note that you cannot avoid saying "year". This is a strong indication that perhaps your recurrence period is incorrect.
E.g. "repeat this event every week, on weeks 31 and 36 of the year" vs. "repeat this event every year, on weeks 31 and 36"
Indeed, changing your restriction from weekly to yearly results in a valid RecurrenceRule:
var recur = CalendarApp.newRecurrence()
.addYearlyRule()
.onlyOnWeeks(rep.split(",").map(
function (week) {
return parseInt(week, 10);
})
);
References:
onlyOnWeeks
addYearlyRule
PS: the EventRecurrence and RecurrenceRule classes are pretty much interchangeable.

Google Script to Submit Form to Calendar Event

School teacher using my personal Google account to create forms and publish calendars to my class web site.
Trying to make it fast and easy as possible for kids (with no access to Google Apps) to schedule make up tests using this form.
A quick and dirty victory would be to have their form submission added to my calendar as an all-day event with the details in the description field. I could then review and edit the event to the specific time requested (I have only certain time options offered on the form as a drop-down selection item.)
A beautiful and elegant solution would be to have the script write the event on the day and time indicated on the drop-down, but I think that would require sorcery....
The form writes its responses to the spreadsheet fine and email notification works too, but can't get the calendar event creation to happen.
Will keep trying to find/learn the necessary code but would greatly appreciate a kick in the right direction.
Cheers,
Here is a "sorcery gift" since you're a teacher (so am I) and not a programmer (neither am I) that hopefully does exactly what you need.
EDIT : I added the submission date/time in description
function createCalEvent(e) {
Logger.log(e);
// this will return something like this :
/*
{values=[11/9/2014 22:30:00, serge, test descr, 11/7/2014, Before school | 7:30],
namedValues={Your Full Name=[serge], Work to Make Up=[test descr], Date You Will Make Up Assignment=[11/7/2014],
Makeup Time=[Before school | 7:30], Timestamp=[11/9/2014 22:30:00]}, range=Range, source=Spreadsheet, authMode=FULL}
*/
var cal = CalendarApp.getCalendarById("h22nevo15tm0nojb6ul4hu7ft8#group.calendar.google.com");// replace with the right calendar ID, this one is for test (and is public)
var name = e.namedValues["Your Full Name"][0];
var descr = e.namedValues["Work to Make Up"][0];
var submitTime = e.namedValues["Timestamp"][0];
var date = e.namedValues["Date You Will Make Up Assignment"][0].split('/');
var time = e.namedValues["Makeup Time"][0].split('|')[1].split(':');
Logger.log(name+' '+descr+' '+date+' '+time); // this will return serge test descr 11,7,2014 7,30
var startTime = new Date(date[2],date[0]-1,date[1]);
startTime.setHours(time[0],time[1],0,0);
endTime = new Date(startTime.getTime()+3600000); //assuming event is 1 hour long
Logger.log('start='+startTime+' end='+endTime);
cal.createEvent('name = '+name, startTime, endTime, {'description':descr+' (subimitted on '+submitTime+')'});
}
You will have to set up a trigger (on form submit) to trigger that function when a form is submitted.
IMPORTANT NOTE : don't try this code from the script editor without sending a form, it won't work !!! (e will be undefined, obviously)

Inviting guests to a "Quick Add" Google Calendar event

I am trying to improve the functionality of the "Quick Add" feature in Google Calendar. Quick Add is the feature that is normally accessed by going to Google Calendar and clicking the down arrow next to the red "Create" button (see image: http://s2.postimg.org/95zxshivt/calendar_screenshot.png).
The functionality I am trying to achieve is to allow the user to invite guests to the newly created Calendar event using keywords in what they type in the Quick Add box. For example, if the user uses the Quick Add box to add an event by entering the text Eat pizza tomorrow at 3pm with michelle#gmail.com and john#gmail.com, Google Calendar adds a new event with the title Eat pizza with michelle#gmail.com and john#gmail.com at 3pm the next day, like it is supposed to. I want to go a step further by having Google also send out two Calendar invites to the newly created event: one for michelle#gmail.com and the other to john#gmail.com.
I appreciate your advice on this topic. I am trying to understand what the best approach is:
Use a trigger with Google Apps Script to catch when the user has added a Calendar event. The trigger will access the title of the event, pick out any e-mail addresses present in the title, and send an invitation to the newly created event to each of those e-mail addresses.
Use a Chrome extension to have the user enter the string that they normally would type into the Quick Add box by clicking on the extension's icon in the Chrome browser. The extension would pick the e-mail addresses out of what the user types in, use createEventFromDescription(description) on the user's input to create the event, and then send an invitation to the newly created event to each of those e-mail addresses.
Please let me know what you think. I would greatly appreciate your ideas.
Lucy
As you probably know, there is not trigger source linked to the creation of an event from the Calendar Ui.
You have indeed 2 possibilities :
encode the event using a dedicated Ui (a chrome extension or a standalone webapp) that would take care of sending the invitations but that would probably not meet the initial requirement you described as "expanding the capabilities os the quickAdd features"
Find a way to detect an event creation and automatically send invitations from its content.
This last possibility is perfectly doable using a timer trigger that monitors your calendar and detects any new event (by comparing a list stored somewhere to the actual calendar content).
I have made such an app for a different purpose and it works nicely but there are a few difficulties you should be aware of.
When storing the events in scriptProperties (it's probably the best place to go) you have a limited amount of storage size available so you must know how much event you will be able to handle.
Any change in an event like adding a detail or rectifying a typo will re-trigger the invitation process and send the invitation again. Although this can probably be avoided but it would be quite complex.
When the script runs right after an event end, the comparison detects an change because one event is missing (from the script pov) so it could send a mail to cancel the event (if you had chosen to implement that functionality of course but I guess it's a "must have"). It might be a bit tricky to handle that situation... (compare event end time to actual time when the trigger fires the script, could be a matter of milliseconds ;-).
Apart from these difficulties, the general idea is as follow :
create a timer trigger to run every hour or so
store every event in this calendar in script Properties (or eventually in a spreadsheet) starting from the present date and ending in a few days (not too far ahead because it wouldn't make sense to send invites for an event happening next year)
compare the list with the calendar content
grab every "new" events and extract email address from the description (using regex for example or string manipulation)
send the invitations (that's the easy part)
This workflow works but it might be a bit fragile in the comparison and in the email detection.
EDIT
Since this was an interesting subject (IMHO) and that I thought I could use efficiently (now that I switched to english in my calendar UI ;-D) I wrote a code to achieve it...
I embedded the code in a spreadsheet to simplify the processsing and the storage of the events in the many calendars I own.
This spreadsheet is viewable here and if you make a copy of it you'll be able to run the code.
I setup a timer trigger that runs the autoCheckAllCal function every hour and it seems to work without any issue.
Tell me what you think.
The full code is reproduced below, it gets data from the calendar, checks if the event has guests and if not it checks the title for any valid email address (one or more) and sends the invitations automatically.
I used a regex to extract emails from the title string (this regex was borrowed from an answer on SO since I'm not good enough at this !)
note : setup an onOpen trigger for myOnOpen (because of global var declaration using SS service)
// 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 autoTest", functionName: "autoCheckAllCals"},
{name: "delete created sheets", functionName: "delsheets"}
];
ss.addMenu("Tracking utilities",menuEntries);//
}
function autoCheckAllCals(){
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 = []
var title = event.getTitle();
if(title.indexOf('#')==-1){return email};
email = title.match(/([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4})/g);
Logger.log('email var = '+email);
return email;
}
function delsheets(){
var numbofsheet = ss.getNumSheets();// check how many sheets in the spreadsheet
for (var pa=numbofsheet-1;pa>0;pa--){
ss.setActiveSheet(ss.getSheets()[pa]);
if(ss.getSheets()[pa].getSheetName()!='calNames'){
ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(400);
}
}
SpreadsheetApp.flush();
}
// 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

why isn't google apps script sending invitations

The Google Apps script ran in a spreadsheet below and everything worked fine except sending the invites. Using sendInvites:true the event is created in the calendar and the guests are added but no email is sent. I have tried it without using the var advancedArgs and same results.
if (eventImported != EVENT_IMPORTED && title != "") { // Prevents importing duplicates
var cal = CalendarApp.openByName('calendarname');
var advancedArgs = {description: details, location: cust, guests:guestlist, sendInvites:true};
cal.createEvent("10% Complete-->"+title, startDate, endDate, {description: details, location: cust, guests:guestlist, sendInvites:true});
sheet.getRange(startcolumn + i, 9).setValue(EVENT_IMPORTED);
The error must be somewhere else, I tested your code in this simplified version and I received the invitation as expected. (I use this option a lot in many scripts without any issue)
Could you show how you get your guest list ? is it a comma separated email list as specified in the documentation ?
function testcal(){
var cal = CalendarApp.getDefaultCalendar()
var advancedArgs = {description: 'details', location: 'here', guests:'serge#xxx.com', sendInvites:true};// change the email adress to a valid one that you have access to (but not your email adress of course !
var startDate = new Date();// now
var endDate = new Date(startDate.setHours(10));// at 10 AM, change this according to time of the day when you (eventually) test it
cal.createEvent("test to delete", startDate, endDate, advancedArgs);
}
I suspect you may be being rate limited somewhere. I had a similar problem and sending emails would work sporadically. I was polling a group of users calendars and when I found enough available at a certain time I would send the invitation to all.
In frustration I added:
Utilities.sleep(30000);
just before I create the event and it works reliably now. You can probably get away with less time, but mine runs on trigger at 2am so I don't care.
I found out that no event invitation is sent to my own email address (although the event is added to my calendar). But event invitations are correctly sent to other guests.
Try Out:
var advancedArgs = {description: details, location: cust,
guests:guestlist, sendInvites:"TRUE"};