Skip to content

Instantly share code, notes, and snippets.

@timgcarlson
Last active July 25, 2024 23:09
Show Gist options
  • Save timgcarlson/503d7ec7a712855df5cf289e85230e39 to your computer and use it in GitHub Desktop.
Save timgcarlson/503d7ec7a712855df5cf289e85230e39 to your computer and use it in GitHub Desktop.
Google Apps Script: Post Daily OOO Events to Slack
function postDailyOOOEventsToSlack() {
// The alphanumeric portion of your Google calendar ID
const calendarId = '';
const fullCalendarId = `${calendarId}@group.calendar.google.com`;
// The link to your Slack app with an Incoming Webhook
const slackWebhookUrl = '';
// Update this URL with your expected timezone
const calendarUrl = `https://calendar.google.com/calendar/embed?src=${calendarId}%40group.calendar.google.com&ctz=America%2FLos_Angeles/event`;
const today = new Date();
const startOfToday = new Date(today.setHours(0, 0, 0, 0));
const endOfDay = new Date(today.setHours(23, 59, 59, 999));
const formattedToday = Utilities.formatDate(today, Session.getScriptTimeZone(), "EEE, MMM d, yyyy");
const events = CalendarApp.getCalendarById(fullCalendarId).getEvents(startOfToday, endOfDay);
let blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `*<${calendarUrl}|Out of Office> events for ${formattedToday}:*\n\n`
}
}
];
const timeZone = Session.getScriptTimeZone();
events.forEach((event, index) => {
const eventTitle = event.getTitle();
const eventDescription = event.getDescription();
const startTime = event.getStartTime();
const endTime = event.getEndTime();
const isAllDay = event.isAllDayEvent();
let timeString = "";
if (isAllDay) {
const totalDays = Math.ceil((endTime - startTime) / (1000 * 60 * 60 * 24));
const currentDay = Math.ceil((startOfToday.getTime() - startTime.getTime()) / (1000 * 60 * 60 * 24)) + 1;
if (totalDays > 1) {
const startMonth = Utilities.formatDate(startTime, timeZone, "MMM d");
const endMonth = Utilities.formatDate(endTime, timeZone, (startTime.getMonth() === endTime.getMonth() ? "d" : "MMM d"));
const endYear = startTime.getFullYear() === endTime.getFullYear() ? "" : `, ${endTime.getFullYear()}`;
timeString = `${startMonth} - ${endMonth}${endYear} (Day ${currentDay} of ${totalDays})`;
} else {
timeString = "All Day";
}
} else {
const formattedStartTime = Utilities.formatDate(startTime, timeZone, "h:mma").toLowerCase().replace("am", "a").replace("pm", "p");
const formattedEndTime = Utilities.formatDate(endTime, timeZone, "h:mma").toLowerCase().replace("am", "a").replace("pm", "p");
const timeZoneName = (new Date()).toLocaleTimeString('en-us', { timeZoneName: 'short' }).split(' ')[2];
if (startTime.getDate() !== endTime.getDate()) {
const endDate = Utilities.formatDate(endTime, timeZone, "MMM d");
timeString = `${formattedStartTime} - ${endDate} ${formattedEndTime} (${timeZoneName})`;
} else {
timeString = `${formattedStartTime} - ${formattedEndTime} (${timeZoneName})`;
}
}
blocks.push(
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": `*${eventTitle}*`
},
{
"type": "mrkdwn",
"text": `${timeString}`
}
]
}
);
if (eventDescription) {
blocks.push(
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `_${eventDescription}_`
}
}
);
}
if (index < events.length - 1) {
blocks.push(
{
"type": "divider"
}
);
}
});
if (events.length === 0) {
blocks.push(
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `No out of office events for today.`
}
}
);
}
const payload = {
blocks: blocks
};
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload)
};
UrlFetchApp.fetch(slackWebhookUrl, options);
}
@timgcarlson
Copy link
Author

timgcarlson commented Jul 25, 2024

Setting Up Daily OOO Updates to Slack

To make use of this script to post daily updates to your Slack channel, follow these steps:

In Google Calendar

  1. Create a New Calendar (if needed):
    • Go to Google Calendar and create a new calendar.
  2. Get the Calendar ID:
    • In the new calendar's settings, save/copy the calendar ID.

In Slack

  1. Create a New App in Slack:
  2. Enable Incoming Webhooks:
    • Under Features, select Incoming Webhooks and turn them on.
  3. Create the Webhook:
    • Select the channel you want the messages to post to and then create the webhook.
  4. Save/Copy the Webhook URL:
    • Save/copy the webhook URL for later use.

In Google Apps Script

  1. Create a New Google Apps Script:
  2. Copy the Script:
    • Copy the provided script into your new Apps Script project.
  3. Configure the Script:
    • Paste the calendar ID and Slack webhook URL into the corresponding variables at the top of the script. Note that this script breaks out @group.calendar.google.com from the ID that you copied in Google Calendar.

    At this point, you should be able to execute the script by clicking the run button in the toolbar, which (if configured correctly) will post a message to your Slack channel.

  4. Set Up a Trigger:
    • Open the "Triggers" section (the stopwatch icon on the left side).
    • Click "Add Trigger" and configure the following settings:
      • Choose which function to run: Select your postDailyOOOEventsToSlack function.
      • Choose which deployment should run: Select "Head" (or the appropriate deployment if you have multiple).
      • Select event source: Choose "Time-driven".
      • Select type of time-based trigger: Choose "Day timer".
      • Select time of day: Choose the time you want the script to run every day.
      • Failure notification settings: Adjust these settings as needed.
  5. Deploy the Script:
    • Click on the blue "Deploy" button in the top-right corner and select "New deployment".
    • In the "Select type" dropdown, choose "Web app".
    • Set the description for your deployment (e.g., "Daily OOO Event Poster").
    • For "Execute as", choose "Me".
    • For "Who has access", select "Anyone" if your script needs to interact with external services like Slack without requiring additional permissions. Otherwise, choose "Only myself" or "Anyone with Google account" based on your requirements.
    • Click "Deploy" and follow the prompts to authorize the script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment