2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Googleカレンダーから昼休憩の時間を取得してslackに投稿する

Last updated at Posted at 2022-02-23

動機

  • 在宅勤務の家族と昼休憩の時間を共有したい。
    • 家族のお昼休憩の時間は日によってまちまち。
    • 休憩開始時間を知りたいけど、毎日直接聞いて確認するのは面倒だし仕事の都合で変わることもある。
  • 会社のカレンダーを共有することはできないので、Google Apps Script(GAS)で昼休憩の開始時間だけ取得してslackに投稿する。

前提

  • 昼休憩の時間はタイトル「ランチ」で登録している。
  • ついでにその日最後のスケジュールの終了時間も取得。
    • 晩ご飯を早くて何時から開始できるか知るため。
  • 有給の日と祝日はslack投稿を行わない。
    • 休みの日はタイトル「有給」で登録している。
    • 祝日はGoogleカレンダーの「日本の祝日」(カレンダーID ja.japanese#holiday@group.v.calendar.google.com)から取得する。

前準備

  • Slack Incoming Webhookを設定してWeb hook URLを取得。
  • GASのスクリプトエディタのtimeZoneをAsia/Tokyoに変更。
  • 予定を取得したいカレンダーのカレンダーIDを確認。
  • GASのトリガーを日時ベースのタイマー午前10~11時と午後5時~6時に設定。

コード

function postMealtime() {
  // 日付を設定
  const today = new Date();
  const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 10, 0);
  const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 0);

  // カレンダーから祝日を取得
  const holiday = CalendarApp.getCalendarById('ja.japanese#holiday@group.v.calendar.google.com').getEvents(startTime,endTime); 
  // 祝日の確認
  if(holiday.length > 0) {
    //return;
  }
      
  // カレンダーから予定を取得
  const schedule = CalendarApp.getCalendarById('カレンダーIDを記載').getEvents(startTime,endTime); 

  // 有給の確認
  if(schedule.find(v => v.getTitle() === "有給" )){
    return;
  }

  // ランチの時間を取得
  const lunchSchedule = schedule.find(v => v.getTitle() === "ランチ");
  const lunchTime = lunchSchedule ? Utilities.formatDate(lunchSchedule.getStartTime(), "JST", "HH:mm") : "登録されていません";  

  // 晩ご飯の時間を取得
  // 厳密にはスケジュールがないときのハンドリングもしたほうがいい
  const dinnerTime = Utilities.formatDate(schedule[schedule.length - 1].getEndTime(), "JST", "HH:mm");
  postToSlack(`お昼🥐${lunchTime}\n晩ご飯🍴${dinnerTime}以降`);
}

function postToSlack(postMessage) {
  const postUrl = 'Web hook URLを記載';
  const payload = JSON.stringify({ text: postMessage });
  const options = { method: 'post', contentType: 'application/json', payload: payload };
  UrlFetchApp.fetch(postUrl, options);
}

結果

slack投稿.png
意外と簡単でした。これで家族とより便利に過ごせそうです。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?