Last active
July 28, 2016 11:19
-
-
Save ymkjp/04d6a100948d85d617e3 to your computer and use it in GitHub Desktop.
Google App Script: Gmail_Label_Chatwork_Notifier
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
/** | |
# ChatWorkでの事前準備 | |
1. 発言させたいルームにBOTを追加する | |
# Gmailでの事前準備 | |
1. "#GAS/ENQ", "#GAS/DEQ" のラベルを作成しておく | |
2. 通知対象のメールに "#GAS/ENQ" のラベルが付加されるようにフィルタの設定をしておく | |
*/ | |
var CHATWORK_TOKEN = "__TOKEN__", | |
CHATWORK_ROOM_ID = "__RID__", | |
CONTENT_MAX_LINE = 1, | |
REPLY_TO_UIDS = [ | |
687933, | |
], | |
LABEL_ENQ = "#GAS/ENQ", | |
LABEL_DEQ = "#GAS/DEQ"; | |
function Gmail_Label_Chatwork_Notifier() { | |
var targetLabel, notifiedLabel, threads, thread, messages; | |
targetLabel = GmailApp.getUserLabelByName(LABEL_ENQ); | |
notifiedLabel = GmailApp.getUserLabelByName(LABEL_DEQ); | |
threads = targetLabel.getThreads().reverse(); | |
for (var i in threads) { | |
thread = threads[i]; | |
messages = thread.getMessages().reverse(); | |
for (var j in messages) { | |
notify(messages[j]); | |
} | |
thread.removeLabel(targetLabel).addLabel(notifiedLabel); | |
} | |
Logger.log("DONE"); | |
} | |
function notify(message) { | |
var cw = ChatWorkClient.factory({token: CHATWORK_TOKEN}); | |
try { | |
cw.sendMessage({room_id: CHATWORK_ROOM_ID, body: format(message)}); | |
} catch (e) { | |
Logger.log(e.message); | |
throw new e; | |
} | |
} | |
function format(message) { | |
var replyHeader, content; | |
replyHeader = generateReplyTargets(REPLY_TO_UIDS); | |
content = generateContent(message) | |
return replyHeader.length > 0 ? replyHeader + "\n" + content : content; | |
} | |
function generateContent(message) { | |
var subject = message.getSubject(), | |
body = message.getPlainBody().trim(), | |
postLength = 0; | |
for (var i = 0; i < CONTENT_MAX_LINE + 1; ++i) { | |
postLength = body.indexOf("\n", postLength + 1); | |
} | |
if (postLength !== -1 && postLength < body.length) { | |
body = body.substr(0, postLength).trim(); | |
body = body + "\n..."; | |
} | |
return "[info][title]" + subject + "[/title]" + body + "[/info]"; | |
} | |
function generateReplyTargets(uid_list) { | |
var body = ''; | |
for (var i = 0; i < uid_list.length; ++i) { | |
body = body + '[To:' + uid_list[i] + '] '; | |
} | |
return body.trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment