Last active
November 19, 2019 06:32
-
-
Save kdmsnr/8856f570183ac0bb96c6319481e1626c to your computer and use it in GitHub Desktop.
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
// inspired from: | |
// https://gist.github.com/masuidrive/0bea937bcaf12bc94e7fba8acf13382a | |
// ## Go to https://api.slack.com/ | |
// * Create your app. | |
// * Create "Bot User". | |
// * Go to "OAuth Tokens & Redirect URLs" and copy the Access Token. | |
// * Set the permission of "chat:write:bot" to the bot. | |
// ## Go to https://www.google.com/script/start/ | |
// * Install a library: https://github.com/soundTricker/SlackApp | |
// * Create your script and paste this script. | |
// * Paste the slack Access Token. | |
// * Publish as a web application and copy the URL. | |
// ## Go to https://api.slack.com/ | |
// * Set the URL of the script. | |
var slack_token = 'xoxp-YOUR TOKEN HERE'; | |
function translateText(text) { | |
var translatedText = LanguageApp.translate(text, "ja", "en"); | |
translatedText = translatedText.replace(/<@\s+/g, '<@'); // username | |
translatedText = translatedText.replace(/:\s(\w+?):/g, ':$1:'); // emoji | |
translatedText = translatedText.replace(/<#\s+(\w+?)\s+\|\s+(\w+?)>/g, '<#$1|$2>'); // channel | |
return translatedText; | |
} | |
function post_to_slack(channel, message, thread_ts) { | |
var slackApp = SlackApp.create(slack_token); | |
var options = {link_names: true}; | |
if (thread_ts) { | |
options["thread_ts"] = thread_ts; | |
} | |
slackApp.chatPostMessage(channel, message, options); | |
} | |
function doPost(e) { | |
var params = JSON.parse(e.postData.getDataAsString()); | |
Logger.log(params); | |
var res = ContentService.createTextOutput(); | |
res.setMimeType(ContentService.MimeType.JSON); | |
// challenge | |
if (params.type == "url_verification") { | |
res.setContent(JSON.stringify(params)); | |
return res; | |
} | |
var ev = params.event; | |
if (ev.type == "app_mention") { | |
var originalText = ev.text; | |
params.authed_users.forEach(function(user){ | |
originalText = originalText.replace("<@" + user + ">", '') | |
}); | |
var translatedText = translateText(originalText); | |
post_to_slack(ev.channel, translatedText, ev.thread_ts); | |
} | |
return ""; // FIXME | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment