Created
December 19, 2011 19:48
-
-
Save hoppula/1498571 to your computer and use it in GitHub Desktop.
Simple chatbot using multimethod.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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