imubot
Version:
A simple helpful bot.
114 lines (103 loc) • 3.56 kB
JavaScript
(function() {
var Listener, Middleware, TextListener, TextMessage, async, inspect,
extend = function(child, parent) {
for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
inspect = require('util').inspect;
async = require('async');
TextMessage = require('./message').TextMessage;
Middleware = require('./middleware');
Listener = (function() {
function Listener(bot, matcher, options, callback) {
this.bot = bot;
this.matcher = matcher;
this.options = options;
this.callback = callback;
if (this.matcher == null) {
throw new Error("Missing a matcher for Listener");
}
if (this.callback == null) {
this.callback = this.options;
this.options = {};
}
if (this.options.id == null) {
this.options.id = null;
}
if ((this.callback == null) || typeof this.callback !== 'function') {
throw new Error("Missing a callback for Listener");
}
}
Listener.prototype.call = function(message, middleware, cb) {
var allDone, executeListener, match, response;
if ((cb == null) && typeof middleware === 'function') {
cb = middleware;
middleware = void 0;
}
if (middleware == null) {
middleware = new Middleware(this.bot);
}
if (match = this.matcher(message)) {
if (this.regex) {
this.bot.logger.debug("Message '" + message + "' matched regex /" + (inspect(this.regex)) + "/; listener.options = " + (inspect(this.options)));
}
executeListener = (function(_this) {
return function(context, done) {
var err;
message.message || _this.bot.logger.debug("Executing listener callback for Message '" + message + "'");
try {
_this.callback(context.response);
} catch (error) {
err = error;
_this.bot.emit('error', err, context.response);
}
return done();
};
})(this);
allDone = function() {
if (cb != null) {
return Middleware.ticker(function() {
return cb(true);
});
}
};
response = new this.bot.Response(this.bot, message, match);
middleware.execute({
listener: this,
response: response
}, executeListener, allDone);
return true;
} else {
if (cb != null) {
process.nextTick(function() {
return cb(false);
});
}
return false;
}
};
return Listener;
})();
TextListener = (function(superClass) {
extend(TextListener, superClass);
function TextListener(bot, regex, options, callback) {
this.bot = bot;
this.regex = regex;
this.options = options;
this.callback = callback;
this.matcher = (function(_this) {
return function(message) {
if (message instanceof TextMessage) {
return message.match(_this.regex);
}
};
})(this);
TextListener.__super__.constructor.call(this, this.bot, this.matcher, this.options, this.callback);
}
return TextListener;
})(Listener);
module.exports = {
Listener: Listener,
TextListener: TextListener
};
}).call(this);