reactjs - 使用 React 的 Azure Bot Framework 存在问题

标签 reactjs azure botframework

下面是我为机器人框架编写的代码,我引用了 git hub 中的文档,并关注了很多文章和堆栈溢出的帖子,似乎在 WebChat 行显示机器人时抛出错误。聊天,这里是link也来自 stackoverlflow 中的帖子:

declare var require: any
var React = require('react');
var ReactDOM = require('react-dom');
var DirectLine  = require('botframework-directlinejs');
//import * as WebChat from 'botframework-webchat';
var WebChat = require('botframework-webchat');


export class Hello extends React.Component {
    constructor() {
        super();
        this.state = { data: [] };
        this.variableValue = { dataValue: [] };

    }
    async componentDidMount() {
        const response = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer secretvalue',
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                accessLevel: 'View',
                allowSaveAs: 'false',
            })
        });
        // const { token } = await res.json();
        const { token } = await response.json();
        console.log(token);
        this.setState({ data: token });
        // 
    }
    render() {
        const {
            state: { data }
        } = this

        return (

            //<div>
            //    <p>Hello there1</p>
            //    <ul>
            //        {data}
            //    </ul>
            //</div>
            <WebChat.Chat
                directLine={{
                   data,
                    webSocket: false
                }}
                style={{
                    height: '100%',
                    width: '100%'
                }}
                //user={{
                //    id: 'default-user',
                //    name: 'Some User'
                //}}
            />



        );
    }

}

ReactDOM.render(<Hello />, document.getElementById('root'));

我可以通过休息调用获取 token ,但在必须使用 WebChat.Chat directLine 显示机器人时出现错误 以下是错误:enter image description here enter image description here

编辑 我能够使用react和babel运行html文件中的代码,下面是代码......

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Integrate with React</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--
      For simplicity and code clarity, we are using Babel and React from unpkg.com.
    -->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee9c8b8f8d9aaedfd8c0dbc0de" rel="noreferrer noopener nofollow">[email protected]</a>/umd/react.development.js"></script>
    <script src="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0a2b5b1b3a4fdb4bfbd90e1e6fee5fee0" rel="noreferrer noopener nofollow">[email protected]</a>/umd/react-dom.development.js"></script>
    <!--
      For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
      When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
      or lock down on a specific version with the following format: "/4.1.0/webchat.js".
    -->
    <script src="https://cdn.botframework.com/botframework-webchat/master/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 type="text/babel">
        (async function () {
        // In this demo, we are using Direct Line token from MockBot.
        // To talk to your bot, you should use the token exchanged using your Direct Line secret.
        // You should never put the Direct Line secret in the browser or client app.
        // https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
        const headers = {"Authorization": "Bearer rngzqJ7rkng.cwA.A8k.xg_Jb-NbNs4Kq8O2CcF-vnNxy8nlCMPMPYaXL0oROr0"}
        const body = {"accessLevel": "View"}
        //const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST' }, {Headers:headers},{Body:body});
        //const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });

        const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', {
        method: 'POST',
        headers: {
        'Authorization': 'Bearer secretvalue',
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        },
        body: JSON.stringify({
        accessLevel: 'View',
        allowSaveAs: 'false',
        })
        });

        const { token } = await res.json();
        const { ReactWebChat } = window.WebChat;
        window.ReactDOM.render(
        <ReactWebChat directLine={ window.WebChat.createDirectLine({ token }) } />,
        document.getElementById('webchat')
        );

        document.querySelector('#webchat > *').focus();
        })().catch(err => console.error(err));
    </script>
  </body>
</html>

但是当我在 Node js 应用程序中使用它时,我在使用 WebCHat.Chat 时遇到了问题。

最佳答案

网络聊天有两个版本 - v3 和 v4。您提到的 StackOverflow 问题使用的是 Web Chat v3,而您使用的依赖项是 v4。请查看下面的代码片段,了解使用 Node 实现的 Web Chat v4 的外观。

import React from 'react';

import ReactWebChat, { createDirectLine } from 'botframework-webchat';

export default class extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      directLine: null
    };
  }

  componentDidMount() {
    this.fetchToken();
  }

  async fetchToken() {
    const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
    const { token } = await res.json();

    this.setState(() => ({
      directLine: createDirectLine({ token })
    }));
  }

  render() {
    return (
      this.state.directLine ?
        <ReactWebChat
          className="chat"
          directLine={ this.state.directLine }
        />
      :
        <div>Connecting to bot&hellip;</div>
    );
  }
}

有关更多详细信息,请查看samples GitHub Repo 上的示例 17 是查看 Node 实现的一个很好的示例。

关于reactjs - 使用 React 的 Azure Bot Framework 存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56630253/

相关文章:

node.js - Facebook 机器人阿拉伯语问候文本显示问号?

azure - Azure Bot 服务的 Teams channel 的 IP 地址限制

node.js - HeroCard 中的多个按钮

javascript - 如何在作为 "this"传递给子组件的函数中使用 "prop"?

reactjs - 如何从 useEffect 中只更新一个函数

sql - 如何在 Visual Studio 中更改 Azure 数据库表的列顺序

Azure Devops YAML - AzureKeyVault 任务不接受变量作为 keyvaultname

azure - 无法初始化 Microsoft Azure 存储模拟器 SDK2.8

javascript - 在 ReactJS 中实现动态表单

javascript - Ant 设计 : How can I disable border-bottom of a menu item on hover?