Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * and so Derpy becomes a real slack bot
- *
- * usage:
- *
- * // will test against any string
- * Derpy.hook('~someWord', function(someWord) { // do something with someWord });
- * Derpy.hook('watch game :id', function(id) { // do something with id });
- *
- * hook options:
- * :x tests against an int
- * *x tests against a string
- * ~x tests against any word
- *
- */
- (function() {
- window.Derpy = (function() {
- // basic constructor
- function D() {
- D.routes = {};
- D.intParam = /:\w+/g;
- D.stringParam = /\*\w+/g;
- D.anyParam = /~\w+/g;
- }
- // add a hook to Derpy
- D.prototype.hook = function(route, callback)
- {
- // escape backslashes
- route = route.replace(/\//, "\\/");
- // convert custom int, string, and any params into nice regex
- route = route.replace(D.intParam, '(\\d+)')
- .replace(D.stringParam, '(\\D+)')
- .replace(D.anyParam, '(\\S+)');
- // add to collection
- // and add string boundaries around the regex so the hook
- // has to match the exact length
- return D.routes["^" + route + "$"] = callback;
- };
- // check message against all known hooks
- D.prototype.check = function(message) {
- // loop through all regexes
- for(regexText in D.routes) {
- var regex = new RegExp(regexText);
- if (regex.test(message)) {
- var callback = D.routes[regexText];
- // run the callback and bind the regex execution (minus the first
- // item in the array since this is the whole match)
- return callback.apply(window, regex.exec(message).slice(1));
- }
- }
- // return null so it's possible to check if check() returns no matches
- return null;
- };
- return new D;
- })();
- }).call(this);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement