hubot-vvs
Version:
Ask your hubot to tell you when your VVS- train from a location in a given direction departs.
64 lines (56 loc) • 3.42 kB
JavaScript
;
const got = require('got');
module.exports = (robot) => {
robot.hear(/vvs from (.*) to (.*)/i, (msg) => {
let originData = `https://efa-api.asw.io/api/v1/station/?format=json&search=${msg.match[1]}`;
let destinationData = `https://efa-api.asw.io/api/v1/station/?format=json&search=${msg.match[2]}`;
var originUppercase = msg.match[1].charAt(0).toUpperCase() + msg.match[1].slice(1); // We need the first character to be a uppercase character
var destinationUppercase = msg.match[2].charAt(0).toUpperCase() + msg.match[2].slice(1); // We need the first character to be a uppercase character
var correctOrigin = got(originData, { json: true }).then((res) => {
for (var i = 0; i < res.body.length; i++) {
if (res.body[i].fullName === originUppercase) {
return res.body[i];
}
}
badName(msg.match[1], msg); // There is no such station as mentioned in the first argument
});
var correctDestination = got(destinationData, { json: true }).then((res) => {
for (var i = 0; i < res.body.length; i++) {
if (res.body[i].fullName === destinationUppercase) {
return res.body[i];
}
}
badName(msg.match[2], msg); // There is no such station as mentioned in the second argument
});
Promise.all([correctOrigin, correctDestination]).then((places) => { // Wait until we received data from the api
// places[0] is the json object of the origin that we got from the api
// places[1] is the json object of the destination that we got from the api
let originID = places[0].stationId; // only the id is important
got(`https://efa-api.asw.io/api/v1/station/${originID}/departures/?format=json`, { json: true }).then((res) => {
let count = 0;
for (var i = 0; i < res.body.length; i++) {
if (res.body[i].direction === destinationUppercase && count <= 1) { // It's true if the answer from the api has a entry which leads us to our desired destination
count ++;
let name = res.body[i].number;
let hour = res.body[i].departureTime.hour;
let minute = res.body[i].departureTime.minute;
if (minute < 10) {
minute = '0' + minute;
}
msg.send(`The ${name} from ${originUppercase} to ${destinationUppercase} leaves at ${hour}:${minute}`);
if (count > 1) { // do it two times only even if there are more results
return;
}
}
}
// If we reach this point there is no train going from our origin to this destination or it's not the last station -> we can't check whether the train goes by a station (yet)
msg.send(`There is no train going from ${originUppercase} to ${destinationUppercase}... Please try again!`);
return;
});
});
});
};
function badName (data, msg) {
msg.send(`Sorry I couldn't find ${data}.\nPlease check your spelling and take care about the case sensitivity.\nAlso make sure to write the names exactly as the VVS wrote them (e.g.: \"Marbach (N)\" not just \"Marbach\").`);
return;
}