Advertisement
bitttttten

derpy

Jun 30th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * and so Derpy becomes a real slack bot
  3.  *
  4.  * usage:
  5.  *
  6.  * // will test against any string
  7.  * Derpy.hook('~someWord', function(someWord) { // do something with someWord });
  8.  * Derpy.hook('watch game :id', function(id) { // do something with id });
  9.  *
  10.  * hook options:
  11.  *  :x      tests against an int
  12.  *  *x      tests against a string
  13.  *  ~x      tests against any word
  14.  *
  15.  */
  16. (function() {
  17.  
  18.     window.Derpy = (function() {
  19.  
  20.         // basic constructor
  21.         function D() {
  22.             D.routes = {};
  23.             D.intParam = /:\w+/g;
  24.             D.stringParam = /\*\w+/g;
  25.             D.anyParam = /~\w+/g;
  26.         }
  27.  
  28.         // add a hook to Derpy
  29.         D.prototype.hook = function(route, callback)
  30.         {
  31.             // escape backslashes
  32.             route = route.replace(/\//, "\\/");
  33.  
  34.             // convert custom int, string, and any params into nice regex
  35.             route = route.replace(D.intParam, '(\\d+)')
  36.                          .replace(D.stringParam, '(\\D+)')
  37.                          .replace(D.anyParam, '(\\S+)');
  38.  
  39.             // add to collection
  40.             // and add string boundaries around the regex so the hook
  41.             // has to match the exact length
  42.             return D.routes["^" + route + "$"] = callback;
  43.         };
  44.  
  45.         // check message against all known hooks
  46.         D.prototype.check = function(message) {
  47.  
  48.             // loop through all regexes
  49.             for(regexText in D.routes) {
  50.                 var regex = new RegExp(regexText);
  51.                 if (regex.test(message)) {
  52.                     var callback = D.routes[regexText];
  53.  
  54.                     // run the callback and bind the regex execution (minus the first
  55.                     // item in the array since this is the whole match)
  56.                     return callback.apply(window, regex.exec(message).slice(1));
  57.                 }
  58.             }
  59.  
  60.             // return null so it's possible to check if check() returns no matches
  61.             return null;
  62.         };
  63.  
  64.         return new D;
  65.  
  66.     })();
  67.  
  68. }).call(this);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement