简体   繁体   中英

How to send msg in scripts that locates without scripts dir in hubot?

I'm beginner at node.js.
I want to do that when hubot hear expected message, evaluate and execute script that is not exist in scripts dir.

I wrote code below code, but I cannot send msg.

Error msg

[Thu Feb 16 2017 20:22:34 GMT+0900 (JST)] ERROR ReferenceError: msg is not defined

Where should I fix it to define msg?

hubot_dir/scripts/load_test.coffee

path = require('path')

module.exports = (robot) ->
  robot.hear /loadscript/i, (msg) ->
    script_name = "dynamictest.coffee"
    script_dir = path.resolve(__dirname, "../dynamicscripts")
    dynamictest = require(script_dir + "/" + script_name)
    robot.loadFile(script_dir, script_name)
    robot.emit "dynamic", {
      robot: robot,
      msg: msg
    }
    delete require.cache[script_dir + "/" + script_name]

hubot_dir/dynamicscripts/dynamictest.coffee

module.exports = (robot) ->
  robot.on "dynamic" , (dynamic) ->
    robot.logger.info "output log"
    msg.send "test"

When you call robot.emit , you are passing an object that contains the variable that you call msg (though the name is entirely arbitrary). This object is passed as the parameter named dynamic , therefore, in order to reference msg , you need to refer to it as dynamic.msg :

module.exports = (robot) ->
  robot.on "dynamic" , (dynamic) ->
    robot.logger.info "output log"
    dynamic.msg.send "test"

I should point out, however, that with the way your loadscript function is written, it will load an additional instance of dynamicscript.coffee every time you call it. For example, the first time you call loadscript , it will load the second file and send back 'test'. The second time, it will load the second file yet again, and you will get two responses that say 'test'. On the third time it will load again and you will receive three messages, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM