且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JavaScript从UI发送消息到直接聊天机器人

更新时间:2023-08-17 20:08:16

这是一个工作示例,应使用

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

<!DOCTYPE html>
<html lang="en-US">

<head>
    <title>Web Chat: Programmatic access to post activity</title>
    <meta name="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
    -->
    <script src="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>
    <div id="webchat" role="main"></div>
    <script>
        (async function () {
            // 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 STUFF

            const sendbox = document.querySelector("[aria-label='Sendbox']");

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

            // This ensures that we create unique listeners for each question
            let 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 element
            function send(event) {
                store.dispatch({
                    type: 'WEB_CHAT/SEND_MESSAGE',
                    payload: { text: event.currentTarget.innerText }
                });
                event.currentTarget.remove();
            }

            // This generates some test questions
            function getQuestion() {
                // Create questions div
                const questions = document.createElement('DIV');
                questions.setAttribute('class', 'questions');
                document.querySelector('.content').appendChild(questions);

                // Generate test questions
                for (var i = 0; i < 4; i++) {
                    // Create question div
                    const 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 question
                    const 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.

注意:我使用jQuery上的香草javascript来减少页面加载时间,因为我对此更加熟悉.