Created
October 26, 2011 14:16
-
-
Save marceldegraaf/1316486 to your computer and use it in GitHub Desktop.
Pull disruptions from the NS (Dutch Railways) API and send them to Campfire
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
# A way to interact with the NS (Dutch Railways) API | |
# | |
# To configure, add NS_API_EMAIL and NS_API_PASSWORD to your Heroku config with "heroku config:add" | |
# | |
# train disruptions <station> - Retrieve the list of disruptions near <station>. | |
# Please note: <station> can be a station code (e.g. 'asd') | |
# or (part of) a station name (e.g. 'Amsterdam Centraal') | |
# | |
disruptionPageRoot = 'http://www.ns.nl/storingen/index.form#' | |
module.exports = (robot) -> | |
robot.respond /train disruptions (.*)/i, (msg) -> | |
station = msg.match[1] | |
station.replace(/^\s+|\s+$/g, "") | |
findDisruptions msg, station, (list) -> | |
if list.Ongepland == undefined || list.Gepland == undefined | |
msg.send "Sorry, that didn't work. Perhaps the NS API is down or your credentials are wrong?" | |
return | |
# | |
# Unplanned disruptions | |
# | |
if list.Ongepland[0].Storing == undefined | |
msg.send "There are no unplanned disruptions around '#{station}'" | |
else | |
sendDisruptions list.Ongepland[0].Storing, msg, false | |
# | |
# Planned disruptions | |
# | |
if list.Gepland[0].Storing == undefined | |
msg.send "There are no planned maintenance disruptions around '#{station}'" | |
else | |
sendDisruptions list.Gepland[0].Storing, msg, true | |
findDisruptions = (msg, station, callback) -> | |
url = 'http://webservices.ns.nl/ns-api-storingen' | |
username = process.env.NS_API_EMAIL | |
password = process.env.NS_API_PASSWORD | |
auth = "Basic " + new Buffer(username + ':' + password).toString('base64') | |
xml2js = require 'xml2js' | |
parser = new xml2js.Parser({explicitArray: true}) | |
msg.http(url) | |
.header('Authorization', auth) | |
.query(station: station, actual: false, unplanned: false) | |
.get() (err, res, body) -> | |
parser.parseString body, (err, result) -> | |
callback result | |
sendDisruptions = (disruptions, msg, planned) -> | |
for disruption in disruptions | |
if planned | |
type = '' | |
urlInfix = 'werkzaamheden-' | |
else | |
type = ':warning:' | |
urlInfix = '' | |
output = [ | |
type, | |
disruption.Traject[0], | |
"(#{disruption.Reden[0]}).", | |
"More info: #{disruptionPageRoot}#{urlInfix}#{disruption.id[0]}" | |
] | |
msg.send output.join(' ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment