Google Script to Submit Form to Calendar Event - google-apps-script

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)

Related

Alternative to using triggers to automatically send email for each calendar event created

I am trying to automate certain parts of my workflow for scheduling clients with Google Calendar. I've successfully managed to capture new/edited/deleted events in Google Apps Script using a trigger which detects changes and Calendar.event.list to sync those changes with a spreadsheet.
I create a new row, or edit an existing one, in my spreadsheet of all the clients. What I desire to do is three days before the appointment with the client, automatically generate a custom email with all of their details, to send them as a reminder regarding the appointment.
My plan was every time a new row was created in the Spreadsheet (when a new Calendar event was created), was to make a new email trigger. That trigger would execute code to create an email, with all of the clients info.
function createEmailTrigger(event) {
var today = new Date();
today.setHours(0,0,0,0); // Don't care about time
// Create Email Trigger three days before
const sendDaysBefore = 3;
var daysBefore = new Date(event.start);
daysBefore.setDate(daysBefore.getDate() - sendDaysBefore);
var trigger = ScriptApp.newTrigger('sendEmail')
.timeBased()
.at(daysBefore)
.create();
associateEventWithTrigger(trigger.getUniqueId(), event);
return trigger.getUniqueId();
}
associateEventWithTrigger connects the trigger id with the Calendar event. sendEmail would then create a new email with all of the client's info, which came from the Calendar event. When the trigger is executed, it deletes the trigger since it won't be used again.
All of this was working fine, as I was testing one Calendar event at a time. However, once I decided to sync all of this year's Calendar events, the script very quickly threw this error:
Exception: This script has too many triggers. Triggers must be deleted from the script before more can be added.
Apparently you can only have 20 triggers per user/script. This is very inconvenient, as I was expecting to create hundreds of triggers.
Therefore, I need to rethink how to go about doing this. Any suggestions? I appreciate it.
Proposed workaround
This script is designed to be run on a time-driven trigger that runs daily.
function sendReminderEmails() {
let file = SpreadsheetApp.getActive();
let sheet = file.getSheetByName("Sheet1");
let range = sheet.getDataRange();
let values = range.getValues();
// removing headers
values.shift()
values.forEach(row => {
let name = row[0]
let email = row[1]
let date = row[2]
// Date object representing time now
let now = new Date();
// helper variables
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
// gets time to appointment in milliseconds
let timeToApp = date.getTime() - now.getTime()
if (timeToApp > 2 * day && timeToApp < 3 * day) {
MailApp.sendEmail(
email,
"Remember Your Appointment",
"Hello " + name + ",\nYou have an appointment coming up soon."
)
}
})
}
This is based on a sample spreadsheet like this:
So you would need to adapt it to your particular format.
Script walkthrough
It is based on the date object.
If your dates are stored as formatted dates in your spreadsheet, when you getValues, Apps Script will automatically pass them as Date object. Alternatively you can cast them as Date objects in Apps Script if needed.
The script starts off by getting all the values in the target sheet.
It initialized a new Date object that represents the time now.
It then goes through each row of the target sheet and gets a value for how long until the appointment.
If the value is between 2 days and 3 days, then an email is sent.
I Think you could make an script to search events every day , events that are 3 days ahead , select then and send email. So it will be just one script that will be triggeres every day, using the date trigger mode.

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

How to fill out multiple sheets everytime a Google Form is submitted

I have created a very simple Apps Script that based on the answers provided through a Google Form, makes a copy of a template (a sheet in the form answers spreadsheet) and fills it out with the entered info. This is part of the code:
function fichas() {
var formato = SpreadsheetApp.getActiveSpreadsheet();
var ficha = formato.duplicateActiveSheet();
var respuestas = SpreadsheetApp.openById('ID').getSheetByName('Form Responses');
var name = respuestas.getRange(**2**, 5);
var apellido = ficha.getRange(4, 2);
name.copyTo(apellido);
var name2 = respuestas.getRange(**2**, 6);
var apellido2 = ficha.getRange(4, 3);
name2.copyTo(apellido2);
The bold number represents the first user's information. I have set up a trigger that runs the script when the form is submitted. Now, what I don't know how to do is how to move to the next row to use the next user's info (in other words I want to automatically increase that bold number by one everytime the script runs). Is it possible? I am new to this and I am trying to learn but sometimes it is too hard!
I really appreciate your help!
Jorge
You should use a variable that is common to all users and that you increment on each form submission. There are a few possible ways to achieve that, why not try script Properties ? it is fairly simple to implement :
First initialize it with a statement like this :
ScriptProperties.setProperty('rowValue', 1);// this must happen only once, you could insert it in a small function to "initialize"
and then in your code you can retrieve it using
var rowValue = Number(ScriptProperties.getProperty('rowValue'));
increment it using rowValue++ and write it back to the storage ... remember that you can always edit this value directly in the script properties (script editor>file>project properties> project properties)
ScriptProperties.setProperty('rowValue', rowValue);
This would be perfect if you never get more than one user sending a form simultaneously.
In this case there is a risk that the script mixes values...
There is another service designed to handle this situation : the lock service
the doc gives an explicit example on how to implement it : it goes simply like this :
var lock = LockService.getPublicLock();
try {
lock.waitLock(10000);
} catch (e) {
Logger.log('Could not obtain lock after 10 seconds.');
}
do what you have to do, increment the counter... and when your done use
lock.releaseLock();
it might seem complicated but it's not ;-) and it will work flawlessly in every possible situation... just give it a try.

EventGuest getName() method not working

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.