Skip to content

Instantly share code, notes, and snippets.

@matsuokah
Last active January 15, 2016 06:01
Show Gist options
  • Save matsuokah/c8f28549d14800ef7110 to your computer and use it in GitHub Desktop.
Save matsuokah/c8f28549d14800ef7110 to your computer and use it in GitHub Desktop.
var slackUrl = "WEBHOOK URL"
var selfAddress = "YOUR EMAIL ADDRESS FOR ERROR NOTIFICATION";
var defaultPayload = {
"channel": "notification",
"username": "ヤマト不在通知",
"icon_emoji": ":smiley_cat:"
};
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
function postSlack(message) {
var payload = clone(defaultPayload);
payload['text'] = message.getPlainBody();
var payloadStr = JSON.stringify(payload);
// :は\:にエスケープする必要がある.
var escapedStr = payloadStr.replace(/":"/g, "\"\:\"");
Logger.log(escapedStr);
var options = {
'method' : 'post',
'contentType' : 'Content-type: application/json; charset=utf-8',
'payload' : escapedStr
}
var response = UrlFetchApp.fetch(slackUrl, options);
var ret = true;
if (response.getResponseCode() != 200) {
ret = false;
}
return {status: ret, code: response.getResponseCode(), response: response};
}
function postError(message) {
GmailApp.sendEmail(selfAddress, "Slackへのポストに失敗しました", "スクリプトを確認してください。失敗メールの件名:" + message.getSubject());
}
function messageFilter(message) {
var sub = message.getSubject();
if (sub.includes("ご不在連絡eメール")) {
return message;
}
return null;
}
function main() {
var searchQuery = 'from:mail@kuronekoyamato.co.jp'
var threads = GmailApp.search(searchQuery);
for (var i = 0; i < threads.length; i++) {
var thread = threads[i];
if (!thread.isUnread()) {
continue;
}
var messages = thread.getMessages();
for (var j = 0; j < messages.length; j++) {
var message = messageFilter(messages[j]);
if (!message || !message.isUnread()) {
continue;
}
res = postSlack(message);
if (!res.status) {
postError(message);
continue;
}
message.markRead();
}
thread.markRead();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment