简体   繁体   中英

Creating dialogs programmatically from JSON file

I am using the Microsoft Bot Framework with Node.js. I have a config file that looks like the following.

{
  "server": {
    "port": 3978
  },
  "dialogs": {
    "default": {
      "text": "This is some sample text.",
      "actions": [
        {
          "title": "Button 1",
          "value": "Action 1"
        },
        {
          "title": "Button 2",
          "value": "Action 2"
        }
      ]
    },
    "hello": {
      "text": "hello",
      "matches": "^hello$"
    },
    "asdf": {
      "text": "asdf",
      "matches": "^asdf$"
    },
    "goodbye": {
      "text": "goodbye",
      "matches": "^goodbye$"
    }
  }
}

I want to use a for loop to read through the dialogs and create them so that they respond with the text value and have the trigger action of the matches value.

For example, the bot responds hello to the input of hello , asdf to the input of asdf , and goodbye to the input of goodbye .

The function I have written in an attempt to solve this looks like this.

var create = function(bot, _config) {
  var config = JSON.parse(JSON.stringify(_config));

  // Create dialogs from config
  var keys = Object.keys(config.dialogs);
  for(var i = 0; i < keys.length; i++) {
    var dialogName = keys[i];
    var dialog = config.dialogs[dialogName];
    // Skip over default dialog
    if(dialogName == "default") continue;
    // Create other dialogs
    bot.dialog(dialogName, function(session) {
      var text = dialog.text;
      session.endDialog(text);
    }).triggerAction({
      matches: new RegExp(dialog.matches, "i")
    });
  } 
}

When I run this, the bot responds with goodbye to the inputs of hello , asdf , and goodbye . However, the console shows that the correct dialogs are being called when they are supposed to. Even when I call the hello dialog by using session.beginDialog('hello'); , the bot returns goodbye .

What seems to be causing the problem here?

It's a common “gotchas” of var in javascript. replace var to let should fix your issue.

The issue similar with

 for (var i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 100 * i); } 

The root cause is var is function-scoped and let is block-scoped. You can refer to https://www.typescriptlang.org/docs/handbook/variable-declarations.html for details.

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