Calendar script adding guests but not sending an invite - google-apps-script

I have a prototype script that is designed to add a guest to a calendar event. It adds them to the event just fine, but it does not trigger an invite. Could someone point me in the right direction to what's missing?
function addToEvent() {
var guest = "you#gmail.com";
var calendar = 'pbekisz#keuka.edu';
var event = "33l5k7p5qocdprt5j2c9nhbhl8";
var cal = CalendarApp.getCalendarById(calendar);
var theEvent = cal.getEventSeriesById(event);
theEvent.addGuest(guest);
}
addToEvent();

The CalendarApp documentation indicates that invitations can be sent when the event is created. Because the addGuest method does not include any indication as to how one might send the invitation, it appears that this functionality is currently limited to the time of event creation.
As a work around, you can continue with your prototype, and email your new guest(s) that they have been invited and that it should be appearing on their calendar. Alternatively, you could create a new event with your new guest(s) and send the invitation, then add the existing guests with their statuses from your original event, and then remove the original event.
Edit
As I was looking in to this further, I came across an old thread on google-apps-scripts-issues where they found the advanced Calendar API service could be used to achieve what you are trying to accomplish:
function sendInvite(calendarId, eventId, email) {
var event = Calendar.Events.get(calendarId, eventId);
event.attendees.push({
email: email
});
event = Calendar.Events.patch(event, calendarId, eventId, {
sendNotifications: true
});
}

Related

Creating calendar event in sheets using Google App Script and want to add attendees

I'm trying to create calendar events in sheets using Google App Script (I'm very new to this). The sheet contains details of the event (date, time, event title, and guest list) as well as the calendar ID (this is a training calendar). I want to make it simple for the end-user to fill in the information on the sheet, click 'schedule now' and the script run and send the events out to all email addresses mentioned in the guest list.
Here is an example of the sheet:
Here is a copy of the code (I found this on the Google Developer website and tried to adapt it to add guests but haven't been able to get it working and really not sure where to go with this. Ideally, I'd like the guest list to come from the sheet and not be written into the code as an option.
function scheduleTraining() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange("C3").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
Logger.log(eventCal)
var signups = spreadsheet.getRange("A5:C20").getValues();
for (x=0; x<signups.length; x++) {
var shift = signups[x];
var startTime = shift[0]
var endTime = shift[1]
var title = shift[2]
eventCal.createEvent(title, startTime, endTime, {
location: 'remote',
description: 'snacks provided',
})
}
}
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Schedule Training')
.addItem('Schedule Now', 'scheduleTraining')
.addToUi();
}
If anyone can help with this or has any ideas on how to do this better, I'm all ears!
Thanks!
Issues:
The dates in your spreadsheet file are strings/texts. You can verify that if you do =isDate(A7). If the latter returns FALSE then you don't have a valid date object. If you see the official documentation you need to pass date objects and not date texts.
Another remark I have is that your range is "A5:C20" but you should start from A7. Row 5 and 6 don't contain the information required, according to your screenshot.
Question based on your comment:
how I can include inviting the guests when it's run
Again according to the documentation, you can add guests using the advanced parameters options and in particular guests:
eventCal.createEvent(title, startTime, endTime, {
location: 'remote',
description: 'snacks provided',
guests: 'test1#gmail.com,test2#gmail.com'
})
guests is a type of string that contains a comma-separated list of email addresses
that should be added as guests.

Replacement needed for eventdelete function to delete google calendar event

I want to delete selected calendar events but eventdelete function is now void in new scripts.
I have google script attached to a google spreadsheet which contains All Day event details. Collaborators use menus run the script to create or delete events in a google calendar.
The script loops through and selects the relevant events including its stored google calendar EventID and deletes or creates it in the google calendar. This all works fine.
I created a new google user account, new Google Calendar and new spreadsheet in a new Drive.
Having copied the Script to the new Sheet adjusting the CalendarID etc. it fails..
The EventDelete is now a Void function The error message is TypeError: CalendarApp.deleteEventSeries is not a function. Checking the list the function deleteEventSeries is now Void.
I have tested code and am able to edit description so the code is working as expected but I cannot find a function/method for deleting a google calendar event in the Calendar.
function DeleteCalendarEvents() {
var CalID = "myUserName#gmail.com"
var cal =CalendarApp.getCalendarById(CalID);
// I have removed code which loops each row in a google spreadsheet
// and selects events marked delete grabbing its stored eventID.
{
var EventID = ("The event ID eg scrambledLettersNumbers#google.com");
var event = cal.getEventSeriesById(EventID);
CalendarApp.deleteEventSeries();
}
}
I think you are confusing some fundamentals of OOP.
Is normal that your code is failing because the class CalendarApp has no function called deleteEventSeries(). You could try to find in the reference for the class.
What you want to delete is actually the object that you have retrieved by invoking the method getEventSeriesById in the Calendar object which type is CalendarEventSeries.
So to delete that Event series you will need to indeed call the method deleteEventSeries() but you need to use CalendarEventSeries object not CalendarApp.
function DeleteCalendarEvents() {
var CalID = "myUserName#gmail.com"
var cal =CalendarApp.getCalendarById(CalID);
var eventSeriesID = "<Id of the event Series>";
var eventSeries = cal.getEventSeriesById(eventSeriesID);
eventSeries.deleteEventSeries();
}
The functions are not deprecated as you have suggest in the comments. The returning type being void just means that the function will not return any variable which make sense because you have just deleted the event.
var a = eventSeries.deleteEventSeries();
>>> a == null // True

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

How can I check the availability of an email id in google calender to be shown in google form

I am quite new to google app scripting and looking for best suggestions and lookouts,
I have made a form that creates the meeting event in gogole app script, and I need to add the possibility of checking the availability of any email id I am inviting to the meeting.
The code for creating a meeting invite.
function CreateEvent_( NamedValues )
{
var calendar = CalendarApp.getDefaultCalendar();
var cEvent1 = calendar.createEvent(NamedValues.Subject_Title, new Date(NamedValues.Start_date_time_1), new Date(NamedValues.End_date_time_1), {description: NamedValues.Description_Competency_1+NamedValues.Interview_1_Type, location: NamedValues.Location_1[0], guests: guestList1, sendInvites: true});
}
function OnFormSubmit(e)
{
Logger.log(e.namedValues);
CreateEvent_(e.namedValues );
}
function updateSheet()
{
//code to update sheet
}
How can I include a section where we can check the availablity of any email id we are including in the meeting
Thanks in advance
I never used it but if I read the documentation on Advanced Calendar Service and particularly the Freebusy page it seems that you can get the availability of a group or a single user.
If you come to a working solution I would be happy to see it.
Edit: see also this post with a sample code Why does the 'Free/Busy' time for Google Calendar API come back 'Undefined'?

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