4
1

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.

LINE BOT にGoogleカレンダー予定を通知

Posted at

はじめに

前提

大まかな流れ

  1. ラインボットからアクセストークンを取得
  2. コード解説
  3. 最後に

ゴール

毎日の設定した時間に今日の予定を通知してくれます☕️

1.作成したアカウントに移動し、アクセストークンをコピーします。

スクリーンショット 2020-11-08 7.20.10.png

2. コード解説

index.gs
var access_token = "ACCESS_TOKEN" //<= LINEのアクセストークン

function getCalendar() {
  var startDate = new Date();
  const CALENDAR_IDS = ["********@gmail.com"]; //<= Googleのメールアドレス(複数可能)
  let message = []
  
  CALENDAR_IDS.forEach(function(CALENDAR_ID){
    var myCalendar = CalendarApp.getCalendarById(CALENDAR_ID)
    var myEvents = myCalendar.getEventsForDay(startDate)
    
    myEvents.forEach(function(event){
      event.getTitle()
      event.getDescription()
      var eventStartTime = event.getStartTime();
      eventStartTime = Utilities.formatDate(eventStartTime, 'JST', 'HH:mm');
      if (event.getTitle()) {
       message.push(eventStartTime + ':' + event.getTitle() + '\n\n')
      }
      if (event.getDescription()) {
       message.push(event.getDescription() + '\n\n\n')
      }
    });
  })  
  message = message.join('');
  return push(message);
}


//メッセージを送信する関数を作成
function push(message) {
  var url = "https://api.line.me/v2/bot/message/push";
  var headers = {
    "Content-Type" : "application/json; charset=UTF-8",
    'Authorization': 'Bearer ' + access_token,
  };

  var postData = {
    "to" : to,
    "messages" : [
      {
        'type' : 'text',
        'text' : message
      }
    ]
  };
  
  var options = {
    "method" : "post",
    "headers" : headers,
    "payload" : JSON.stringify(postData)
  };

  return UrlFetchApp.fetch(url, options);
}
}
  • 1行目、LINEアクセストークン設定
var access_token = "ACCESS_TOKEN" //<= LINEのアクセストークン
  • 2行目、カレンダー情報を取得したいGoogleアカウントのメールアドレス設定
const CALENDAR_IDS = ["********@gmail.com"]; //<= Googleのメールアドレス(複数可能)
  • 3行目~25行目

今回は、複数のアカウント設定を想定していますので、foreachでループ処理をしています。

  • 25行目以降で、LINEにメッセージを送るためのパラメータを設定しています。

3. 最後に

どうですか?うまく送信できましたか?☕️

定期実行、トリガーの設定方法
https://tonari-it.com/gas-timed-driven-trigger/

メッセージタイプを変更したい場合、
https://developers.line.biz/ja/reference/messaging-api/#rich-menu

カレンダー📆取得内容変更したい場合、
https://developers.google.com/calendar/v3/reference/events#resource

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?