【GAS】#2 Google Calendarに登録されている予定をSlackに通知する

ショートカットキー

1. 概要

Google Calendar to Slack

本記事では「API連携」による通知について解説します。

2. SlackからWebHook URLを取得

2-1. Slackから「Add apps」をクリック

2-2. 「Incoming WebHooks」を検索し、「Add」ボタンをクリック

2-3. 「Add to Slack」をクリック

2-4. 「通知するチャンネルを選択」し、「Add Incoming WebHooks integration」ボタンをクリック後、「WebHook URL」(*4-3)を取得

  • 「https://hooks.slack.com/services/~」

3. Calendar IDの取得

3-1. 「Options for ユーザー名」をクリック後、「Settings and sharing」をクリック

3-2. 「Integrate calendar」をクリック

3-3. 「Calendar ID」が表示される

4. サンプルコード

4-1. ファイル構成(GitHubで管理

  • notification/slack/calendar_to_slack.gs
    • メインコード
  • notification/slack/gas_properties.gsheet
    • 「WebHook URL」を含め、コード内に書かない方が良いデータ(ID、PASSWORD、KEY等)をプロパティとして保存

4-2. スプレッドシートIDの取得

4-3. GAS Editorの開け方

※「+新規」をクリック

4-4. コード & 解説

※複数のプログラムよりプロパティファイルを共有する為、敢えてスタンドアロン型(*4-2)を採用する

// SlackのWebHook URLが記載されているスプレッドシートのID
const bookId = '1j2z-S●●●●●●●●●●●●●●●●●●●●●●●●●●●●cQk';
// Slackへ通知する際の名前
const username = 'Notification';

// Mainメソッド
// Google Calendarに登録されているスケジュールをSlackへ通知する
const notifySlack = () => {
  sendToSlack(getCalendarInfo());
}

// カレンダー情報を取得
const getCalendarInfo = () => {
  const ownerOfCalendar = getValueOfProperty('D3');
  const calendar = CalendarApp.getCalendarById(ownerOfCalendar);
  const targetDate = new Date();
  const calendarEvents = calendar.getEventsForDay(targetDate);

  let calendarInfo = [];

  calendarEvents.forEach((event) => {
    const title = event.getTitle();
    const startTime = formatDt(event.getStartTime());
    // trueの場合、Owner含む
    const guests = event.getGuestList(true);
    let guestNames = [];
    guests.forEach((guest) => {
      guestNames.push(getFullNameFromEmail(guest.getEmail()));
    });
    calendarInfo.push(`【日時】${startTime}\n【タイトル】${title}\n【参加者】${guestNames.toString()}`);
  });
  return calendarInfo;
}

// 指定のスプレッドシートに記載されているプロパティの値を取得
const getValueOfProperty = (cell) => {
  const sheet = SpreadsheetApp.openById(bookId).getSheetByName('Properties');
  return sheet.getRange(cell).getValue();
}

// 日時を読みやすく整形
const formatDt = (calDt) => {
  return `${calDt.getFullYear()}/${calDt.getMonth() + 1}/${calDt.getDate()} ${calDt.getHours()}:${calDt.getMinutes()}:${calDt.getSeconds()}`;
}

// Emailから名前を取得
const getFullNameFromEmail = (email) => {
  return ContactsApp.getContact(email).getFullName();
}

// 配列に格納されている分を回しながら、Slackへ通知
const sendToSlack = (msgs) => {
  const webhookUrl = getValueOfProperty('C3');

  msgs.forEach((msg) => {
    // 通知する内容
    const param = {
      'username': username,
      'text': msg
    };
    // paramをJSON文字列に変換
    const payload = JSON.stringify(param);
    // APIを叩くにあたってどのような仕様で通信を行うか、どのような情報を送るかを指定
    const options = {
      'method': 'post',
      'headers': {
        'Content-Type': 'application/json'
      },
      'payload': payload
    };
    // APIの呼び出し(ここで実際に通知される)
    UrlFetchApp.fetch(webhookUrl, options);
  });
}

5. 参考

5-1. GAS(Google Apps Script)とは

5-2. 2種類の方式

5-3. Webhookとは

5-4. 「UrlFetchApp.fetch()」について

投稿者プロフィール

Sondon
開発好きなシステムエンジニアです。
卓球にハマってます。

関連記事

  1. ショートカットキー

    【GAS】#9 スプレッドシートの明日のシフト表より当番や時間を取得し…

  2. ショートカットキー

    【GAS】#12 指定フォルダ(下位フォルダ含む)に更新されたファイル…

  3. ショートカットキー

    【GAS】#5 LINE(リッチメニュー)とスプレッドシートを利用し、…

  4. ショートカットキー

    【GAS】#6 ブログにて発信しているユーザーを月毎に集計し、Slac…

  5. ショートカットキー

    【GAS】#8 TwitterのPublic Metricsデータを取…

  6. ショートカットキー

    【GAS】#4 OCRにて画像からテキストを起こし、Lineへ通知する…

最近の記事

  1. AWS
  2. flutter

制作実績一覧

  1. Checkeys