prisme-flow
Version:
prisme platform flow engine
84 lines (70 loc) • 2.29 kB
JavaScript
/**
* Created by prisme.io on 09/06/2017.
*/
var _ = require('underscore')
var NplMatcher = require('./lib/npl-matcher')
var clc = require('cli-color')
var prettyjson = require('prettyjson')
var green = clc.greenBright
var white = clc.white
var grey = clc.blackBright
module.exports = function (RED) {
function BotListen (config) {
RED.nodes.createNode(this, config)
var node = this
this.rules = config.rules
this.showdebug = config.showdebug
this.on('input', function (msg) {
var originalMessage = msg.originalMessage
var chatContext = msg.chat()
var rules = node.rules
var debug = node.showdebug
// do nothing if it's not a chat message
if (originalMessage == null || _.isEmpty(rules)) {
return
}
var output = []
var matched = false
// parse incoming message
var message = msg.payload.content
var terms = NplMatcher.parseSentence(message)
// debug the terms
if (debug) {
// eslint-disable-next-line no-console
console.log('')
// eslint-disable-next-line no-console
console.log(grey('------ Sentence Analysis ----------------'))
// eslint-disable-next-line no-console
console.log(green('Message:'), white(message))
try {
// eslint-disable-next-line no-console
console.log(prettyjson.render(terms._terms))
} catch (e) {
// pretty json may breaks
}
}
rules.forEach(function (rule) {
var matchedRule = null
if (!matched && rule === '*') {
// mark as matched, only the first wins
matched = true
output.push(msg)
} else if (!matched && (matchedRule = NplMatcher.matchRule(terms, new NplMatcher.MatchRules(rule.split(',')))) != null) {
// mark as matched, only the first wins
matched = true
// store variables
matchedRule.forEach(function (rule) {
if (!_.isEmpty(rule.variable)) {
chatContext.set(rule.variable, rule.value)
}
})
output.push(msg)
} else {
output.push(null)
}
})
node.send(output)
})
}
RED.nodes.registerType('bot-listen', BotListen)
}