สร้างปฏิทินวันหยุดของทีม

ระดับการเขียนโค้ด: ผู้เริ่มต้น
ระยะเวลา: 15 นาที
ประเภทโปรเจ็กต์: การทำงานอัตโนมัติด้วยทริกเกอร์ที่อิงตามเวลา

วัตถุประสงค์

  • ทำความเข้าใจสิ่งที่โซลูชันทำ
  • ทำความเข้าใจสิ่งที่บริการ Google Apps Script ทำภายในโซลูชัน
  • ตั้งค่าสคริปต์
  • เรียกใช้สคริปต์

เกี่ยวกับโซลูชันนี้

ปฏิทินวันหยุดที่แชร์เป็นเครื่องมือที่ยอดเยี่ยมในการช่วยให้ทีมทำงานร่วมกันได้ ทุกคนจะดูได้ทันทีว่าใครไม่อยู่ที่ออฟฟิศ โซลูชันนี้ช่วยให้คุณ ดูได้ว่าเพื่อนร่วมงานลาพักร้อนเมื่อใดโดยไม่ต้องป้อนข้อมูลด้วยตนเอง

ตัวอย่างปฏิทินวันหยุดของทีมที่ป้อนข้อมูลกิจกรรมลางาน

วิธีการทำงาน

โซลูชันนี้จะสร้างปฏิทินวันหยุดที่แชร์โดยอิงตามปฏิทินส่วนตัวของแต่ละคนในกลุ่ม Google เมื่อมีผู้จองวันหยุดพักผ่อน บุคคลดังกล่าวจะเพิ่มกิจกรรมลงใน Google ปฏิทินส่วนตัวโดยใช้คีย์เวิร์ด เช่น "วันหยุด" หรือ "ไม่อยู่ที่สำนักงาน"

ทุกชั่วโมง สคริปต์จะสแกนปฏิทินของสมาชิกในกลุ่มและซิงค์ กิจกรรมที่เหมาะสมกับปฏิทินที่แชร์ คุณสามารถเปลี่ยนความถี่ที่สคริปต์จะสแกนหาเหตุการณ์ใหม่ได้

โซลูชันนี้จะเข้าถึงเฉพาะกิจกรรมในปฏิทินที่เพื่อนร่วมงานของคุณ ตั้งค่าให้คุณมองเห็นได้โดยใช้การตั้งค่าความเป็นส่วนตัว

บริการ Apps Script

โซลูชันนี้ใช้บริการต่อไปนี้

ข้อกำหนดเบื้องต้น

หากต้องการใช้ตัวอย่างนี้ คุณต้องมีข้อกำหนดเบื้องต้นต่อไปนี้

  • บัญชี Google (บัญชี Google Workspace อาจต้อง ได้รับการอนุมัติจากผู้ดูแลระบบ)
  • เว็บเบราว์เซอร์ที่มีสิทธิ์เข้าถึงอินเทอร์เน็ต

ตั้งค่าสคริปต์

หากต้องการตั้งค่าสคริปต์เพื่อป้อนข้อมูลปฏิทินวันหยุดของทีม ให้ทำตามขั้นตอนต่อไปนี้

สร้างปฏิทินวันหยุดของทีม

  1. เปิดปฏิทิน
  2. สร้างปฏิทินใหม่ ชื่อ "วันหยุดของทีม"
  3. ในการตั้งค่าของปฏิทิน ให้คัดลอกรหัสปฏิทินในส่วนใช้งานร่วมกับปฏิทิน

สร้างโปรเจ็กต์ Apps Script

  1. หากต้องการเปิดโปรเจ็กต์ Apps Script ของปฏิทินวันหยุด ให้คลิกปุ่มต่อไปนี้ เปิดโปรเจ็กต์
  2. คลิกภาพรวม
  3. ในหน้าภาพรวม ให้คลิกทำสำเนา ไอคอนสำหรับการทำสำเนา
  4. ในโปรเจ็กต์ Apps Script ที่คัดลอก ให้ตั้งค่าตัวแปร TEAM_CALENDAR_ID เป็นรหัสของ ปฏิทินที่คุณสร้างไว้ก่อนหน้านี้
  5. ตั้งค่าตัวแปร GROUP_EMAIL เป็นอีเมลของกลุ่ม Google Groups ที่มีสมาชิกในทีม
  6. คลิกเพิ่มบริการ ข้างบริการ
  7. เลือก API Google ปฏิทิน แล้วคลิกเพิ่ม

เรียกใช้สคริปต์

  1. ในโปรเจ็กต์ Apps Script ที่คัดลอกไว้ ให้เลือกsetup ในเมนูแบบเลื่อนลงของฟังก์ชัน
  2. คลิกเรียกใช้
  3. ให้สิทธิ์สคริปต์เมื่อได้รับข้อความแจ้ง <<../_snippets/oauth.md>>
  4. เมื่อเสร็จแล้ว ให้กลับไปที่ปฏิทินเพื่อยืนยันว่าปฏิทินวันหยุดของทีมมีกิจกรรม

ตรวจสอบโค้ด

หากต้องการตรวจสอบโค้ด Apps Script สำหรับโซลูชันนี้ ให้คลิกดูซอร์สโค้ด

ดูซอร์สโค้ด

Code.gs

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

/*
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.
*/

// Set the ID of the team calendar to add events to. You can find the calendar's
// ID on the settings page.
const TEAM_CALENDAR_ID = "ENTER_TEAM_CALENDAR_ID_HERE";
// Set the email address of the Google Group that contains everyone in the team.
// Ensure the group has less than 500 members to avoid timeouts.
// Change to an array in order to add indirect members frrm multiple groups, for example:
// let GROUP_EMAIL = ['ENTER_GOOGLE_GROUP_EMAIL_HERE', 'ENTER_ANOTHER_GOOGLE_GROUP_EMAIL_HERE'];
const GROUP_EMAIL = "ENTER_GOOGLE_GROUP_EMAIL_HERE";

const ONLY_DIRECT_MEMBERS = false;

const KEYWORDS = ["vacation", "ooo", "out of office", "offline"];
const MONTHS_IN_ADVANCE = 3;

/**
 * Sets up the script to run automatically every hour.
 */
function setup() {
  const triggers = ScriptApp.getProjectTriggers();
  if (triggers.length > 0) {
    throw new Error("Triggers are already setup.");
  }
  ScriptApp.newTrigger("sync").timeBased().everyHours(1).create();
  // Runs the first sync immediately.
  sync();
}

/**
 * Looks through the group members' public calendars and adds any
 * 'vacation' or 'out of office' events to the team calendar.
 */
function sync() {
  // Defines the calendar event date range to search.
  const today = new Date();
  const maxDate = new Date();
  maxDate.setMonth(maxDate.getMonth() + MONTHS_IN_ADVANCE);

  // Determines the time the the script was last run.
  let lastRun = PropertiesService.getScriptProperties().getProperty("lastRun");
  lastRun = lastRun ? new Date(lastRun) : null;

  // Gets the list of users in the Google Group.
  let users = getAllMembers(GROUP_EMAIL);
  if (ONLY_DIRECT_MEMBERS) {
    users = GroupsApp.getGroupByEmail(GROUP_EMAIL).getUsers();
  } else if (Array.isArray(GROUP_EMAIL)) {
    users = getUsersFromGroups(GROUP_EMAIL);
  }

  // For each user, finds events having one or more of the keywords in the event
  // summary in the specified date range. Imports each of those to the team
  // calendar.
  let count = 0;
  for (const user of users) {
    const username = user.getEmail().split("@")[0];
    const events = findEvents(user, today, maxDate, lastRun);
    for (const event of events) {
      importEvent(username, event);
      count++;
    }
  }

  PropertiesService.getScriptProperties().setProperty("lastRun", today);
  console.log(`Imported ${count} events`);
}

/**
 * Imports the given event from the user's calendar into the shared team
 * calendar.
 * @param {string} username The team member that is attending the event.
 * @param {Calendar.Event} event The event to import.
 */
function importEvent(username, event) {
  event.summary = `[${username}] ${event.summary}`;
  event.organizer = {
    id: TEAM_CALENDAR_ID,
  };
  event.attendees = [];

  // If the event is not of type 'default', it can't be imported, so it needs
  // to be changed.
  if (event.eventType !== "default") {
    event.eventType = "default";
    event.outOfOfficeProperties = undefined;
    event.focusTimeProperties = undefined;
  }

  console.log("Importing: %s", event.summary);
  try {
    Calendar.Events.import(event, TEAM_CALENDAR_ID);
  } catch (e) {
    console.error(
      "Error attempting to import event: %s. Skipping.",
      e.toString(),
    );
  }
}

/**
 * In a given user's calendar, looks for occurrences of the given keyword
 * in events within the specified date range and returns any such events
 * found.
 * @param {Session.User} user The user to retrieve events for.
 * @param {string} keyword The keyword to look for.
 * @param {Date} start The starting date of the range to examine.
 * @param {Date} end The ending date of the range to examine.
 * @param {Date} optSince A date indicating the last time this script was run.
 * @return {Calendar.Event[]} An array of calendar events.
 */
function findEvents(user, start, end, optSince) {
  const params = {
    eventTypes: "outOfOffice",
    timeMin: formatDateAsRFC3339(start),
    timeMax: formatDateAsRFC3339(end),
    showDeleted: true,
  };
  if (optSince) {
    // This prevents the script from examining events that have not been
    // modified since the specified date (that is, the last time the
    // script was run).
    params.updatedMin = formatDateAsRFC3339(optSince);
  }
  let pageToken = null;
  let events = [];
  do {
    params.pageToken = pageToken;
    let response;
    try {
      response = Calendar.Events.list(user.getEmail(), params);
    } catch (e) {
      console.error(
        "Error retriving events for %s, %s: %s; skipping",
        user,
        keyword,
        e.toString(),
      );
      continue;
    }
    events = events.concat(response.items);
    pageToken = response.nextPageToken;
  } while (pageToken);
  return events;
}

/**
 * Returns an RFC3339 formated date String corresponding to the given
 * Date object.
 * @param {Date} date a Date.
 * @return {string} a formatted date string.
 */
function formatDateAsRFC3339(date) {
  return Utilities.formatDate(date, "UTC", "yyyy-MM-dd'T'HH:mm:ssZ");
}

/**
 * Get both direct and indirect members (and delete duplicates).
 * @param {string} the e-mail address of the group.
 * @return {object} direct and indirect members.
 */
function getAllMembers(groupEmail) {
  const group = GroupsApp.getGroupByEmail(groupEmail);
  let users = group.getUsers();
  const childGroups = group.getGroups();
  for (let i = 0; i < childGroups.length; i++) {
    const childGroup = childGroups[i];
    users = users.concat(getAllMembers(childGroup.getEmail()));
  }
  // Remove duplicate members
  const uniqueUsers = [];
  const userEmails = {};
  for (let i = 0; i < users.length; i++) {
    const user = users[i];
    if (!userEmails[user.getEmail()]) {
      uniqueUsers.push(user);
      userEmails[user.getEmail()] = true;
    }
  }
  return uniqueUsers;
}

/**
 * Get indirect members from multiple groups (and delete duplicates).
 * @param {array} the e-mail addresses of multiple groups.
 * @return {object} indirect members of multiple groups.
 */
function getUsersFromGroups(groupEmails) {
  const users = [];
  for (const groupEmail of groupEmails) {
    const groupUsers = GroupsApp.getGroupByEmail(groupEmail).getUsers();
    for (const user of groupUsers) {
      if (!users.some((u) => u.getEmail() === user.getEmail())) {
        users.push(user);
      }
    }
  }
  return users;
}

การปรับเปลี่ยน

คุณแก้ไขการทำงานอัตโนมัติของปฏิทินวันหยุดของทีมได้มากเท่าที่ต้องการเพื่อให้ตรงกับความต้องการของคุณ การเปลี่ยนแปลงต่อไปนี้เป็นการเปลี่ยนแปลงที่ไม่บังคับเพื่อแก้ไขทริกเกอร์

เปลี่ยนความถี่ที่สคริปต์จะสแกนหากิจกรรมใหม่

หากต้องการเปลี่ยนความถี่ในการเรียกใช้สคริปต์ ให้ทำตามขั้นตอนต่อไปนี้

  1. ในโปรเจ็กต์ Apps Script ให้คลิกทริกเกอร์
  2. คลิกแก้ไขทริกเกอร์ ข้างทริกเกอร์
  3. เลือกการเปลี่ยนแปลง แล้วคลิกบันทึก

ผู้ร่วมให้ข้อมูล

ตัวอย่างนี้ได้รับการดูแลโดย Google โดยได้รับความช่วยเหลือจาก Google Developer Expert

ขั้นตอนถัดไป