Skip to content

Instantly share code, notes, and snippets.

@hoppula
Created December 19, 2011 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoppula/1498571 to your computer and use it in GitHub Desktop.
Save hoppula/1498571 to your computer and use it in GitHub Desktop.
Simple chatbot using multimethod.js
var multimethod = require('multimethod');
var _ = require('underscore');
// expected message format: {from: String, text: String}
var Bot = function() {
this.regexps = {};
this.dispatcher = multimethod().dispatch(function(message) {
var regexp = _.find(this.regexps, function(regexp, key) {
return regexp.test(message.text);
});
if (regexp) return regexp.toString();
});
};
Bot.prototype.listen = function(message) {
return this.dispatcher(message);
};
Bot.prototype.respond = function(condition, fn) {
var key = condition.toString();
this.regexps[key] = condition;
this.dispatcher.when(key, fn);
}
var myBot = new Bot();
myBot.respond(/hello/i, function(message) {
console.log( "Hello to you too "+ message.from +" :)" );
});
myBot.respond(/now\?/, function(message) {
console.log( message.from +", current time is: "+ new Date().toString() );
});
myBot.listen( {from: "Adam", text: "Hello man, how are you?"} );
myBot.listen( {from: "Boris", text: "now?"} );
myBot.listen( {from: "Cedric", text: "This should not match anything..."} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment