Question

Hi i'm trying to write a addon script for hubot. I seem to have a problem with scoping. The reference of "msg" inside the fork callback is undefined, i don't seem to get any variables in the callback.

I've also had this same issue with the built-in jira-issues.coffee! Yesterday in that script the jiraUrl was undefined in the callback. This morning it was working again and now it's stopped working again (after i restarted hubot). I've never even modified it.

Has anyone experienced anything like this?

githubApi = require("node-github")

module.exports = (robot) ->
  github = new githubApi { "version": "3.0.0" }
  github.authenticate { "type":"basic", "username":process.env.HUBOT_GITHUB_USER, "password":process.env.HUBOT_GITHUB_P
ASSWORD }
  robot.respond /kickstart\s(\S+)/i, (msg) ->
    name = msg.match[1]
    msg.send name
    base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com'
    github.repos.fork {"user":"Raven", "repo":"Raven","org":"codedemos"}, (err,data) ->
      if err
        msg.send "error :("
      else
        msg.send "Fork Complete..."

it compiles to

// Generated by CoffeeScript 1.6.3
(function() {
  var githubApi;

  githubApi = require("node-github");

  module.exports = function(robot) {
    var github;
    github = new githubApi({
      "version": "3.0.0"
    });
    github.authenticate({
      "type": "basic",
      "username": process.env.HUBOT_GITHUB_USER,
      "password": process.env.HUBOT_GITHUB_PASSWORD
    });
    return robot.respond(/kickstart\s(\S+)/i, function(msg) {
      var base_url, name;
      name = msg.match[1];
      msg.send(name);
      base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com';
      return github.repos.fork({
        "user": "Raven",
        "repo": "Raven",
        "org": "codedemos"
      }, function(err, data) {
        var id;
        if (err) {
          return msg.send("error :(");
        } else {
          return id = data.id;
        }
      });
    });
  };

  msg.send("Fork Complete...");

}).call(this);

Which looks fine yet running it yields:

ReferenceError: msg is not defined
  at Object.<anonymous> (/opt/kbot/scripts/kickstart.coffee:48:2, <js>:36:3)
  at Object.<anonymous> (/opt/kbot/scripts/kickstart.coffee:33:1, <js>:38:4)
  at Module._compile (module.js:456:26)
Was it helpful?

Solution

It's almost certainly a whitespace problem with that last line. Triple-check you are using consistent indentation in the whole file and make sure your file has a final newline after msg.send "Fork Complete...". I copied and pasted your coffeescript code and compiled it to javascript and the last msg.send line gets correctly put inside the proper function, vs your js above which has that line in the wrong place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top