

## やりたい事

複数のGoogleカレンダーの週間予定を習得しLINEに通知をしたいです。

  * 予定がない時は通知をしない
  * 日付をまたぐ予定は開始日の日付しか表示をしない。

初心者な者でうまくできません。アドバイスよろしくお願い致します。

## ソースコード

[code]

        const lineToken = "LINE　コード";
    
    function q219287() {
        const today = new Date();
        const days = [0,1,2,3,4,5,6].map(function (d) { return (new Date()).setDate(today.getDate() + d);});
        const events = days.reduce(function (a, c) {
            const eves = getEvents(c);
            return eves.length === 0 ? a : a.concat([c, eves]);
        },[]);
        if(events.length === 0) { return; }
        const message = events.map(function (e) { return [toDate(e[0])].concat(e[1].map(eventAsText));}).join("\n");
        sendToLine(message);
    }
    
    function getEvents(thedate) {
        const calendars = {
            "①@group.calendar.google.com" : "①",
            "②@group.calendar.google.com" : "②",
            "③@group.calendar.google.com" : "③",
            "④@group.calendar.google.com" : "④",
            "⑤@group.calendar.google.com" : "⑤",
            "⑥@gmail.com" : "⑥",
        };
        return Object.keys(calendars).map(function (e) { return CalendarApp.getCalendarById(e);}).map(function (cal) {
            return [calendars[e], getEventsStartsInTheDay(cal, thedate)];
        }).filter(function (e) {
            return e[1].length > 0;
        });
    }
    
    function eventAsText(events) {
        return events.map(function (e) {
            return '◆ ' + e[0] + '\n' + e[1].map(eventToString).join('\n\n');
        }).join('\n');
    }
    function sendToLine(text) {
        const token = lineToken;
        const options = {
            "method": "post",
            "payload": "message=" + text,
            "headers": {"Authorization": "Bearer " + token}
        };
        UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
    }
    
    function toTime(targetdate, basedate) {
        const min = Utilities.formatDate(str, 'JST', "mm");
        const hour = Utilities.formatDate(str, 'JST', "HH");
        if(targetdate.getDate() === basedate.getDate()) {
            return hour + ":" + min;
        }
        const target = new Date(targetdate.getFullYear(), targetdate.getMonth(), targetdate.getDate());
        const base = new Date(basedate.getFullYear(), basedate.getMonth(), basedate.getDate());
        const datediff = Math.floor(target - base / 86400000);
        return ("0" + ((hour - 0) + 24 * datediff)).slice(-2) + ":" + min;
    }
    function toDate(date) {
        return Utilities.formatDate(dt, 'JST', '★ MM/dd(' + ["日", "月", "火", "水", "木", "金", "土"][date.getDay()] + ')');
    }
    
    function getEventsStartsInTheDay(calendar, thedate) {
        const dateNum = thedate.getDate();// 219287 のエラーからすると (new Date(thedate)).getDate(); か。
        return calendar.getEventsForDay(thedate).filter(function (e) {
            return e.getStartTime().getDate() === dateNum;
        });
    }
    function eventToString(event) {
        const start = event.getStartTime();
        return toTime(start, start) + ' - ' + toTime(event.getEndTime(), start) + '\n ' + event.getTitle() + '\n\n';
    }
    // 219287
    // 219724 style
    function sendTodaySchedule() {
        var accessToken = PropertiesService.getScriptProperties().getProperty('LINE_TOKEN');
    
        const message = [0,1,2,3,4,5,6].map(function (d) { return getMessage(d);}).filter(function (e) { return e !== "";}).join("\n");
        if (!_isNull(message)) {
            const options =
                {
                    'method': 'post'
                    , 'payload': 'message=' + message
                    , 'headers': {'Authorization': 'Bearer ' + accessToken}
                    , muteHttpExceptions: true
                };
            UrlFetchApp.fetch('https://notify-api.line.me/api/notify', options);
        }
    }
    
    function getMessage(prm) {
        const week = ['日', '月', '火', '水', '木', '金', '土'];
    
        var arrCals = [];
        arrCals.push(CalendarApp.getCalendarById('Googleカレンダー@gmail.com'));
        arrCals.push(CalendarApp.getCalendarById('Googleカレンダー@group.calendar.google.com'));//①
        arrCals.push(CalendarApp.getCalendarById('Googleカレンダー@group.calendar.google.com'));//②
        arrCals.push(CalendarApp.getCalendarById('Googleカレンダー@group.calendar.google.com'));//③
        arrCals.push(CalendarApp.getCalendarById('Googleカレンダー@group.calendar.google.com'));//④
        arrCals.push(CalendarApp.getCalendarById('Googleカレンダー@group.calendar.google.com'));//⑤
    
        var date = new Date();
        var strHeader = '';
        date = new Date(date.getYear(), date.getMonth(), date.getDate() + prm);
        strHeader += Utilities.formatDate(date, 'JST', 'yyyy/M/d')
            + '(' + week[date.getDay()] + ') の予定\n';
    
        var strBody = getEvents(arrCals, date);
        //if ( _isNull(strBody) ) strBody = '予定はありません。';
        return _isNull(strBody) ? '' : strHeader + strBody;
    }
    
    function getEvents(prmarrCals, prmDate) {
        var strEvents = '';
        var strStart = '';
        var strEnd = '';
        var strTime = '';
        var strLocation = '';
        var strDescription = '';
        if (!_isNull(prmarrCals)) {
            for (var j = 0; j < prmarrCals.length; j++) {
                var currentEvents = '';
                var arrEvents = prmarrCals[j].getEventsForDay(new Date(prmDate));
                for (var i = 0; i < arrEvents.length; i++) {
    //                if (!_isNull(strEvents)) strEvents += '\n';
                    var starts = arrEvents[i].getStartTime();
                    if (starts.getDate() !== prmDate.getDate()) continue;
                    strStart = _HHmm(starts);
                    strEnd = toTime(arrEvents[i].getEndTime(), starts);
                    if (strStart === strEnd) {
                        strTime = '終日';
                    } else {
                        strTime = strStart + '～' + strEnd;
                    }
                    currentEvents += '･' + strTime + '【' + arrEvents[i].getTitle() + '】';
                    strLocation = arrEvents[i].getLocation();
                    strDescription = arrEvents[i].getDescription();
                    if (!_isNull(strLocation)) currentEvents += '\n　場所：' + strLocation;
                    if (!_isNull(strDescription)) currentEvents += '\n　説明：' + strDescription;
                }
                if (_isNull(currentEvents)) continue;
                if (!_isNull(strEvents)) strEvents += '\n';
                strEvents += prmarrCals[j].getName() + '\n' + currentEvents;
            }
        }
        return strEvents;
    }
    
    function _HHmm(str) {
        return Utilities.formatDate(str, 'JST', 'HH:mm');
    }
    
    function _isNull(prm) {
        if (prm == '' || prm === null || prm === undefined) {
            return true;
        } else {
            return false;
        }
    }
    //219724
    //236158 style
    const token = "LINE_TOKEN";
    
    const calendarTitleMap = {
        "①@group.calendar.google.com" : "①",
        "②@group.calendar.google.com" : "②",
        "③@group.calendar.google.com" : "③",
        "④@group.calendar.google.com" : "④",
        "⑤@group.calendar.google.com" : "⑤",
        "⑥@gmail.com" : "⑥",
    
    };
    
    const weekday = ["日", "月", "火", "水", "木", "金", "土"];
    
    function notifyWeekly() {
        var _counter = 0;
        const calendars = CalendarApp.getAllCalendars();
        var dt = new Date()
        var message = "週間予定\n\n";
    
        for ( var i = 3;  i < 8;  i++ ) {
    
            dt.setDate(dt.getDate() + 2);
            message += Utilities.formatDate(dt, 'JST', '★ MM/dd(' + weekday[dt.getDay()] + ')') + "\n";
    
            var dayText = "";
            for(j in calendars) {
                var calendar = calendars[j];
    
                var calendarName = calendarTitleMap[calendar.getId()]
                if ( calendarName == undefined ) {
                    continue;
                }
    
                var events = calendar.getEventsForDay(dt);
                if( events.length == 0 ) {
                    continue;
                }
    
                dayText += "< " + calendarName + " >\n";
                for(j in events) {
                    var tmp = toDayText(events[j], dt);
                    dayText += tmp === "" ? "" : tmp + "\n";
                }
                //dayText += "\n"
            }
    
            if ( dayText == "") {
                dayText += "予定はありません\n\n";
                counter++;
            }
            message += dayText;
        }
        if(_counter === 5) { return; }
        sendToLine(message);
    }
    
    function toDayText(event, date) {
        const st = event.getStartTime();
        if(st.getDate() !== date.getDate()) { return ""; }
        return toTimeText(st) + ' - ' + toTime(event.getEndTime(), st) + " " + event.getTitle() + '\n';
    }
    
    function toTimeText(str){
        return Utilities.formatDate(str, 'JST', 'HH:mm');
    }
    
[/code]


CC BY-SA 4.0
2020-01-28T05:00:56.120
62601
2020-01-28T05:03:57.073
2020-01-28T05:03:57.073
32986
37612
question
google-apps-script line google-calendar-api
複数のGoogleカレンダーの週間予定を習得しLINEに通知をしたいです。