Skip to content

Instantly share code, notes, and snippets.

@matthiask
Last active November 26, 2016 10:58
Show Gist options
  • Save matthiask/ce2408f248e765bf6c26466a1372002d to your computer and use it in GitHub Desktop.
Save matthiask/ce2408f248e765bf6c26466a1372002d to your computer and use it in GitHub Desktop.
Slack Bot
const Botkit = require('botkit');
const request = require('superagent');
const controller = Botkit.slackbot();
// Slack Bot starten; und unendlich viele Wieder-Verbindungen zulassen
controller.spawn({
token: process.env.SLACK_BOT_TOKEN,
retry: Infinity,
}).startRTM(function (err, bot, payload) {
if (!err) return;
console.log(err);
throw new Error('Unable to connect to Slack');
});
// Der Bot ist nett, und begrüsst alle, die "hey" in den Channel schreiben
// unter Angabe ihres Nicknames. Der Nickname muss mit der API Methode
// "users.info" erst noch abgeholt werden"
controller.hears(
['hey'],
['ambient'],
function (bot, message) {
bot.api.users.info(
{user: message.user},
function(error, response) {
bot.reply(message, `${response.user.name} hey!`);
}
);
}
);
// Direkte Mitteilungen an den Bot, entweder per @bot im Channel oder per
// DM werden vom Bot immer beantwortet (ausser es gibt einen Crash)
controller.hears(
['.*'],
['direct_message', 'direct_mention'],
function (bot, message) {
console.log(message);
// How are you?
if (/how.*you/im.test(message.text)) {
bot.reply(message, 'Well enough, thank you very much!');
// cargo 8038 -- zeige nächste Cargotram-Daten für 8038 an
} else if (/cargo \d{4}/.test(message.text)) {
let match = /cargo (\d{4})/.exec(message.text),
zip = match && match[1];
if (zip) {
request
.get('http://openerz.herokuapp.com/api/calendar/cargotram.json')
.query({zip: zip, start: '2016-11-25', sort: 'date'})
.set('Accept', 'application/json')
.end(function (err, response) {
if (err || !response.ok) {
bot.reply(message, 'Something went wrong.');
} else {
let msg = response.body.result.map(data => data.date).join(', ');
bot.reply(message, `Cargotram is in ${zip} on ${msg}`);
}
});
}
// Unbekannte Frage
} else {
bot.reply(message, 'I\'m sorry, I did not understand.');
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment