Looping through a list of Google Calendar Users - javascript

I have a list of Google Email users in a google sheet(named Master, column E). Each user also has a blank sheet named after that email address (User#Whatever.com).
What I'm aiming to do it go through the user list, retrieve the calendar entries for today for each user, and enter them into their relevant sheet. So far I have the following code, but it's returning
TypeError: Cannot call method "getEventsForDay" of null. (line 15,
file "Calendar Update")
Code is below:
var employeeDataRange = SpreadsheetApp.getActiveSpreadsheet().getRange("Master!E2:E");
var employeeObjects = employeeDataRange.getValues();
for (var j=0; j<employeeObjects.length; j++) {
var cal = CalendarApp.getCalendarById(employeeObjects[j]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(employeeObjects[j])
var today = new Date();
var events = CalendarApp.getCalendarById(cal).getEventsForDay(today);
for (var i=0;i<events.length;i++) {
var details=[[events[i].getTitle(), events[i].getStartTime(), events[i].getEndTime(), events[i].getAllTagKeys()]];
var row=i+1;
var range=sheet.getRange(row,1,1,4);
range.setValues(details);
}
}
}
Cheers,
Dan

Are you sure that you have all permissions to see those calendars and their events?
Moreover, you have this row
var cal = CalendarApp.getCalendarById(employeeObjects[j]);
where employeeObjects[j] is the calendar id and cal is the relative calendar.
Two rows after you have
var events = CalendarApp.getCalendarById(cal).getEventsForDay(today);
but cal is a calendar, not its id. Why you don't use cal.getEventsForDay(today)?

I Figured it out:
var calendar = SpreadsheetApp.getActiveSpreadsheet().getRange("Master!E2:E");
var employeeObjects = calendar.getValues();
for (var j=0; j<employeeObjects.length; j++) {
var cal = CalendarApp.getCalendarById(employeeObjects[j]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(employeeObjects[j])
var today = new Date();
var events = CalendarApp.getCalendarById(employeeObjects[j]).getEventsForDay(today);
for (var i=0;i<events.length;i++) {
var details=[[events[i].getTitle(), events[i].getStartTime(), events[i].getEndTime(), events[i].getAllTagKeys()]];
var row=i+1;
var range=sheet.getRange(row,1,1,4);
range.setValues(details);
}
}
}

Related

Google Apps Script trigger to create Google Calendar events is failing

My Google Apps Script works with the "On edit" trigger with no issues.
However, when I try to put a time based daily trigger it gets a 100% error rate.
Can someone help me understand why this may be happening? The App Script code is below.
function schedule_shifts() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange("D1").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
var signups = spreadsheet.getRange("A3:C19").getValues();
for (x=0; x<signups.length; x++) {
var shift = signups[x]
var startTime = shift[0];
var endTime = shift[1];
var name = shift[2];
eventCal.createEvent(name, startTime, endTime)
}
}
'''
Try it this way
function schedule_shifts() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange("D1").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
var signups = spreadsheet.getRange("A3:C19").getValues();
for (x=0; x<signups.length; x++) {
var shift = signups[x]
var startTime = new Date(shift[0]);
var endTime = new Date(shift[1]);
var name = shift[2];
eventCal.createEvent(name, startTime, endTime)
}
}
Be more specific about what is wrong

Google Form creates Google Slides from template Script

I have a script that on Form submit takes the data from the spreadsheet and creates a copy of a template and populates the google docs. I am trying to accomplish the same thing from google form to google slides.
First script I use for the google forms to google docs. The second script is my attempt of using the same principles and applying to google slides. My issue is I'm getting an error saying TypeError: values.forEach is not a function (line 109, file "Code") in relation to values.forEach(function(page). Any suggestions on how I could go about solving this?
Google Form to Google Sheets
function autoFillGoogleDocFromForm(e) {
var timestamp = e.values[0];
var address = e.values[1];
var image = e.values[2];
var price = e.values[3];
var summary = e.values[4];
var type = e.values[5];
var year_built = e.values[6];
var bed = e.values[7];
var bath = e.values[8];
var home_size = e.values[9];
var lot_size = e.values[10];
var occupancy = e.values[11];
var templateFile = DriveApp.getFileById("xxxxxxxx");
var templateResponseFolder = DriveApp.getFolderById("yyyyyyyyyy")
var copy = templateFile.makeCopy( address , templateResponseFolder);
var doc = DocumentApp.openById(copy.getId())
var body = doc.getBody();
body.replaceText("{{address}}", address);
body.replaceText("{{price}}", price);
body.replaceText("{{summary}}", summary);
body.replaceText("{{type}}", type);
body.replaceText("{{year_built}}", year_built);
body.replaceText("{{beds}}", bed);
body.replaceText("{{baths}}", bath);
body.replaceText("{{home_size}}", home_size);
body.replaceText("{{lot_size}}", lot_size);
body.replaceText("{{occupancy}}", occupancy);
doc.saveAndClose;
}
Google Form to Google Slides
function generateLandingPagesReport(){
var dataSpreadsheetUrl = "https://docs.google.com/spreadsheets/xxxxxxxxx/edit"
var Presentation_ID = "xxxxxxxxxxxxxx";
var ss = SpreadsheetApp.openByUrl(dataSpreadsheetUrl);
var deck = SlidesApp.openById(Presentation_ID);
var sheet = ss.getSheetByName('Sheet1');
var values = sheet.getRange('A1:J17').getValues;
var slides = deck.getSlides();
var templateSlide = slides[1];
var presLength = slides.length;
values.forEach(function(page){
values.forEach(function(page){
if(page[0]){
var landingPage = page[0];
var sessions = page[1];
var newSessions = page[2];
}
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});
presLength = slides.length;
newSlide.move(presLength);
//end our condition statement
}); //close our loop of values
//remove template slide
templateSlide.remove();
});
}
You're missing the parenthesis when calling the getValue() method.
Change this:
var values = sheet.getRange('A1:J17').getValues;
To this:
var values = sheet.getRange('A1:J17').getValues();
Not exactly what I was looking for but this uses the first Row to identify the tag inside the Google slides template like {{title}} and replaces that with the value in the second row of the sheet
function createPresentation() {
var templateFile = DriveApp.getFileById("1YVEA4WtU1Kf6nZRgHpwnKBIR-V6rRN6s9zCdOQDkWNI");
var templateResponseFolder = DriveApp.getFolderById("1k7rcfXODij4o4arSULuKZUHbit1m_X64");
var copy = templateFile.makeCopy("New" , templateResponseFolder);
var Presentation = SlidesApp.openById(copy.getId());
var values = SpreadsheetApp.getActive().getDataRange().getValues();
values.forEach(function(row) {
var templateVariable = row[0];
var templateValue = row[1];
Presentation.replaceAllText(templateVariable, templateValue);
});
}
After you have copy the template page, you work on it and try to do replace.
However, change may be pending such that newSlide = slides[2]; give undefined.
You may need to try saveAndClose() before performing any actions.
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
/* flush the presentation */
deck.saveAndClose();
deck = SlidesApp.openById(Presentation_ID);
slides = deck.getSlides();
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});

Creating a Google Calendar Event from a spreadsheet "Cannot call method "setTitle of null."

I'm working on a script that generates a calendar event from a sheet in a google spreadsheet. after debugging the code I come up with no errors but when I run the code I get this "Cannot call method 'setTitle' of null". I have been unsuccessful in my attempts in troubleshooting and do not fully understand the substance of this error. Can someone help me understand what I'm doing wrong here?
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
ss.addMenu("Calendar Actions", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var headerRows = 389; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "somewhere#farfaraway.com";
var cal = CalendarApp.getCalendarById(calId);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[11]); // column L
var title = row[9]; // Column J
var estimator = row[6];
var tstart = new Date(row[11]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[11]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[10]; // Column K
var desc = row[13]; // Column N
var id = row[0]; // Column A == eventId
// Check if event already exists, update it if it does
try {
var calev = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (estimator == "a person" && !calev) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc}).getId();
row[0] = newEvent; // Update the data array with event ID
}
else {
calev.setTitle(title);
calev.setDescription(desc);
calev.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
// Record all event IDs to spreadsheet
range.setValues(data);
}

Trouble creating events in Google Agenda from Google Sheets with a script

I created a script in a Google Sheet to create events in Google Agenda, in order to study.
My goal is to create many events like this : if i study on D0, the first event must be at D+3, then D+10 , D+30, D+60.
I get many problems :
the script write "AJOUTE" in each box of the column (which means in french that the events are added to Agenda) , even if they are not completed with dates (I want to update for each chapter when it's done, and I do not do a whole chapter the same day!)
the script doesn't care if the events are already created, so i get multiple events for the same thing...
My script is the following :
var EVENT_IMPORTED = "AJOUTE";
var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
var menuEntries = [{name: "Ajouter les événements à l'agenda", functionName: "importCalendar"}];
ss.addMenu("Agenda", menuEntries);
}
function importCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var startcolumn = 1
var numcolumns = 30
var dataRange = sheet.getRange(startcolumn, 1, numcolumns, 6)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var column = data[i];
var titre = column[1];
var DateJ3 = column[2];
var DateJ10 = column[3];
var DateJ30 = column[4];
var DateJ60 = column[5];
var eventImported = column[6];
var setupInfo = ss.getSheetByName("agenda");
var calendarName = setupInfo.getRange("A1").getValue();
if (eventImported != EVENT_IMPORTED && titre != "") {
var cal = CalendarApp.openByName(calendarName);
cal.createAllDayEvent(titre, new Date(DateJ3));
cal.createAllDayEvent(titre, new Date(DateJ10));
cal.createAllDayEvent(titre, new Date(DateJ30));
cal.createAllDayEvent(titre, new Date(DateJ60));
sheet.getRange(startcolumn + i, 7).setValue(EVENT_IMPORTED);
SpreadsheetApp.flush();
}
}
}
Thank you in advance, i'm despair, i searched for hours but found nothing to help...

sending data from a google spreadsheet program to google calender

Here is my case.
A user fills a form for event booking, the submitted form is stored in a google spreadsheet which I have synced to a google calender so that it automatically sends the data to it.
Everything is working fine apart from the fact that event times could clash.
When customers book an event centre for let's say on 13/3/2015 T 10:00AM, if another user enters the same date and time, the entry should not be accepted.
To summarise it, I want to avoid a clash of events booking. Thank you all.
here is my script.
var calendarId = "mycalenderid";
//below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed)
var startDtId = 9;
var endDtId = 10;
var titleId = 6;
var descId = 11;
var formTimeStampId = 1;
function getLatestAndSubmitToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var startDt = sheet.getRange(lr,startDtId,1,1).getValue();
//set to first hour and minute of the day.
//startDt.setHours(0);
//startDt.setMinutes(00);
var endDt = sheet.getRange(lr,endDtId,1,1).getValue();
//set endDt to last hour and minute of the day
//endDt.setHours(23);
//endDt.setMinutes(59);
var subOn = "Submitted on:"+sheet.getRange(lr,formTimeStampId,1,1).getValue();
var desc = "Added by :"+sheet.getRange(lr,descId,1,1).getValue()+"\n"+subOn;
var title = sheet.getRange(lr,titleId,1,1).getValue()+"DIA";
createEvent(calendarId,title,startDt,endDt,desc);
}
function createEvent(calendarId,title,startDt,endDt,desc) {
var cal = CalendarApp.getCalendarById(calendarId);
var start = new Date(startDt);
var end = new Date(endDt);
var loc = 'Script Center';
var event = cal.createEvent(title, start, end, {
description : desc,
location : loc
});
};
Here's a pseudocode of what you're trying to do:
function findEvent(desiredDateTime)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var range = sheet.getDataRange();
var data = range.getValues();
var lRow = range.getLastRow();
var flag = true;
var count = 0;
while (flag == true || count < lRow)
{
if (desiredDateTime >= data[count][startDtId] && desiredDateTime <= data[count][endDtId])
{
flag = false;
}
else
{
count++;
}
}
if (flag == true)
{
//Call function to add event
}else{
//Tell user desired date-time is not available.
//If you're asking for user's email address,
//simplest approach would be to send an email.
}
}
You might have to modify other bits and pieces of your code as well to accommodate this but it shouldn't be too hard. Hope this provides you with a certain direction to follow through.

Categories

Resources