Last active
April 2, 2017 09:48
-
-
Save xeno14/9b16acfe5f3cf8c3ef706249bbda1a41 to your computer and use it in GitHub Desktop.
DMM英会話のレッスン予約完了メールをGmailからパースしてGoogleカレンダーに予約するGoogle App Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 本体 | |
function DMMCalenderFromGmail() { | |
// prefixとsuffixに挟まれた文字列の取得 | |
function findLine(body, prefix, suffix) { | |
var istart, iend; | |
istart = body.indexOf(prefix) + prefix.length; | |
iend = istart + body.slice(istart).indexOf(suffix); | |
return body.slice(istart, iend); | |
} | |
// メール中の日時をDateオブジェクトへ変換 | |
function dateStrToDate(strDate, strTime) { | |
var date = strDate.replace('年', '/').replace('月', '/').replace('日', ''); | |
var time = strTime.replace('時', ':').replace('分', ''); | |
return new Date(date + " " + time); | |
} | |
// メール本文のパース | |
function parseBody(body) { | |
var teacher = findLine(body, "講師名:", "\n"); | |
var strDate = findLine(body, "ご予約日:", "\n"); | |
var strTime = findLine(body, "開始時間:", "\n"); | |
var startDate = dateStrToDate(strDate, strTime); | |
var endDate = new Date(startDate); | |
endDate.setMinutes(startDate.getMinutes() + 25); | |
return { | |
"teacher": teacher, | |
"start": startDate, | |
"end": endDate, | |
"title": "【DMM英会話】" + teacher | |
}; | |
} | |
// レッスン予約完了のお知らせの取得 | |
var threads = GmailApp.search("【DMM英会話】レッスン予約完了のお知らせ"); | |
// 最近の10件のみカレンダーに追加する対象とする | |
var numThreads = Math.min(threads.length, 10); | |
// メールのメッセージ | |
var messages = GmailApp.getMessagesForThreads(threads.slice(0, numThreads)); | |
// カレンダー | |
var calender = CalendarApp.getDefaultCalendar(); | |
for (var i=0; i<messages.length; i++) { | |
// メール | |
var msg = messages[i][0]; | |
// メール本文のパース | |
var body = msg.getBody(); | |
var contents = parseBody(body); | |
// 既に同名の予定が同じ時間に存在するかチェックする | |
var alreadyCreated = calender.getEvents(contents["start"], contents["end"], {search: contents["title"]}); | |
// 存在しなければ予定を作成する | |
if (alreadyCreated.length == 0) { | |
var event = calender.createEvent(contents["title"], contents["start"], contents["end"]); | |
// 10分前のポップアップ通知 | |
event.addPopupReminder(10); | |
Logger.log("Created event: " + contents["title"] + " at " + contents["start"]); | |
} else { | |
Logger.log("Event already exists: " + contents["title"] + " at " + contents["start"]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment