יצירת הרשמה לסשנים של כנס

רמת תכנות: למתחילים
משך זמן: 5 דקות
סוג הפרויקט: אוטומציה עם תפריט בהתאמה אישית וטריגר מבוסס-אירועים

מטרות

  • להבין מה הפתרון עושה.
  • להבין מה שירותי Apps Script עושים בפתרון הזה.
  • מגדירים את הסקריפט.
  • מריצים את הסקריפט.

מידע על הפתרון הזה

יוצרים מערכת רישום לאירועים מקצה לקצה. אם יש אירוע קרוב, כמו שיחת ועידה, תוכלו להגדיר יומן חדש לפגישות של שיחות ועידה, ליצור טופס הרשמה ולשלוח למשתתפים אימיילים מותאמים אישית באימייל באופן אוטומטי.

מידע מ-Sheets שמועבר ל-Forms וליומן

איך זה עובד

בפתרון הזה נעשה שימוש בתפריט מותאם אישית ב-Google Sheets כדי להטמיע מערכת אוטומטית לרישום אירועים. הסקריפט יוצר יומן עם אירועי שיחת הוועידה הרשומים בגיליון האלקטרוני של Sheets. לאחר מכן, הסקריפט יוצר טופס עם רשימת האירועים שהמשתתפים יכולים להירשם אליהם. אחרי שהמשתתפים ממלאים את הטופס, הסקריפט מוסיף את המשתתפים לאירועים ביומן ושולח להם באימייל את מסלולי הנסיעה.

שירותי Apps Script

הפתרון הזה משתמש בשירותים הבאים:

  • גיליון אלקטרוני שירות – מספק את פרטי האירוע לשירותים האחרים.
  • שירות יומן – יוצר יומן חדש לאירוע, מוסיף אירועים ליומן ומוסיף משתתפים לאירועים שהם נרשמים אליהם.
  • שירות מאפיינים – אחסון המזהה של היומן שנוצר על ידי שירות היומן. כשמשתמש לוחץ על Set up שיחת ועידה בתפריט המותאם אישית שיחת ועידה, השירות Properties בודק אם מערכת הרישום של האירועים כבר הוגדרה על ידי בדיקת המאפיין של מזהה היומן. כך תוכלו למנוע יצירה של טפסים ויומנים כפולים.
  • שירות Forms – יצירת טופס מהמידע שבגיליון האלקטרוני שמאפשר למשתתפים להירשם לסשנים.
  • שירות סקריפט – יצירת טריגר שמופעל כשמשתתף ממלא את הטופס.
  • שירות מסמכים – קבלת פרטי אירוע לאירועים שמשתתף נרשם אליהם, והוספה של רשימה של האירועים למסמך חדש. הסקריפט מעניק למשתתף הרשאה לערוך את המסמך.
  • שירות דואר – שליחת מסמך מסלול הנסיעה באימייל למשתתפים.

דרישות מוקדמות

כדי להשתמש בדוגמה הזו, צריך לעמוד בדרישות המוקדמות הבאות:

  • חשבון Google (יכול להיות שחשבונות Google Workspace יצטרכו לקבל אישור אדמין).
  • דפדפן אינטרנט עם גישה לאינטרנט.

הגדרת הסקריפט

  1. לוחצים על הלחצן הבא כדי ליצור עותק של הגיליון האלקטרוני לדוגמה Create a sign-up for sessions in the meeting (יצירת עותק של הגיליון האלקטרוני לדוגמה). פרויקט Apps Script של הפתרון הזה מצורף לגיליון האלקטרוני.
    יצירת עותק
  2. לוחצים על Conference > הגדרת שיחות ועידה. ייתכן שתצטרכו לרענן את הדף כדי שהתפריט המותאם אישית יופיע.
  3. כשמוצגת הנחיה, מאשרים את הסקריפט. אם במסך ההסכמה ל-OAuth מוצגת האזהרה האפליקציה הזו לא מאומתת, ממשיכים לבחור באפשרות Advanced > Go to {Project Name} (unsafe) (מעבר אל {Project Name} (unsafe)).

  4. לוחצים שוב על שיחת ועידה > הגדרת שיחת ועידה.

מריצים את הסקריפט

  1. לוחצים על כלים > ניהול טופס > מעבר לטופס הפעיל.
  2. ממלאים את הטופס ושולחים אותו.
  3. נכנסים לאתר calendar.google.com.
  4. מימין, מוודאים שהתיבה שליד יומן שיחות ועידה מסומנת.
  5. נכנסים לתאריכים של האירועים שנרשמתם אליהם ומוודאים שהוסיפו אתכם כמשתתפים.

(אופציונלי) איפוס הפתרון

אם אתם רוצים לנסות את הפתרון הזה שוב, או להתאים אותו אישית כך שישתמש בפרטי האירועים שלכם, תצטרכו לאפס כמה פריטים שהוגדרו כשהרצתם את הסקריפט בפעם הראשונה. כדי לצפות בשלבים לאיפוס הפתרון, לוחצים על Reset the Solution (איפוס הפתרון):

איפוס הפתרון

שלב 1: מאפסים את מאפייני הסקריפט המאוחסנים

אם תנסו להריץ את הסקריפט יותר מפעם אחת, תופיע הודעה עם הכיתוב שיחת הוועידה שלך כבר מוגדרת. צריך לחפש את טופס ההרשמה ב-Google Drive! הסיבה לכך היא שאחרי שיומן שיחת הוועידה נוצר, מזהה היומן נשמר כמאפיין של סקריפט. כשהסקריפט רץ, הוא בודק אם המאפיין של מזהה היומן כבר קיים, ומפסיק לפעול אם הוא קיים.

כדי להסיר את המאפיין הקיים של מזהה היומן:

  1. בגיליון האלקטרוני, לוחצים על תוספים > Apps Script.
  2. בעורך Apps Script, בוחרים את resetProperties מהרשימה הנפתחת של הפונקציות ולוחצים על Run.

שלב 2: מוחקים את יומן שיחת הוועידה

בכל פעם שהסקריפט רץ, הוא יוצר יומן חדש. לא רוצים לשמור את היומן המקורי שנוצר?

  1. נכנסים לאתר calendar.google.com.
  2. ליד 'יומן שיחת ועידה', לוחצים על 'אפשרויות של יומן שיחת ועידה' > הגדרות ושיתוף.
  3. גוללים לחלק התחתון של ההגדרות ולוחצים על מחיקה.

שלב 3: מוחקים את הטריגר לשליחת טופס

הסקריפט יוצר טריגר לשליחה של טפסים בכל פעם שמריצים אותו. כדי להימנע מכמה טריגרים שגורמים לשליחת אימיילים כפולים, צריך להסיר את הטריגר המקורי. כך עושים זאת:

  1. בגיליון האלקטרוני, לוחצים על תוספים > Apps Script.
  2. בפרויקט Apps Script, לוחצים על טריגרים .
  3. לצד הטריגר, לוחצים על סמל האפשרויות הנוספות > מחיקת הטריגר.

בכל פעם שאתם מריצים את הסקריפט, הוא יוצר טופס חדש. כדי לבטל את הקישור של הטופס לגיליון האלקטרוני ולמחוק אותו, פועלים לפי השלבים הבאים:

  1. בגיליון האלקטרוני, לוחצים לחיצה ימנית על הגיליון Form responses (תשובות בטפסים) ולוחצים על Unlink form (ביטול הקישור של הטופס) > Ok (אישור).
  2. לוחצים שוב לחיצה ימנית על הגיליון Form interactions (תגובות לטופס) ולוחצים על Delete > Ok (אישור).
  3. נכנסים אל forms.google.com.
  4. לוחצים לחיצה ימנית על טופס שיחת ועידה ואז על הסרה > העברה לאשפה.

לאחר איפוס הפתרון, אפשר להוסיף נתונים משלך או להמשיך להשתמש בנתונים לדוגמה ולהריץ את הסקריפט שוב.

בדיקת הקוד

כדי לעיין בקוד Apps Script של הפתרון הזה, לוחצים על הצגת קוד המקור למטה:

הצגת קוד המקור

Code.gs

solutions/automations/event-session-signup/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/event-session-signup

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Inserts a custom menu when the spreadsheet opens.
 */
function onOpen() {
  SpreadsheetApp.getUi().createMenu('Conference')
      .addItem('Set up conference', 'setUpConference_')
      .addToUi();
}

/**
 * Uses the conference data in the spreadsheet to create
 * Google Calendar events, a Google Form, and a trigger that allows the script
 * to react to form responses.
 */
function setUpConference_() {
  let scriptProperties = PropertiesService.getScriptProperties();
  if (scriptProperties.getProperty('calId')) {
    Browser.msgBox('Your conference is already set up. Look in Google Drive for your'
                   + ' sign-up form!');
                   return;
  }
  let ss = SpreadsheetApp.getActive();
  let sheet = ss.getSheetByName('Conference Setup');
  let range = sheet.getDataRange();
  let values = range.getValues();
  setUpCalendar_(values, range);
  setUpForm_(ss, values);
  ScriptApp.newTrigger('onFormSubmit').forSpreadsheet(ss).onFormSubmit()
      .create();
}

/**
 * Creates a Google Calendar with events for each conference session in the
 * spreadsheet, then writes the event IDs to the spreadsheet for future use.
 * @param {Array<string[]>} values Cell values for the spreadsheet range.
 * @param {Range} range A spreadsheet range that contains conference data.
 */
function setUpCalendar_(values, range) {
  let cal = CalendarApp.createCalendar('Conference Calendar');
  // Start at 1 to skip the header row.
  for (let i = 1; i < values.length; i++) {
    let session = values[i];
    let title = session[0];
    let start = joinDateAndTime_(session[1], session[2]);
    let end = joinDateAndTime_(session[1], session[3]);
    let options = {location: session[4], sendInvites: true};
    let event = cal.createEvent(title, start, end, options)
        .setGuestsCanSeeGuests(false);
    session[5] = event.getId();
  }
  range.setValues(values);

  // Stores the ID for the Calendar, which is needed to retrieve events by ID.
  let scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('calId', cal.getId());
}

/**
 * Creates a single Date object from separate date and time cells.
 *
 * @param {Date} date A Date object from which to extract the date.
 * @param {Date} time A Date object from which to extract the time.
 * @return {Date} A Date object representing the combined date and time.
 */
function joinDateAndTime_(date, time) {
  date = new Date(date);
  date.setHours(time.getHours());
  date.setMinutes(time.getMinutes());
  return date;
}

/**
 * Creates a Google Form that allows respondents to select which conference
 * sessions they would like to attend, grouped by date and start time in the
 * caller's time zone.
 *
 * @param {Spreadsheet} ss The spreadsheet that contains the conference data.
 * @param {Array<String[]>} values Cell values for the spreadsheet range.
 */
function setUpForm_(ss, values) {
  // Group the sessions by date and time so that they can be passed to the form.
  let schedule = {};
  // Start at 1 to skip the header row.
  for (let i = 1; i < values.length; i++) {
    let session = values[i];
    let day = session[1].toLocaleDateString();
    let time = session[2].toLocaleTimeString();
    if (!schedule[day]) {
      schedule[day] = {};
    }
    if (!schedule[day][time]) {
      schedule[day][time] = [];
    }
    schedule[day][time].push(session[0]);
  }

  // Creates the form and adds a multiple-choice question for each timeslot.
  let form = FormApp.create('Conference Form');
  form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
  form.addTextItem().setTitle('Name').setRequired(true);
  form.addTextItem().setTitle('Email').setRequired(true);
  Object.keys(schedule).forEach(function(day) {
    let header = form.addSectionHeaderItem().setTitle('Sessions for ' + day);
    Object.keys(schedule[day]).forEach(function(time) {
      let item = form.addMultipleChoiceItem().setTitle(time + ' ' + day)
          .setChoiceValues(schedule[day][time]);
    });
  });
}

/**
 * Sends out calendar invitations and a
 * personalized Google Docs itinerary after a user responds to the form.
 *
 * @param {Object} e The event parameter for form submission to a spreadsheet;
 *     see https://developers.google.com/apps-script/understanding_events
 */
function onFormSubmit(e) {
  let user = {name: e.namedValues['Name'][0], email: e.namedValues['Email'][0]};

  // Grab the session data again so that we can match it to the user's choices.
  let response = [];
  let values = SpreadsheetApp.getActive().getSheetByName('Conference Setup')
      .getDataRange().getValues();
  for (let i = 1; i < values.length; i++) {
    let session = values[i];
    let title = session[0];
    let day = session[1].toLocaleDateString();
    let time = session[2].toLocaleTimeString();
    let timeslot = time + ' ' + day;

    // For every selection in the response, find the matching timeslot and title
    // in the spreadsheet and add the session data to the response array.
    if (e.namedValues[timeslot] && e.namedValues[timeslot] == title) {
      response.push(session);
    }
  }
  sendInvites_(user, response);
  sendDoc_(user, response);
}

/**
 * Add the user as a guest for every session he or she selected.
 * @param {object} user An object that contains the user's name and email.
 * @param {Array<String[]>} response An array of data for the user's session choices.
 */
function sendInvites_(user, response) {
  let id = ScriptProperties.getProperty('calId');
  let cal = CalendarApp.getCalendarById(id);
  for (let i = 0; i < response.length; i++) {
    cal.getEventSeriesById(response[i][5]).addGuest(user.email);
  }
}

/**
 * Creates and shares a personalized Google Doc that shows the user's itinerary.
 * @param {object} user An object that contains the user's name and email.
 * @param {Array<string[]>} response An array of data for the user's session choices.
 */
function sendDoc_(user, response) {
  let doc = DocumentApp.create('Conference Itinerary for ' + user.name)
      .addEditor(user.email);
  let body = doc.getBody();
  let table = [['Session', 'Date', 'Time', 'Location']];
  for (let i = 0; i < response.length; i++) {
    table.push([response[i][0], response[i][1].toLocaleDateString(),
      response[i][2].toLocaleTimeString(), response[i][4]]);
  }
  body.insertParagraph(0, doc.getName())
      .setHeading(DocumentApp.ParagraphHeading.HEADING1);
  table = body.appendTable(table);
  table.getRow(0).editAsText().setBold(true);
  doc.saveAndClose();

  // Emails a link to the Doc as well as a PDF copy.
  MailApp.sendEmail({
    to: user.email,
    subject: doc.getName(),
    body: 'Thanks for registering! Here\'s your itinerary: ' + doc.getUrl(),
    attachments: doc.getAs(MimeType.PDF),
  });
}

/**
 * Removes the calId script property so that the 'setUpConference_()' can be run again.
 */
function resetProperties(){
  let scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.deleteAllProperties();
}

תורמים

הדוגמה הזו מתוחזקת על ידי Google בעזרת מומחי המפתחים של Google.

השלבים הבאים