Google Script - Create Events to Multiple Calendars - google-apps-script

I have a spreadsheet with a list of events, but need to insert them into their own respective calendars. So far I have this:
function pushCalendars() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
for (i in sheets){
if (sheets.length > 1){
var lastRow = sheets[i].getLastRow();
var range = sheets[i].getRange(3,1,lastRow,100);
var data = range.getValues();
for (i in data){
var row = data[i];
var title = row[0];
var title2 = row[1];
var date = row[2];
var desc = row[3];
var calName = ss.getSheetByName("Resorts").getRange('E3').getValue();
var cal = CalendarApp.openByName(calName);
cal.createAllDayEvent(title,date);
}
}
}
Let me know if you have any solutions!

If the calendars are owned by your user you will face no problems.
The only thing that you need to change in your code is to create the calendars that still does not exists with this piece of code:
// Creates a new calendar named "Travel Plans" with a summary and color.
var calendar = CalendarApp.createCalendar('Travel Plans', {
summary: 'A calendar to plan my travel schedule.',
color: CalendarApp.Color.BLUE
});
Logger.log('Created the calendar "%s", with the ID "%s".',
calendar.getName(), calendar.getId());
The API documentation can be found here.
If the calendars belongs to other user you will need to have administrative permissions to modify it and you need to log with OAuth plus calling the calendar API using URLFetch (Calendar API can be found here.)

I always get my calendars by id, since the calendars already exist, you could get the calendar ID from the Calendar Settings, and insert them into the script as Project Properties. Then all you need to do is load the id that matches the name.
Change these two lines:
var calName = ss.getSheetByName("Resorts").getRange('E3').getValue();
var cal = CalendarApp.openByName(calName);
To this:
var calName = ss.getSheetByName("Resorts").getRange('E3').getValue();
var calID = ScriptProperties.getProperty(calName);
var cal = CalendarApp.getCalendarByID(calID);
https://developers.google.com/apps-script/guides/properties#scriptProperties for reference on ScriptProperties.

Related

Google apps script - extract numerous Google Calendars and fields to Google Sheets

I have the following Google Sheets Apps Script to extract calendar invites to a Google Sheet, however, I am trying to make some adjustments that I am struggling to find a solution for:
function getEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var start_time = sheet.getRange("A2").getValue();
var end_time = sheet.getRange("B2").getValue();
var id_cal = sheet.getRange("P5").getValue();
var cal = CalendarApp.getCalendarById(id_cal);
var events = cal.getEvents(new Date(start_time), new Date(end_time));
for (var i = 0;i<events.length;i++){
var title = events[i].getTitle();
var start_time = events[i].getStartTime();
var end_time = events[i].getEndTime();
var des = events[i].getDescription();
var vis = events[i].getVisibility();
var guestlist = events[i].getGuestList();
sheet.getRange(i+5,1).setValue(title);
sheet.getRange(i+5,2).setValue(start_time);
sheet.getRange(i+5,3).setValue(end_time);
sheet.getRange(i+5,4).setValue(des);
sheet.getRange(i+5,5).setValue(vis);
sheet.getRange(i+5,6).setValue(guestlist);
}
Logger.log("Events have been added to the Spreadsheet");
}
How do I amend this script to:
Extract from several calendars that I have the email addresses in a range of cells (Z1:Z25) instead of just 1 calendar. I have attempted changing the range, but it only pulls the calendar from the top cell.
Include all accepted/pending attendees (including the organiser). I have attempted to add .getGuestList, but this returns 'EventGuest'
Include the calendar that event was taken from
I believe your goal is as follows.
You want to retrieve the events from multiple Calendars by the calendar IDs which are retrieved from the cells "Z1:Z25" of the Spreadsheet.
As the data, from Include all accepted/pending attendees (including the organiser)., you want to add the user's email addresses.
You want to add the calendar IDs as the additional value.
Modification points:
In your script, only one Calendar ID is used. In order to achieve your goal, it is required to retrieve the calendar IDs from the cells "Z1:Z25".
About I have attempted to add .getGuestList, but this returns 'EventGuest', the method of getGuestList() returns EventGuest object. I think that this is the reason for your issue.
In your script, setValue is used in a loop. In this case, the process cost becomes high. Ref
When these points are reflected in your script, it becomes as follows.
Modified script:
function getEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var [start_time, end_time] = sheet.getRange("A2:B2").getValues()[0];
var dates = [new Date(start_time), new Date(end_time)]; // If the cell value is date object, you can also use [start_time, end_time]
var ids = sheet.getRange("Z1:Z25").getValues().reduce((ar, [z]) => {
if (z) ar.push(z);
return ar;
}, []);
var values = ids.flatMap(id_cal => {
var cal = CalendarApp.getCalendarById(id_cal);
if (!cal) return [];
var events = cal.getEvents(...dates);
return events.map(e => {
var title = e.getTitle();
var start = e.getStartTime();
var end = e.getEndTime();
var des = e.getDescription();
var vis = e.getVisibility().toString(); // or e.getVisibility()
var guestlist = e.getGuestList().map(f => f.getEmail()).join(",");
return [id_cal, title, start, end, des, vis, guestlist];
});
});
sheet.getRange(5, 1, values.length, values[0].length).setValues(values);
Logger.log("Events have been added to the Spreadsheet");
}
When this script is run, the calendar IDs are retrieved from "Z1:Z25" of "Sheet1". And, the events are retrieved, and the values are retrieved from each event. In this case, the calendar ID, event title, start time, end time, description, visibility, and guest email addresses are put on the sheet in order.
If you want to change the order of values, please modify return [id_cal, title, start, end, des, vis, guestlist];.
If you want to change the user's email to the user's name, please modify f.getEmail() to f.getName().
Note:
This modified script is a simple modification. So, please modify this for your actual situation.
References:
map()
Class EventGuest
Try something like this:
function getEvents() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Sheet1");
var start = sh.getRange("A2").getValue();
var end = sh.getRange("B2").getValue();
const ids = [];
CalendarApp.getAllCalendars().forEach(c => ids.push(c.getId()));
ids.forEach(id => {
let cal = CalendarApp.getCalendarById(id);
let events = cal.getEvents(new Date(start), new Date(end));
for (var i = 0; i < events.length; i++) {
var title = events[i].getTitle();
var start = events[i].getStartTime();
var end = events[i].getEndTime();
var des = events[i].getDescription();
var vis = events[i].getVisibility();
var guestlist = events[i].getGuestList();
let row = sh.getLastRow() + 1
sh.getRange(sh.getLastRow() + 1, 1,1,5).setValues([[title,start,end,des,vis,guestlist]]);
}
})
Logger.log("Events have been added to the Spreadsheet");
}
I'll leave it up to you to add the additional items as this is not a venue for getting free scripts.

Can a script automatically find the next available date and time on my calendar and schedule event?

I'm looking for a script that will create a new event on my calendar using information from sheets. The script would look in column 6, find numbers over 30 (the number of days since my last meeting), then use information in column 4 (the name of my client) to create a new appointment.
I have used the script below successfully to create an event, but I want the script to automatically find the next available date and time during my working hours, instead of me manually entering the date and time. Is this possible???
function Calendar(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Priority');
var calendarId = ss.getRange("B1").getValue();
var eventCal = CalendarApp.getCalendarById('sheet ID');
var signups = ss.getRange("A3:D3").getValues();
var lr = ss.getLastRow();
var count = ss.getRange("A3:E"+lr+"").getValues();
for (x=0; x<count.length; x++) {
var shift = count[x];
var title = shift[0];
var startTime = shift [1];
var endTime = shift [2];
eventCal.createEvent(title, startTime, endTime, {location: 'Hazelwood School District'});
}
}

Google Sheets to link to Google Team Calendar using Script Editor

Hi I've been trying to experiment with google's script editor and i think that I've gotten the code right but it wont seem to work. I used the code they made in google's tutorial video with edits but it cant seem to create an event. On the executions page it says completed but no new event is showing up.
Anyway i've attached screen shots of the sheet as well as the code. Hope y'all can help thanks!
function scheduleMeetings() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange('H6').getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
var tasks = spreadsheet.getRange("G10:H100").getValue();
for (x=0; x<tasks.length; x++) {
var schedules = tasks[x];
var date = schedules[0];
var task = schedules[1];
eventCal.createAllDayEvent(task, date);
}
}
Try this:
function scheduleMeetings() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange('H6').getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
var tasks = spreadsheet.getRange("G10:H100").getValues();//you had getValue()
for (var x=0;x<tasks.length;x++) {
var schedules = tasks[x];//Select a row
var date = schedules[0];//column G
var task = schedules[1];//column H
//you may need to add var date=new Date(schedules[0]);
eventCal.createAllDayEvent(task, date);
}
}

Why can't I return a list of specific email addresses from a Calendar invite with App Script?

I'm trying to return a list of specific email addresses of all event attendees on a GSuite calendar with a script and I can only return either an ID number or a list that appears only as "EventGuest, EventGuest, EventGuest...."
Is it possible to return the email address itself? Thanks in advance for any guidance here!
This is the basic script that I'm working with:
function listCalendarAttendees(){
var calendar = CalendarApp.getCalendarById('AnyCalendarTEST#gmail.com');
var sheet = SpreadsheetApp.openById('TEST ID').getSheetByName('Bobs Calendar');
var startTime = new Date();
var endTime = new Date(startTime.getTime()+(1000*60*60*24*7));
var events = calendar.getEvents(startTime, endTime);
Logger.log('Number '+events.length);
for(var x=0;x<events.length;x++){
var event = events[x];
var messages = event.getTitle();
var eventStart = event.getStartTime();
var emails = event.getCreators().toString();
var descriptions = event.getDescription();
var guestListLength = event.getGuestList().length;
var guestListNames =event.getGuestList().toString();
sheet.appendRow([messages,eventStart,emails,descriptions,guestListLength,guestListNames]);
}
}
You want to retrieve the emails of all guests in the event.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
getGuestList() returns the object of EventGuest[]. In this case, the email can be retrieved by getEmail() from EventGuest.
When appendRow() is used in the for loop, the process cost will be high. So in this modification, setValues() is used instead.
Modified script:
When your script is modified, it becomes as follows.
From:
for(var x=0;x<events.length;x++){
var event = events[x];
var messages = event.getTitle();
var eventStart = event.getStartTime();
var emails = event.getCreators().toString();
var descriptions = event.getDescription();
var guestListLength = event.getGuestList().length;
var guestListNames =event.getGuestList().toString();
sheet.appendRow([messages,eventStart,emails,descriptions,guestListLength,guestListNames]);
}
To:
var values = []; // Added
for(var x=0;x<events.length;x++){
var event = events[x];
var messages = event.getTitle();
var eventStart = event.getStartTime();
var emails = event.getCreators().toString();
var descriptions = event.getDescription();
var guestListLength = event.getGuestList().length;
var guestListNames = event.getGuestList().map(function(e) {return e.getEmail()}).join(","); // Modified
values.push([messages,eventStart,emails,descriptions,guestListLength,guestListNames]); // Modified
}
sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values); // Added
In this modification, the emails are separated by , and it is put to a cell.
References:
getGuestList()
Class EventGuest
getEmail()
If I misunderstood your question and this was not the direction you want, I apologize.
Event Guest is an object. Here are it's methods:
getEmail()
getAdditionalGuests()
getGuestStatus()
getName()

Google Sheets to Calendar Apps Script ColorId [duplicate]

This question already has answers here:
Google Apps Script: Setting color of an event using Calendar API
(4 answers)
Closed 3 years ago.
This is my introduction to Google's script editor, I have very little knowledge on the matter. Anyway, I am trying to run a script to create events on Google Calendar with data from Google Sheets. I ended up with the code below.
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var calendar = CalendarApp.getCalendarById('ID');
var startRow = 2;
var numRows = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
var complete = "Done";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var client = row[0]; //Client
var task = row[1]; //Task
var employee = row[2] //Employee
var date = new Date(row[3]); //Start Date
var rDate = new Date(row[4]); //End Date
var addguest = row[8]; //Employee Email
var employeecolor = row[9]; //Employee Calendar Color
var eventID = row[10]; //Scheduled?
Logger.log(row)
if (eventID != complete) {
var currentCell = sheet.getRange(startRow + i, numColumns);
calendar.createAllDayEvent(employee+ " - " + client, rDate,
{description: task, colorId: employeecolor, guests: addguest, sendInvites: true
});
currentCell.setValue(complete);
}
}
}
The script creates an event and sends guests email invites but the only thing I can't get to work is the ColorID. Right now, the colorID cell in Sheets generates a number between 1-11. I've tried hex color codes and Enum EventColor properties from Google's reference but nothing seems to change the color from the default calendar color. Help. Not sure what's wrong and I am sorry if this has been answered already. Thanks for reading.
Without using Advanced Services, you cannot set the event color. You can see this on the description of the setColor method on the documentation.
To change the color of an event, insert it into the calendar with the correct color.
The object you are passing as options does not have those properties, check the documentation for available properties.
However, if you are using Advanced Services you can set the colors as explained on this answer.