Skip to content

Instantly share code, notes, and snippets.

@makoto-unity
Created September 11, 2019 05:31
Show Gist options
  • Save makoto-unity/95e24e586e9eb527e2b9edce098097db to your computer and use it in GitHub Desktop.
Save makoto-unity/95e24e586e9eb527e2b9edce098097db to your computer and use it in GitHub Desktop.
function doPost(e) {
// トークンの確認
var VERIFY_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXX"; // 1. トークン
if (VERIFY_TOKEN != e.parameter.token) {
throw new Error("invalid token.");
}
var googleCalenderId = "[email protected]"; // 2. GoogleカレンダーのID
var scheduleWords = '俺のスケジュール'; // 3. この後の数字が最大日数になる
var maxDay = 14; // 4. デフォルト最大日数
var startHour = 11; // 5. 予定可能開始時間(この時間から〜)
var endHour = 19; // 6. 予定可能終了時間(この時間まで予定が入れられる)
var webHookURL = "https://hooks.slack.com/services/XXXXXXXX/YYYYYYYYY/ZZZZZZZZZZZZZZZZZZZ"; // 7. Webhook URL
var text = e.parameter.text;
text = text.replace(scheduleWords, '');
var intText = Number(text);
if ( intText > 0 ) {
maxDay = intText;
}
var list = "";
var s;
s = listupEvent(googleCalenderId, maxDay, startHour, endHour);
if (s != "") list += "\n" + s;
// Logger.log(list);
if (list != "") {
var payload = {
"text" : "直近" + maxDay.toString() + "日の空いている日程です。\n\n\n" + list, // 8. メッセージの本文
"channel" : "#my-schedule", // 9. チャネル名
"icon_url" : "https://pbs.twimg.com/profile_images/966692705026818048/OqVg_vx9_400x400.jpg", // 10. アイコン
"username" : "秘書おなか", // 11. Bot名
}
postSlack(payload, webHookURL);
}
}
function listupEvent(cal_id, maxDay, startHour, endHour)
{
var list = "";
var cal = CalendarApp.getCalendarById(cal_id);
var date = new Date();
var endTimeString = "";
date.setMinutes(0);
for(var i=0 ; i<maxDay ; i++) {
s = "";
date.setDate(date.getDate() + 1);
var isStartFreeTime = new Boolean(false);
var day = date.getDay();
if ( day == 0 || day == 6 ) continue; // 土日は除外
for(var j=startHour ; j<=(endHour-1) ; j++ ) {
date.setHours(j);
var startTime = new Date(date.getTime() - (59 * 60 * 1000));
var endTime = new Date(date.getTime() + ((60+59) * 60 * 1000));
var events = cal.getEvents(startTime, endTime); // 前後1時間以内に予定があるか確認
if ( events.length > 0 ) {
if ( isStartFreeTime == true )
{
isStartFreeTime = false;
s += endTimeString;
}
} else {
var dateEnd = new Date(date.getTime());
dateEnd.setHours(dateEnd.getHours() + 1);
if ( isStartFreeTime == false )
{
s += Utilities.formatDate(date, "GMT+0900","MM/dd HH:mm");
isStartFreeTime = true;
}
endTimeString = Utilities.formatDate(dateEnd, "GMT+0900","-HH:mm \n");
}
}
if ( isStartFreeTime == true )
{
s += endTimeString;
}
list += s;
}
return list;
}
function postSlack(payload, webHookURL)
{
var options = {
"method" : "POST",
"payload" : JSON.stringify(payload)
}
var response = UrlFetchApp.fetch(webHookURL, options);
var content = response.getContentText("UTF-8");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment