Initiating a conversation using a greeting in the Javascript bot framework

I am looking to initiate a multi-level, multiple choice dialog from the welcome message in the Bot Framework SDK using JavaScript. I have a main dialog (finalAnswerDialog) that utilizes LUIS for predicting intents, and a multi-level, multiple choice menu dialog (menuDialog) to assist users with navigating to specific intents. Despite my efforts, I have been encountering errors when trying to display the menu dialog from the beginning. Below is the code snippet:

dialogAndWelcomeBot

const { CardFactory } = require('botbuilder');
const { DialogBot } = require('./dialogBot');
const { ActivityHandler, MessageFactory } = require('botbuilder');
const { ActionTypes } = require('botframework-schema');
const { MenuDialog } = require('../dialogs/menuDialog');

class DialogAndWelcomeBot extends DialogBot {
    constructor(conversationState, userState, dialog) {
        super(conversationState, userState, dialog);
        this.onMembersAdded(async (context, next) => {
            const membersAdded = context.activity.membersAdded;
            for (let cnt = 0; cnt < membersAdded.length; cnt++) {
                if (membersAdded[cnt].id !== context.activity.recipient.id) {
                    await dialog.run(context, conversationState.createProperty('DialogState'));
                    await step.beginDialog('menuDialog');
                }
            }

            // By calling next() you ensure that the next BotHandler is run.
            await next();
        });
    }
}


module.exports.DialogAndWelcomeBot = DialogAndWelcomeBot;

menuDialog triggers finalAnswerDialog to handle LUIS calls at any stage

class MenuDialog extends ComponentDialog {
    constructor(finalAnswerDialog) {
        super('menuDialog');

        this.answered=true;
        this.addDialog(new TextPrompt(TEXT_PROMPT));
        this.addDialog(new TextPrompt(NAME_PROMPT));
        this.addDialog(new ChoicePrompt(CHOICE_PROMPT));
        this.addDialog(new ConfirmPrompt(CONFIRM_PROMPT));
        this.addDialog(finalAnswerDialog);

        this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
            this.firstQuestion.bind(this),
            this.secondQuestion.bind(this),
            this.thirdQuestion.bind(this),
            this.answerTheQuestion.bind(this),
            this.finalStep.bind(this)
        ]));
        
        this.initialDialogId = WATERFALL_DIALOG;
    }

finalAnswerDialog

class FinalAnswerDialog extends ComponentDialog {
    constructor(luisRecognizer) {
        super('finalAnswerDialog');

        if (!luisRecognizer) throw new Error('[MainDialog]: Missing parameter \'luisRecognizer\' is required');
        this.luisRecognizer = luisRecognizer;

        // Define the main dialog and its related components.
        // This is a sample "book a flight" dialog.
        this.addDialog(new TextPrompt('TextPrompt'));
        this.addDialog(new WaterfallDialog(MAIN_WATERFALL_DIALOG, [
                //this.initStep.bind(this),
                this.actStep.bind(this),

            ]));

        this.initialDialogId = MAIN_WATERFALL_DIALOG;
    }

    async run(turnContext, accessor) {
        const dialogSet = new DialogSet(accessor);
        dialogSet.add(this);

        const dialogContext = await dialogSet.createContext(turnContext);
        const results = await dialogContext.continueDialog();
        if (results.status === DialogTurnStatus.empty) {
            await dialogContext.beginDialog(this.id);
        }
    }

    async initStep(stepContext) {
        return await stepContext.prompt(TEXT_PROMPT, promptOptions);
    }

    async actStep(stepContext) {
        if (!this.luisRecognizer.isConfigured) {
            const messageText = 'NOTE: LUIS is not configured. To enable all capabilities, add `LuisAppId`, `LuisAPIKey` and `LuisAPIHostName` to the .env file.';
            await stepContext.context.sendActivity(messageText, null, InputHints.IgnoringInput);
            return await stepContext.next();
        }

        const luisResult = await this.luisRecognizer.executeLuisQuery(stepContext.context);
        let top_intent = LuisRecognizer.topIntent(luisResult)
        //let top_intent="contacto"
        console.log("intent predicted by Luis: " + top_intent)
        
        switch (top_intent) {
//SendActivity

index.js

const dialog = new FinalAnswerDialog(luisRecognizer);
const bot = new DialogAndWelcomeBot(conversationState, userState, dialog);

What steps can I take to successfully launch the menu dialog during the welcome sequence?

Answer №1

A specific dialogue, whether it be a menu or any other type, can indeed be initiated from the welcome code.

The crucial point to note here is to avoid using conversationUpdate in your bot code. Instead, you should send an event activity from the client and include code in your bot to handle the event.

If you want to add an activity as an event handler, check out this article on how to send a greeting message and address common issues.


Another approach would involve storing a mapping of user IDs and sessions, enabling you to use seesion.send to send a dialog to a particular user. In most cases, utilizing conversationUpdate is the recommended method.

Example Welcome Code:

bot.on('conversationUpdate', function(message) {
  if (message.membersAdded) {
    message.membersAdded.forEach(function(identity) {
      if (identity.id === message.address.bot.id) {
        var reply = new builder.Message()
          .address(message.address)
          .text("Welcome");
        bot.send(reply);
      }
    });
  }
});

To initiate a specific dialog, follow these steps:

bot.on('conversationUpdate', function (message) {
  if (message.membersAdded) {
    message.membersAdded.forEach(function (identity) {
      if (identity.id === message.address.bot.id) {
        bot.beginDialog(message.address, '/main');
      }
    });
  }
});

bot.dialog('/main', [
  function (session, args, next) {
    session.send("Glad you could join.");
    session.beginDialog('/next');
  }
]);

The above code encompasses both sending a welcome message and initiating a dialogue. You may also find a related discussion on Stack Overflow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

Issue with CornerstoneJs React restoreImageIdToolState causing annotations to fail to load automatically post-execution

Once this code is executed, I need the annotations to appear without having to hover over the cornerstoneViewport. const restore = () => { let element; const stack = { currentImageIdIndex: 0, imageIds, }; console.log(dico ...

Using React.js to establish a connection with a database

Can someone help me with connecting my reactjs to mysql? I have already installed mysql and followed the usual instructions, but I keep getting an error "TypeError: mysql.createConnection is not a function". Below are the codes I am working with. import ...

I made a request using the post type fetch to submit data to this form, but unfortunately, the server-side response returned

I encountered an issue where after sending the post type fetch to this form, I received 'undefined' on the server side. Here's the code snippet for my fetch request: const { text, id } = Data; fetch('http://localhost:3001/add' ...

What steps do I need to follow to upload an image file through Socket.IO?

For my school project, I am developing a chat application and facing a challenge with implementing an onClick event to trigger a function that utilizes socket-io-file-upload to prompt the user to select a file for upload. This functionality is detailed in ...

Tips for updating checked checkboxes in a php mysql database

When submitting an HTML form with a selected checkbox, update the values of the selected checkboxes in a MySQL database. For example: update enquires set status = '2' where id in (selected checkbox values) View the screenshot of the checkbox Vi ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

Tips for rotating individual letters within a sentence on popular web browsers, including Chrome

Can you make a sentence appear with each individual letter rotating and getting larger? This is my approach: I decided to split the sentence into separate span elements, one for each letter. Then I used CSS transform -webkit-transform to animate the lette ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...

Reduce the size of log messages in cypress

I am looking to shorten the cypress messages to a more concise string, for instance: Cypress log Transform to: -assert expected #buy-price-field to have value 17,169.00. Is there a way to achieve this? I have searched through the documentation but hav ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...

Load website content in real-time

My website requires dynamic content to be loaded on user interaction. When a user clicks certain elements on the page, information should be retrieved from a file located in the same directory as the webpage and displayed in a designated <div>. My u ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

Angular 7 features a table with multiple timers indicating the remaining time until expiration

I have a table with multiple rows where I need to display a timer showing the remaining time in days, hours, minutes, and seconds. After researching how to calculate the remaining time using this link, I found a solution that works well. I am calling the ...