Search code examples
javascriptazurevariablesbotsbotframework

JavaScript variable assignment in Azure Bot


I'm creating a bot using Azure BotBuilder and JavaScript and am having the following issue.

I don't know how to capture the value for a button that is pressed in the chat window. In the code below, the 'startOrderCoffee' bot.dialog presents the user with three options for coffees (see pic). When a selection is made by clicking a button, the selection is returned as a message. From the pic, if the user clicks 'Drip coffee', then 'Drip' is shown in the chat window.

What I don't know is how to capture the message value and return that response to the next function. In this case, the button is generated as part of the 'welcomeCard' object and is generated in the chat window via the following session.send() function.

Normally, the results.response option in the second function would capture the previous user input. However, it isn't working here. I've created variables, but it's the assignment that I don't know how to do. Can someone help me understand how to do this?

Coffee buttons and message/error output

// Dialog for ordering a coffee
bot.dialog('startOrderCoffee', [
function (session, args, next) {
    if (!args.continueOrder) {
        session.userData.cart = [];
        session.send("At anytime you can say 'cancel order', 'view cart', or 'checkout'.")
    }
    welcomeCard = new builder.HeroCard(session)
        .title('What kind of coffee would you like?')
        .buttons([
            builder.CardAction.imBack(session, "Drip", "Drip coffee"),
            builder.CardAction.imBack(session, "Espresso", "Espresso coffee"),
            builder.CardAction.imBack(session, "Mocha", "Mocha")
        ]);
    session.send(new builder.Message(session).addAttachment(welcomeCard));
},
function (session, results) {
    session.beginDialog('add' + results.response);

Solution

  • You are trying to do something that is already packaged and working, called Prompts.

    In particular, what you are doing should be coded with a prompt.choice: see doc here

    Sample:

    var salesData = {
        "west": {
            units: 200,
            total: "$6,000"
        },
        "central": {
            units: 100,
            total: "$3,000"
        },
        "east": {
            units: 300,
            total: "$9,000"
        }
    };
    
    bot.dialog('getSalesData', [
        function (session) {
            builder.Prompts.choice(session, "Which region would you like sales for?", salesData); 
        },
        function (session, results) {
            if (results.response) {
                var region = salesData[results.response.entity];
                session.send(`We sold ${region.units} units for a total of ${region.total}.`); 
            } else {
                session.send("OK");
            }
        }
    ]);