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

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

What could be causing the React-Router-Dom Outlet to not show the component?

I am working on a component that houses four different components. const ProtectedRoute = () => { return ( <> <Header /> <div className='flex h-screen overflow-hidden'> <div className="md:block h ...

Struggling to find the element using Selenium

Hey there, I'm struggling with identifying the input id button in my HTML code while using Selenium through Java. The error message says it's unable to locate the element. Can anyone provide some guidance? I've already tried using xpath and ...

What is the process for translating symbols in a URL or text into hexadecimal characters? (e.g. changing = to %3D)

Currently, my script in use is extracting variables from URL parameters using jQuery. The value it retrieves happens to be a URL. For instance, if the URL is as follows: http://localhost/index.html?url=http://www.example.com/index.php?something=some the ...

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

JavaScript functions are not being triggered when the submit button is clicked

I am facing an issue where the form buttons are not triggering functions in my React application. The post request is being made using Axios. Could this be related to the structure of my components? Or perhaps it has something to do with file naming conven ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

How to prevent click events and still enable scrolling within a DIV using CSS/JS

Basically, I am looking to enable scrolling within a DIV while also disabling click events. Any suggestions on how this can be achieved? Appreciate any help! ...

Is an input field/text area necessary for the traditional copy to clipboard feature?

I needed to copy a section of text enclosed within an anchor tag to the clipboard. Following suggestions found online, I implemented the code below: HTML: <div class="organizer-link"> <i class="fa fa-link" id="copylink"></i> <a href ...

Anyone have any (placeholder) fetch URL parameters that require some time to resolve?

Can anyone share any fetch URL parameters that result in a loading time of roughly 5 seconds or longer for the promise to resolve when using fetch(urlArgument);? I'm eager to experiment and learn more. ...

Strategies for retrieving the latest content from a CMS while utilizing getStaticProps

After fetching blog content from the CMS within getStaticProps, I noticed that updates made to the blog in the CMS are not reflected because getStaticProps only fetches data during build time. Is there a way to update the data without rebuilding? I typica ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

Eliminate repetitive elements within an array of objects

Is there a way to eliminate duplicate values in an object array using Javascript? 0: {d: “2021/01/19”, color: “#009988"} 1: {d: “2021/01/19”, color: “#CC3311"} 2: {d: “2021/01/19”, color: “#009988"} 3: {d: “2021/01/19”, ...

Unusual shift in the modal's behavior occurs when the parent component's style.transform is applied

I have encountered an unusual issue with a modal's appearance and functionality. The modal is designed to enlarge images sent in a chat, with the chat upload preview div serving as the parent element and the modal as the child element. This strange be ...