slack-phrase-command/index.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2014-08-09 22:49:22 +00:00
var fs = require('fs'),
_ = require('lodash');
2014-08-09 22:20:03 +00:00
2014-08-09 21:57:42 +00:00
module.exports = function(configuration) {
2014-08-09 22:20:03 +00:00
var listenOn = (function(name) {
switch (typeof name) {
case "string":
return [name];
case "object":
if (name instanceof Array) {
return name;
}
//fallthrough
default:
return ["phrase"];
}
})(configuration.command);
2014-08-09 22:49:22 +00:00
var phrases = configuration.phrases;
phrases = (typeof phrases === "object" && phrases instanceof Array) ? phrases : [];
if (typeof configuration.phraseFile === "string") {
phrases = _.compact(_.union(phrases, fs.readFileSync(configuration.phraseFile).split("\n")));
}
function phrase() {
if (phrases.length)
return phrases[Math.floor(Math.random() * phrases.length)];
return "This phrase command has not been properly configured."
}
2014-08-09 22:20:03 +00:00
function handler(slack) {
try {
2014-08-09 22:49:22 +00:00
slack.replyUser(phrase());
2014-08-09 22:20:03 +00:00
} catch (e) {
slack.error(e.toString());
}
}
2014-08-09 21:57:42 +00:00
return function(ee) {
2014-08-09 22:20:03 +00:00
_.forEach(listenOn, function(commandName) {
ee.on(commandName, handler);
2014-08-09 21:57:42 +00:00
});
};
};