From 05dbd6bccb58c4bd765ffaa1c117da001348e917 Mon Sep 17 00:00:00 2001 From: Eduard Nunes <eduardonunes2525@gmail.com> Date: Tue, 23 Jan 2018 10:50:50 -0200 Subject: [PATCH] Adding method concat ymls and appling code style - Code style with CoffeeLint Signed-off-by: Eduard Nunes <eduardonunes2525@gmail.com> Signed-off-by: Matheus Faria <matheus.sousa.faria@gmail.com> --- scripts/bot/index.coffee | 53 +++++++++++++++++++-------------- scripts/events/configure.coffee | 16 ++++++---- scripts/events/error.coffee | 2 +- scripts/events/respond.coffee | 4 +-- scripts/index.coffee | 5 +--- scripts/lib/common.coffee | 21 +++++++++---- 6 files changed, 60 insertions(+), 41 deletions(-) diff --git a/scripts/bot/index.coffee b/scripts/bot/index.coffee index 5a71474..77f7ecf 100644 --- a/scripts/bot/index.coffee +++ b/scripts/bot/index.coffee @@ -5,9 +5,11 @@ natural = require 'natural' lang = (process.env.HUBOT_LANG || 'en') if lang == "en" - PorterStemmer = require path.join '..','..','node_modules','natural','lib','natural','stemmers','porter_stemmer.js' + PorterStemmer = require path.join '..', '..', 'node_modules', 'natural', 'lib', + 'natural', 'stemmers', 'porter_stemmer.js' else - PorterStemmer = require path.join '..','..','node_modules','natural','lib','natural','stemmers','porter_stemmer_' + lang + '.js' + PorterStemmer = require path.join '..', '..', 'node_modules', 'natural', 'lib', + 'natural', 'stemmers', 'porter_stemmer_' + lang + '.js' debug_mode = ((process.env.HUBOT_NATURAL_DEBUG_MODE == 'true') || false) @@ -17,17 +19,18 @@ nodes = {} error_count = 0 err_nodes = 0 -{regexEscape, loadConfigfile} = require path.join '..', 'lib', 'common.coffee' -{getUserRoles, checkRole} = require path.join '..', 'lib', 'security.coffee' +{ regexEscape, loadConfigfile } = require path.join '..', 'lib', 'common.coffee' +{ getUserRoles, checkRole } = require path.join '..', 'lib', 'security.coffee' eventsPath = path.join __dirname, '..', 'events' for event in fs.readdirSync(eventsPath).sort() events[event.replace /\.coffee$/, ''] = require path.join eventsPath, event typing = (res, t) -> - res.robot.adapter.callMethod 'stream-notify-room', res.envelope.user.roomID+'/typing', res.robot.alias, t is true + res.robot.adapter.callMethod 'stream-notify-room', + res.envelope.user.roomID + '/typing', res.robot.alias, t is true -sendWithNaturalDelay = (msgs, elapsed=0) -> +sendWithNaturalDelay = (msgs, elapsed = 0) -> if !Array.isArray msgs msgs = [msgs] @@ -39,7 +42,8 @@ sendWithNaturalDelay = (msgs, elapsed=0) -> cb = msg.callback msg = msg.answer - delay = Math.min(Math.max((msg.length / keysPerSecond) * 1000 - elapsed, 0), maxResponseTimeInSeconds * 1000) + delay = Math.min(Math.max((msg.length / keysPerSecond) * 1000 - elapsed, 0), + maxResponseTimeInSeconds * 1000) typing @, true setTimeout => @@ -64,7 +68,7 @@ classifyInteraction = (interaction, classifier) -> if Array.isArray interaction.expect for doc in interaction.expect if interaction.multi == true - classifier.addDocument(doc, interaction.name+'|'+doc) + classifier.addDocument(doc, interaction.name + '|' + doc) else classifier.addDocument(doc, interaction.name) @@ -86,20 +90,20 @@ classifyInteraction = (interaction, classifier) -> interaction.classifier.train() setContext = (res, context) -> - key = 'context_'+res.envelope.room+'_'+res.envelope.user.id + key = 'context_' + res.envelope.room + '_' + res.envelope.user.id console.log 'set context', context res.robot.brain.set(key, context) getContext = (res) -> - key = 'context_'+res.envelope.room+'_'+res.envelope.user.id + key = 'context_' + res.envelope.room + '_' + res.envelope.user.id return res.robot.brain.get(key) isDebugMode = (res) -> - key = 'configure_debug-mode_'+res.envelope.room + key = 'configure_debug-mode_' + res.envelope.room return (res.robot.brain.get(key) == 'true') getDebugCount = (res) -> - key = 'configure_debug-count_'+res.envelope.room + key = 'configure_debug-count_' + res.envelope.room return if res.robot.brain.get(key) then res.robot.brain.get(key) - 1 else false buildClassificationDebugMsg = (res, classifications) -> @@ -123,7 +127,7 @@ buildClassificationDebugMsg = (res, classifications) -> return newMsg incErrors = (res) -> - key = 'errors_'+res.envelope.room+'_'+res.envelope.user.id + key = 'errors_' + res.envelope.room + '_' + res.envelope.user.id errors = res.robot.brain.get(key) or 0 errors++ console.log 'inc errors ', errors @@ -132,7 +136,7 @@ incErrors = (res) -> clearErrors = (res) -> console.log 'clear errors' - key = 'errors_'+res.envelope.room+'_'+res.envelope.user.id + key = 'errors_' + res.envelope.room + '_' + res.envelope.user.id res.robot.brain.set(key, 0) module.exports = (_config, robot) -> @@ -157,17 +161,20 @@ module.exports = (_config, robot) -> global.classifier = new natural.LogisticRegressionClassifier(PorterStemmer) for interaction in global.config.interactions - {name, event} = interaction + { name, event } = interaction global.nodes[name] = new events[event] interaction # count error nodes - if name.substr(0,5) == "error" + if name.substr(0, 5) == "error" err_nodes++ if interaction.level != 'context' classifyInteraction interaction, global.classifier + console.log('\tProcessing interaction: ' + name) + console.log 'Training Hubot (This could be take a while...)' global.classifier.train() + console.log '\n' - console.timeEnd 'Processing interactions (Done)' + console.timeEnd '\nProcessing interactions (Done)' global.train() @@ -193,12 +200,12 @@ module.exports = (_config, robot) -> if debugMode newMsg = buildClassificationDebugMsg(res, classifications) - robot.adapter.chatdriver.customMessage(newMsg); + robot.adapter.chatdriver.customMessage(newMsg) if classifications[0].value >= trust clearErrors res [node_name, sub_node_name] = classifications[0].label.split('|') - console.log({node_name, sub_node_name}) + console.log({ node_name, sub_node_name }) int = global.config.interactions.find (interaction) -> interaction.name is node_name if int.classifier? @@ -224,7 +231,7 @@ module.exports = (_config, robot) -> if not currentInteraction? clearErrors res - return console.log 'Invalid interaction ['+node_name+']' + return console.log 'Invalid interaction [' + node_name + ']' if currentInteraction.context == 'clear' setContext(res, undefined) @@ -236,13 +243,13 @@ module.exports = (_config, robot) -> robot.hear /(.+)/i, (res) -> res.sendWithNaturalDelay = sendWithNaturalDelay.bind(res) - msg = res.match[0].replace res.robot.name+' ', '' + msg = res.match[0].replace res.robot.name + ' ', '' msg = msg.replace(/^\s+/, '') msg = msg.replace(/\s+&/, '') # check if robot should respond - if res.envelope.user.roomType in ['c','p'] + if res.envelope.user.roomType in ['c', 'p'] if (res.message.text.match new RegExp('\\b' + res.robot.name + '\\b', 'i')) or (res.message.text.match new RegExp('\\b' + res.robot.alias + '\\b', 'i')) processMessage res, msg # TODO: Add engaged user conversation recognition/tracking - else if res.envelope.user.roomType in ['d','l'] + else if res.envelope.user.roomType in ['d', 'l'] processMessage res, msg diff --git a/scripts/events/configure.coffee b/scripts/events/configure.coffee index 74621f6..e62226f 100644 --- a/scripts/events/configure.coffee +++ b/scripts/events/configure.coffee @@ -1,8 +1,11 @@ +require 'coffeescript/register' + path = require 'path' natural = require 'natural' -{msgVariables, stringElseRandomKey, loadConfigfile, getConfigFilePath} = require '../lib/common' -{checkRole} = require path.join '..', 'lib', 'security.coffee' +{ msgVariables, stringElseRandomKey, loadConfigfile, getConfigFilePath } = require '../lib/common' +{ checkRole } = require '../lib/security.coffee' + answers = {} class configure @@ -18,21 +21,22 @@ class configure @act(msg) setVariable: (msg) -> - configurationBlock = msg.message.text.replace(msg.robot.name + ' ', '').split(' ')[-1..].toString() + configurationBlock = msg.message.text.replace(msg.robot.name + ' ', '') + .split(' ')[-1..].toString() configKeyValue = configurationBlock.split('=') configKey = configKeyValue[0] configValue = configKeyValue[1] - key = 'configure_'+configKey+'_'+msg.envelope.room + key = 'configure_' + configKey + '_' + msg.envelope.room msg.robot.brain.set(key, configValue) type = @interaction.type?.toLowerCase() or 'random' switch type when 'block' messages = @interaction.answer.map (line) -> - return msgVariables line, msg, {key:configKey, value: configValue} + return msgVariables line, msg, { key: configKey, value: configValue } msg.sendWithNaturalDelay messages when 'random' message = stringElseRandomKey @interaction.answer - message = msgVariables message, msg, {key:configKey, value: configValue} + message = msgVariables message, msg, { key: configKey, value: configValue } msg.sendWithNaturalDelay message return diff --git a/scripts/events/error.coffee b/scripts/events/error.coffee index 152d04c..ebc34da 100644 --- a/scripts/events/error.coffee +++ b/scripts/events/error.coffee @@ -1,7 +1,7 @@ path = require 'path' natural = require 'natural' -{msgVariables, stringElseRandomKey} = require path.join '..', 'lib', 'common.coffee' +{ msgVariables, stringElseRandomKey } = require path.join '..', 'lib', 'common.coffee' answers = {} class error diff --git a/scripts/events/respond.coffee b/scripts/events/respond.coffee index 462045e..18a7e14 100644 --- a/scripts/events/respond.coffee +++ b/scripts/events/respond.coffee @@ -1,7 +1,7 @@ path = require 'path' natural = require 'natural' -{msgVariables, stringElseRandomKey} = require path.join '..', 'lib', 'common.coffee' +{ msgVariables, stringElseRandomKey } = require path.join '..', 'lib', 'common.coffee' answers = {} livechat_department = (process.env.LIVECHAT_DEPARTMENT_ID || null ) @@ -27,7 +27,7 @@ class respond @livechatTransfer(msg, 3000, lc_dept, offline_message, type) - livechatTransfer: (msg, delay=3000, lc_dept, offline_message, type) -> + livechatTransfer: (msg, delay = 3000, lc_dept, offline_message, type) -> setTimeout((-> msg.robot.adapter.callMethod('livechat:transfer', roomId: msg.envelope.room departmentId: lc_dept diff --git a/scripts/index.coffee b/scripts/index.coffee index fd66a27..c695a41 100644 --- a/scripts/index.coffee +++ b/scripts/index.coffee @@ -1,9 +1,6 @@ require 'coffeescript/register' -path = require 'path' -fs = require 'fs' - -{loadConfigfile, getConfigFilePath} = require './lib/common' +{ loadConfigfile, getConfigFilePath } = require './lib/common' chatbot = require './bot/index' try diff --git a/scripts/lib/common.coffee b/scripts/lib/common.coffee index e46e0b4..cf26951 100644 --- a/scripts/lib/common.coffee +++ b/scripts/lib/common.coffee @@ -25,11 +25,22 @@ getYAMLFiles = (filepath) -> dataFiles = [] if listFile.length > 0 dataFiles = listFile.map (filename) -> - return yaml.safeLoad fs.readFileSync filepath+'/'+filename, 'utf8' + return yaml.safeLoad fs.readFileSync filepath + '/' + filename, 'utf8' else - console.error('The directory: '+ filepath + ' is empty.') + console.error('The directory: ' + filepath + ' is empty.') return dataFiles +concatYAMLFiles = (dataFiles) -> + mindBot = {} + if dataFiles.length > 0 + mindBot = { trust: dataFiles[0].trust, interactions: [] } + dataFiles.forEach (element) -> + mindBot.trust = Math.min(mindBot.trust, element.trust) + mindBot.interactions = mindBot.interactions.concat element.interactions + else + console.error('Data files is empty.') + return mindBot + common.regexEscape = (string) -> #http://stackoverflow.com/a/6969486 string.replace /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&" @@ -43,12 +54,12 @@ common.loadConfigfile = (filepath) -> if fs.lstatSync(filepath).isFile() return yaml.safeLoad fs.readFileSync filepath, 'utf8' else if fs.lstatSync(filepath).isDirectory() - # Return array with ymls files data yamlFiles = getYAMLFiles(filepath) - console.log(yamlFiles) + return concatYAMLFiles(yamlFiles) catch err console.error "An error occurred while trying to load bot's config." console.error err - throw "Error on loading YAML file " + filepath + errorMessage = "Error on loading YAML file " + filepath + throw errorMessage module.exports = common -- GitLab