Skip to content

Instantly share code, notes, and snippets.

@yoshimov
Last active September 13, 2016 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshimov/5647e03ee55c113b25d73927a325d6bf to your computer and use it in GitHub Desktop.
Save yoshimov/5647e03ee55c113b25d73927a325d6bf to your computer and use it in GitHub Desktop.
Notify train accident to Slack using Google Apps Script
// GAS Script for train daemon on Slack
// ScriptProperties:
// - trainUrl: JR line information web page URL
// - trainName: Name of JR line
// - slackHookUrl: Slack web hook URL
// - slackChannel: Channel name of Slack
function trainRetrieve() {
var url = PropertiesService.getScriptProperties().getProperty("trainUrl");
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
// get train text
var name = PropertiesService.getScriptProperties().getProperty("trainName");
var index = content.indexOf(name);
if (index < 0) {
return;
}
var point = content.substring(index);
// search second </tr>
index = point.indexOf("</tr>");
index = point.indexOf("</tr>", index + 5);
point = point.substring(0, index);
index = point.search(/class="cause">/);
if (index < 0) {
// no problem
return;
}
var cause = point.substring(index + 14);
cause = cause.substring(0, cause.indexOf("</"));
var t = point.substring(point.indexOf("time02") + 8);
t = t.substring(0, t.indexOf("</"));
var notify = false;
if (cause && !(cause == "&nbsp;")) {
notify = true;
Logger.log(cause);
}
if (notify) {
sendNotify(cause + " (<" + url + "|" + t + ">)");
}
}
function sendNotify(text) {
var channel = PropertiesService.getScriptProperties().getProperty("slackChannel");
var url = PropertiesService.getScriptProperties().getProperty("slackHookUrl");
var payload = {"channel": "#" + channel, "username": "train daemon", "text": text};
var params = {"method": "POST", "payload": JSON.stringify(payload)};
var res = UrlFetchApp.fetch(url, params);
Logger.log(text);
if (res) {
return true;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment