Google Apps Script: Calendar Service: Find first event in CalendarEventSeries - google-apps-script

I'd like to calculate the age of a person whose birthday exists as event series within my calendar. To do this I need to know the first event within this series and that's the question: how to get the first event of a series from an actual event?
Thanks
Ronny

The other answer doesn't actually answer the initial request, the CalendarApp has no method to get the start date of a recurring event.
You should use the advanced Calendar API (must be enabled manually, see below and follow instructions)
Then use the advanced API to get the information you want, (the auto complete feature works on these methods too so you can easily see what is available)
Test code below, note that event ID is different for the advanced Calendar API, you have to remove the part after '#'.
function createTestEvents() {
var recurrence = CalendarApp.newRecurrence().addWeeklyRule().times(10);
var testEvent = CalendarApp.getDefaultCalendar().createEventSeries('test event serie', new Date('2016/05/10'), new Date(new Date('2016/05/10').getTime()+12*3600000), recurrence);
var id = testEvent.getId();
Logger.log('Event Series ID: ' + id);
viewTestEvent(id)
}
function viewTestEvent(id){
var event= CalendarApp.getDefaultCalendar().getEventSeriesById(id);
var calId = CalendarApp.getDefaultCalendar().getId();
Logger.log('event title = '+event.getTitle());
var AdvanncedId = id.substring(0,id.indexOf('#'));
Logger.log('AdvanncedId = '+AdvanncedId);
var testEvent = Calendar.Events.get(calId, AdvanncedId);
Logger.log('testEvent start = '+ testEvent.start);
return testEvent;
}
function test(){ // a few examples of what you can retrieve...
var event = viewTestEvent('59buf7nq6nr6qo79bh14kmsr6g#google.com');
Logger.log('\n\nstart = '+event.start);
Logger.log('\n\ncreated on = '+event.created);
Logger.log('\n\nend on = '+event.end);
Logger.log('\n\nrecurrence = '+event.recurrence);
}

You need to use the startDate parameter to get the date of the first event in the series (only the day is used; the time is ignored).
var eventSeries = CalendarApp.getDefaultCalendar().createAllDayEventSeries('No Meetings',
new Date('January 2, 2013 03:00:00 PM EST'),
CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekday(CalendarApp.Weekday.WEDNESDAY)
.until(new Date('January 1, 2014')));
Logger.log('Event Series ID: ' + eventSeries.getId());
You can also get the event series with the given ID using getEventSeriesById(iCalId).
If the ID given is for a single CalendarEvent, then a CalendarEventSeries will be returned with a single event in the series. Note that if the event series belongs to a calendar other than the default calendar, this method must be called from that Calendar; calling CalendarApp.getEventSeriesById(id) directly will only return an event series that exists in the default calendar.
Hope this helps!

Related

Modify a Google Calendar recurrence in Apps Script

I'm trying to create a script that, given a date, will change the end date of all my recurrent events this week to that date. Unfortunately, I can't find a way to update a recurrence info.
First, I iterate all events in the week. Then, thanks to the API, I can get the recurrence info of every event:
var eventId = event.getId().split("#")[0];
var eventFromAPI = Calendar.Events.get(ID_CALENDARIO_MENUS, eventId);
var cadenaRecurrencia = eventFromAPI["recurrence"];
witch then I use to create a new recurrence to overwrite the existing one in the event.
var recurrencia = CalendarApp.newRecurrence().addWeeklyRule().onlyOnWeekdays(arrayWeekdays).until(fecha);
But when I try to set the new recurrence, it asks me for a start date that should be the original, and I can't seem to retrieve that data:
var serie = calendario_menus.getEventSeriesById(eventoId);
serie.setRecurrence(recurrencia, date);
Is there a way to access an event's recurrence, modify it so it changes for all the events that use the recurrence and update it?
Thanks for your help.

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

check if event exists before adding it from google sheet to calendar

I've got a script that updates a calendar from a sheet.
Is there a way of getting the eventID of an event i would add to the calendar if it didn't exist ?
what would be the ID of the event to be created with (title, start, stop)
I can then check it against the eventIDs of existing events and add , if not already there.
i think this would be quicker than checking existing events for matching all properties before either adding the new one , or just moving on
I don't think that the IDs work the way you seem to think they do (as some sort of hash of the information inside them). Can you check the date you want for the title you want? I think that would be enough.
this is a script to get you started, it finds the next occurence of "Sample Meeting" in the next 20 days. You can easily narrow the scope to a single day and then add an "else" that creates the new meeting.
function insertItem() {
var fromDate = new Date(); //This is Today
var toDate = new Date();
toDate.setDate(toDate.getDate()+20);
Logger.log("From "+fromDate+" to "+toDate);
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(fromDate, toDate);
for(var i=0; i<events.length;i++)
{
var ev = events[i];
var title = calendar.getEventSeriesById(ev.getId()).getTitle();
if (title.indexOf("Sample Meeting")>-1){
var start = ev.getStartTime();
Logger.log("Found Team Meeting");
var id = ev.getId();
var date = ev.getStartTime();
var desc = ev.getDescription();
return;
}
}
}
It can be done, but its going to take a bit of work.
Event ids are auto-generated by default. However, you can generate custom ids for an event as long as they conform to Google's format requirements. So, you'll have to manage the generation of these event ids yourself.
You will have to ensure that the id is unique, so you might want to base it on a combination of inputs related to the event.
Once you have some way of generating a unique id, you can use it to fetch an event directly by id, but you have to use the Advanced Calendar Service (the built-in service does not allow lookup by event id, but it does allow lookup by iCalUID).

Type error getting Calendar event dates in Apps Script: 'TypeError when attempting "getStartTime()"'

I'm coding a script to modify select Google Calendar events by setting their start & end date/times to today. However, I'm stuck due to a type error every time I attempt to get the date or time of a calendar event - such as by using "event.getTime()", which results in "TypeError: Cannot find function getStartTime in object" (see line 19 of my sample code).
I have enabled both the Calendar API and the Google Apps API, and have authorized the script to modify my calendar.
My code to select and retrieve the relevant calendar events works fine. Based on the error text, however, I'm apparently not getting the events as objects, and I can't pinpoint what I need to correct. I've spent the better part of 2-3 days scouring Stack Overflow (such as this and this post), Apps Script documentation, API references, and many other relevant resources for solutions or examples, and attempting all variations of "get" that I can find, but to no avail.
I'm totally new to Apps Script, so any help will be greatly appreciated.
function FloatEvents() {
var calName = "AAAAAAA"; //The name of the calendar to modify
var calID = CalendarApp.getCalendarsByName(calName)[0].getId();
var fromDate = new Date(Date.now() - 7*1000*3600*24); //Start of the time range with events to be handled
var untilDate = new Date(Date.now() + 1*1000*3600*24); //End of the time range with events to be handled
var optionalArgs = {
timeMin: fromDate.toISOString(),
timeMax: untilDate.toISOString(),
showDeleted: false,
singleEvents: true,
orderBy: 'startTime'
};
var service = Calendar.Events;
var response = Calendar.Events.list(calID, optionalArgs);
var events = response.items;
// ----- Loop thru period's events -----
for (i = 0; i < events.length; i++) {
Logger.log(events[i].getStartTime()); // <=== THIS RESULTS IN A "TypeError: Cannot find function getStartTime in object" ERROR
// ----- Process event -----
// Event update code goes here
// Will work on this once I solve the dates problem
}
}
Although you are getting the calendar ID through the CalendarApp, you are using Calendar API to retrieve Calendar Events, which returns an array of events (each one is a JSON object). To get the start and end time of each event, you have to access to their start and end properties in your loop:
for (i = 0; i < events.length; i++) {
var startTime = events[i].start.dateTime;
var endTime = events[i].end.dateTime;
console.log(startTime);
console.log(endTime);
}
You can try the API to check what it is going to retrieve before start coding so you know the structure of the data you are going to work with.
However, if you want to use CalendarApp service instead of the Calendar API, you would have to call getEvents function, which returns a CalendarEvent array. These objects do have the getStartTime function.

Google script google calendar TypeError: Cannot call method "createEvent" of null

I am trying to follow the examples here in google script calendar. I didn't change the code except for the calendarID thing. The code is exactly the same as the example shows:
function createEvent(calendarId) {
var cal = CalendarApp.getCalendarById(calendarId);
var title = 'Script Demo Event';
var start = new Date("April 1, 2012 08:00:00 PDT");
var end = new Date("April 1, 2012 10:00:00 PDT");
var desc = 'Created using Google Apps Script';
var loc = 'Script Center';
var event = cal.createEvent(title, start, end, {
description : desc,
location : loc
});
};
I am not sure if I need to change calendarId to my 'xxxxx#gmail.com'. But when i run these code,the error is TypeError: Cannot call method "createEvent" of null. (line 15, file "Code")
What is the problem ?
The error message is telling you that there is no Calendar with this ID, the usual form of a calendar ID for a non domain user is something like h22xxxxxxxjb6ul4hu7ft8#group.calendar.google.com, and for a domain : domain.xxx_se8nmkl1qsqxxxxxxxxx28ufs#group.calendar.google.com.
Have you checked that the ID you entered is valid ?
You can also test the same script using getCalendarsByName('calendarName') which will return an array of all the calendars having this name in your calendars, in this case you'll have to generally pick the first one using getCalendarsByName('calendarName')[0].
You can also use your default calendar using getDefaultCalendar(), this is the one attached to your gmail address.
All this is pretty well illustrated in the documentation.
This small code will allow you to check the IDs of all the calendars you own or subscribed to.
function testCals(){
var cals = CalendarApp.getAllCalendars();
for(var n in cals){
Logger.log(' calendar ID = '+cals[n].getId()+'\nName = '+cals[n].getName()+'\n')
}
}
The event in 2012 is the default code used by google as an example