理由
最近、ジムを始めました。会費が地味に高いので、どのぐらい通ったかを自動にカウントしたい。
必要な設定
- ジムのイベントがGoogleカレンダーに追加されていること
- [Gmailに受信したFEELCYCLE予約完了メールからGoogleカレンダーにイベント追加するGASスクリプト]
(https://qiita.com/micciiii/items/3bbc8bd78f38018a292f)
- [Gmailに受信したFEELCYCLE予約完了メールからGoogleカレンダーにイベント追加するGASスクリプト]
- SlackでEmail受け取りの設定済み
- [【超簡単5分】自分宛のbacklogの通知をSlackで受け取る方法] (https://qiita.com/Kathy/items/14749d2bdbf1f23f4012)
イメージ
Script
テスト時はmain()関数を実行し、Trigger設定を含めて実装する時はinit()を実行。
cal_name
, gym_name
, slack_email
を適宜変えてください
function init(){
// Trigger every week
ScriptApp.newTrigger('main').timeBased().everyWeeks(1).onWeekDay(ScriptApp.WeekDay.FRIDAY).atHour(10).create();
}
function main() {
var cal_name = "Feelcycle";
var gym_name = "Feelcycle";
var slack_email = "xxxx@xxxx.slack.com";
var end_date = new Date();
var start_date = new Date(end_date.getTime());
start_date.setDate(start_date.getDate() - 6); // one week from now
events = getEventsFromCal(cal_name, start_date, end_date);
Logger.log("Fetched " + events.length + " events");
content = createEmailBody(events, gym_name);
Logger.log("content " + content);
sendToMyself(slack_email, gym_name, content, start_date, end_date);
}
function getEventsFromCal(name, start, end) {
var cal = CalendarApp.getCalendarsByName(name)[0];
if (cal) {
return cal.getEvents(start, end);
} else {
Logger.log("カレンダーが見つかりませんでした: " + name);
}
}
function formatDateStr(d){
Logger.log(d);
return d.getFullYear() + ("0" + (d.getMonth() + 1)).slice(-2) + ("0" + d.getDate()).slice(-2);
}
function sendToMyself(email_address, gym_name, content, start_date, end_date) {
var startDateStr = formatDateStr(start_date);
var endDateStr = formatDateStr(end_date);
var fileName = gym_name + "_weekly_stats" + "_" + startDateStr + "_" + endDateStr
GmailApp.createDraft(email_address, fileName, content).send();
}
function createEmailLine(i, event, gym_name){
var title = event.getTitle();
var startIdx = title.indexOf("]"); // parse event title
var endIdx = title.indexOf("@");
var realTitle = title.slice(startIdx + 1, endIdx);
var date = event.getStartTime();
var dateStr = date.toLocaleDateString();
var str = (i+1) + ") " + dateStr + " - " + realTitle + "、" + gym_name + "に行ったね"
return str
}
function createEmailBody(events, gym_name) {
// loop through all events
if (events.length > 0) {
var body = "";
for (var i = 0; i < events.length; i++) {
var event = events[i];
var str = createEmailLine(i, event, gym_name);
if (i < events.length - 1) {
body += str + "\r\n";
}
else {
body += str;
}
}
return body;
} else {
return gym_name + "に行ってないじゃん";
}
}