watson-developer-cloud / botkit-middleware

A middleware to connect Watson Conversation Service to different chat channels using Botkit
https://www.npmjs.com/package/botkit-middleware-watson
Apache License 2.0
206 stars 254 forks source link

Watson Middleware "hear" does not support regex #20

Closed robertyates closed 7 years ago

robertyates commented 7 years ago

I was trying to understand why the following code wasn't working

slackController.changeEars(watsonMiddleware.hear);
slackController.hears(['.*'], ['direct_message', 'direct_mention', 'mention'], function(bot, message) {
    var reply = {

In debugging it, it appears that the middleware hears function doesn't support regex and I think it needs to so greater control over the selected intents can be done.

The change is fairly simple and I include it below. The code is taken from botkit's matching algorithm

hear: function(tests, message) {
      for (var t = 0; t < tests.length; t++) {
          if (message.watsonData && message.watsonData.intents) {
              // the pattern might be a string to match (including regular expression syntax)
              // or it might be a prebuilt regular expression
              var test = null;
              if (typeof(tests[t]) == 'string') {
                  try {
                      test = new RegExp(tests[t], 'i');
                  } catch (err) {
                      botkit.log('Error in regular expression: ' + tests[t] + ': ' + err);
                      return false;
                  }
                  if (!test) {
                      return false;
                  }
              } else {
                  test = tests[t];
              }

              for (var i = 0; i < message.watsonData.intents.length; i++) {
                if (match = message.watsonData.intents[i].intent.match(test) &&
                  message.watsonData.intents[i].confidence >= middleware.minimum_confidence) {
                    message.match = match;
                  return true;
                }
              }
            }
          }
      return false;
    },