Skip to content Skip to sidebar Skip to footer

How To Send A Message To Direct Line Chat Bot From The Ui Using Javascript

I'm developing a chat bot (v4 using MS Azure bot framework & QnAmaker), I've added a feature in that, i.e. while the users starts typing the questions, the bot will get prompt

Solution 1:

Here's a working demo that should get you started, using a similar method from the sample:

<!DOCTYPE html><htmllang="en-US"><head><title>Web Chat: Programmatic access to post activity</title><metaname="viewport"content="width=device-width, initial-scale=1.0" /><!--
      This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to pointing to Web Chat's MyGet feed:
      https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
    --><scriptsrc="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script><style>html,
        body {
            height: 100%;
        }

        body {
            margin: 0;
        }

        #webchat {
            height: 100%;
            width: 100%;
        }
    </style></head><body><divid="webchat"role="main"></div><script>
        (asyncfunction () {
            // In this demo, we are using Direct Line token from MockBot.// Your client code must provide either a secret or a token to talk to your bot.// Tokens are more secure. To learn about the differences between secrets and tokens// and to understand the risks associated with using secrets, visit https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0// We are creating the Web Chat store here so we can dispatch WEB_CHAT/SEND_MESSAGE action later.const store = window.WebChat.createStore();

            window.WebChat.renderWebChat(
                {
                    directLine: window.WebChat.createDirectLine({ token: '<your token>' }),
                    // We are passing our own version of Web Chat store.
                    store
                },
                document.getElementById('webchat')
            );

            document.querySelector('#webchat > *').focus();

// THIS IS THE IMPORTANT STUFFconst sendbox = document.querySelector("[aria-label='Sendbox']");

            functionremoveQuestions() {
                const questionDivs = document.querySelectorAll('.questions');
                    questionDivs.forEach((div) => {
                        div.remove();
                    })
            }

            // This ensures that we create unique listeners for each questionlet totalQuestions = 0;

            // Track the keypress events in the Send Box
            sendbox.addEventListener('keypress', () => {
                if (sendbox.defaultValue.length > 4) {
                    getQuestion();
                } else {
                    removeQuestions();
                }
            });

            // Send a message containing the innerText of the target elementfunctionsend(event) {
                store.dispatch({
                    type: 'WEB_CHAT/SEND_MESSAGE',
                    payload: { text: event.currentTarget.innerText }
                });
                event.currentTarget.remove();
            }

            // This generates some test questionsfunctiongetQuestion() {
                // Create questions divconst questions = document.createElement('DIV');
                questions.setAttribute('class', 'questions');
                document.querySelector('.content').appendChild(questions);

                // Generate test questionsfor (var i = 0; i < 4; i++) {
                    // Create question divconst question = document.createElement('DIV');
                    question.setAttribute('id', `question${totalQuestions}`);
                    question.setAttribute('class', 'probing');
                    question.innerText = `this is a test ${totalQuestions}`;
                    questions.appendChild(question);

                    // Create listener for questionconst element = document.querySelector(`#question${totalQuestions}`);
                    element.addEventListener('click', send, false);
                    totalQuestions++;
                }
            }
        })().catch(err =>console.error(err));
    </script></body></html>

There are likely more elegant ways to do this, but I wanted to get an answer out to you ASAP.

Note: I used vanilla javascript over jQuery to cut down on page load times and because I'm more familiar with it.

Post a Comment for "How To Send A Message To Direct Line Chat Bot From The Ui Using Javascript"