@a4aditya/webchat 中文文档教程

发布于 3年前 浏览 26 更新于 3年前

npm 许可证 频谱链接

Rasa Webchat ????

A chat widget to deploy virtual assistants made with Rasa or Botfront on any website.



demonstration


⚠️ Version 1.0.1 of the rasa webchat is made to work with version 2.3.x and 2.4.x of rasa. Use 1.0.0 for other rasa versions.


Features

  • Text Messages
  • Quick Replies
  • Images
  • Carousels
  • Markdown support
  • Persistent sessions
  • Typing indications
  • Smart delay between messages
  • Easy to import in a script tag or as a React Component

Promo: check out our other cool open source project

demonstration

Usage

In a <script> tag

在您的 中:

<script>!(function () {
  let e = document.createElement("script"),
    t = document.head || document.getElementsByTagName("head")[0];
  (e.src =
    "https://cdn.jsdelivr.net/npm/rasa-webchat@1.x.x/lib/index.js"),
    // Replace 1.x.x with the version that you want
    (e.async = !0),
    (e.onload = () => {
      window.WebChat.default(
        {
          customData: { language: "en" },
          socketUrl: "https://bf-botfront.development.agents.botfront.cloud",
          // add other props here
        },
        null
      );
    }),
    t.insertBefore(e, t.firstChild);
})();
</script>

⚠️ 我们建议添加版本标签以防止主要版本的重大更改,例如版本 1.0.0 https://cdn.jsdelivr.net /npm/rasa-webchat@1.0.0/lib/index.js, 然而,这不适用于 1.0.0 以下的版本。 如果您不指定版本,您将获得最新可用版本的 rasa-webchat。

关于图像:widthheight 定义邮件中的图像被裁剪后的像素大小。 如果不存在,图像将缩放到容器和图像的最大宽度。

As a React component

安装 npm 包

npm install rasa-webchat

然后:

import Widget from 'rasa-webchat';

function CustomWidget = () => {
  return (
    <Widget
      initPayload={"/get_started"}
      socketUrl={"http://localhost:5005"}
      socketPath={"/socket.io/"}
      customData={{1,2}} // arbitrary custom data. Stay minimal as this will be added to the socket
      title={"Title"}
    />
  )
}
  • Make sure to have the prop embedded set to true if you don't want to see the launcher.

Parameters

Prop / ParamDefault valueDescription
initPayloadnullPayload sent to Rasa when conversation starts
socketUrlnullSocket URL
socketPathnullClose the chat window
customDatanullArbitrary object sent with the socket. If using with Botfront, it must include the language (e.g. {"language": "en"})
docViewerfalseIf you add this prop to the component or to the init script, docViewer=true , this will treat links in received messages as links to a document ( .pdf .doc .xlsx etc. ) and will open them in a popup using https://docs.google.com/viewer service
title'Welcome"Title shown in the header of the widget
subtitlenullSubtitle shown under the title in the header of the widget
inputTextFieldHint"Type a message"User message input field placeholder
hideWhenNotConnectedtrueIf true the widget will hide when the connection to the socket is lost
connectOn"mount"This prop lets you choose when the widget will try connecting to the server. By default, it tries connecting as soon as it mounts. If you select connectOn='open' it will only attempt connection when the widget is opened. it can only take the values mount and open.
onSocketEventnullcall custom code on a specific socket event
embeddedfalseSet to true if you want to embed the in a web page. The widget will always be open and the initPayload will be triggered immediately
showFullScreenButtonfalseShow a full screen toggle
displayUnreadCountfalsePath to an image displayed on the launcher when the widget is closed
showMessageDatefalseShow message date. Can be overriden with a function: (timestamp, message) => return 'my custom date'
customMessageDelaySee belowThis prop is a function, the function take a message string as an argument. The defined function will be called everytime a message is received and the returned value will be used as a milliseconds delay before displaying a new message.
paramsSee belowEssentially used to customize the image size, also used to change storage options.
storage"local"⚠️ This is not a prop, it has to be passed inside the params object above.
Specifies the storage location of the conversation state in the browser. "session" defines the state to be stored in the session storage. The session storage persists on reload of the page, and is cleared after the browser or tab is closed, or when sessionStorage.clear()is called. "local" defines the state to be stored in the local stoage. The local storage persists after the the browser is closed, and is cleared when the cookies of the browser are cleared, or when localStorage.clear()is called.
customComponentnullCustom component to be used with custom responses. E.g.: customComponent={ (messageData) => (<div>Custom React component</div>)}. Please note that this can only be used if you call the webchat from a React application as you can't write a component in pure Javscript.
onWidgetEvent{}call custom code on a specific widget event ( onChatOpen, onChatClose, onChatHidden, are available for now ), add a function to the desired object property in the props to have it react to the event.

Additional Examples

customMessageDelay
(message) => {
    let delay = message.length * 30;
    if (delay > 2 * 1000) delay = 3 * 1000;
    if (delay < 400) delay = 1000;
    return delay;
}
onSocketEvent
onSocketEvent={{
  'bot_uttered': () => console.log('the bot said something'),
  'connect': () => console.log('connection established'),
  'disconnect': () => doSomeCleanup(),
}}
params

params 道具只允许指定自定义图像尺寸:

params={{
        images: {
          dims: {
            width: 300,
            height: 200
          }
        }
      }}

Other features

Tooltips

收到短信当小部件关闭时将显示为工具提示。

Sending a message on page load

当重新连接到现有的聊天会话时,机器人将发送包含在 NEXT_MESSAGE 常量指定的 localStorage 键中的消息。 消息应该是字符串化的 JSON,具有描述消息的 message 属性和设置为 UNIX 时间戳(以毫秒为单位)的 expiry 属性,超过此时间不应发送此消息。 如果您希望您的机器人能够为您的用户提供在网站上导航的功能,这将很有用。

Sending a payload from your React app

function myComponent() {
    const webchatRef = useRef(null);

    // triggered when something happens in your app
    function callback() {
        if (webchatRef.current && webchatRef.current.sendMessage) {
            webchatRef.current.sendMessage('/myIntent{"entityName":"value"}');
        }
    }

    return <RasaWebchat
        ref={webchatRef}
    />;
}

有效载荷可以是用户通常发送的任何消息,但如果你想强制一个意图和一些实体,你可以使用该格式 /myIntent{"entity1":"value1","entity2":"value2"}

Backends

该小部件可用于任何后端,但主要设计用于 RasaBotfront

Rasa

使用 socketio 通道:请参阅 Rasa 文档中的说明

如果您需要要在 Rasa 中处理 customData,您必须创建一个新通道。 使用频道 rasa_core.channels.socketio 作为新频道的模板。 在这个通道中,customData可以通过data['customData']获取。 然后您可以修改 sender_id,将 customData 保存到数据库,填充插槽或任何您需要的附加数据。

Botfront

Rasa Webchat 由 Botfront 团队开发,并与 Botfront 配合使用。 如果您的机器人是多语言的,请确保在 customData 属性中指定当前语言。 例如 customData={{language: 'en'}}。 有关详细信息,请参阅 Botfront 文档

Styles

从 0.8 版开始,我们开始为所有 css 类添加前缀,如果您已经为小部件设置了 css 样式,只需将 rw- 添加到您更改的所有类之前。

层次结构:

.rw-conversation-container
  |-- .rw-header
        |-- .rw-title
        |-- .rw-close-function
        |-- .rw-loading
  |-- .rw-messages-container
        |-- .rw-message
              |-- .rw-client
              |-- .rw-response
        |-- .rw-replies
              |-- .rw-reply
              |-- .rw-response
        |-- .rw-snippet
              |-- .rw-snippet-title
              |-- .rw-snippet-details
              |-- .rw-link
        |-- .rw-imageFrame
        |-- .rw-videoFrame
  |-- .rw-sender
        |-- .rw-new-message
        |-- .rw-send
ClassDescription
.rw-widget-containerThe div containing the chatbox of the default version
.rw-widget-embeddeddiv of the embedded chatbox (using embedded prop)
.rw-full-screendiv of the fullscreen chatbox (using fullScreenMode prop)
.rw-conversation-containerthe parent div containing the header, message-container and sender
.rw-messages-containerthe central area where the messages appear
.rw-senderdiv of the bottom area which prompts user input
.rw-new-messagethe text input element of sender
.rw-sendthe send icon element of sender
.rw-headerdiv of the top area with the chatbox header
.rw-titlethe title element of the header
.rw-close-buttonthe close icon of the header
.rw-loadingthe loading status element of the header
.rw-messagethe boxes holding the messages of client and response
.rw-repliesthe area that gives quick reply options
.rw-snippeta component for describing links
.rw-imageFramea container for sending images
.rw-videoFramea container for sending video

Contributors

@PHLF @znat @TheoTomalty @Hub4IT @dliuproduction @MatthieuJnon @mofortin @GuillaumeTech


License

版权所有 (C) 2021 Dialogue Technologies Inc.

根据 Apache 许可证 2.0 版(“许可证”)获得许可; 除非遵守许可证,否则您不得使用此文件。 下获得许可副本

http://www.apache.org/licenses/LICENSE-2.0

您可以在除非适用法律要求或书面同意的情况 ,软件 根据许可证分发是在“按原样”的基础上分发的, 没有任何明示或暗示的保证或条件。 请参阅许可证以获取特定语言的管理权限和 许可下的限制。(C) 2021 Dialogue Technologies Inc. 保留所有权利。

npm License Spectrum link

Rasa Webchat ????

A chat widget to deploy virtual assistants made with Rasa or Botfront on any website.



demonstration


⚠️ Version 1.0.1 of the rasa webchat is made to work with version 2.3.x and 2.4.x of rasa. Use 1.0.0 for other rasa versions.


Features

  • Text Messages
  • Quick Replies
  • Images
  • Carousels
  • Markdown support
  • Persistent sessions
  • Typing indications
  • Smart delay between messages
  • Easy to import in a script tag or as a React Component

???? Promo: check out our other cool open source project

demonstration

Usage

In a <script> tag

In your <body/>:

<script>!(function () {
  let e = document.createElement("script"),
    t = document.head || document.getElementsByTagName("head")[0];
  (e.src =
    "https://cdn.jsdelivr.net/npm/rasa-webchat@1.x.x/lib/index.js"),
    // Replace 1.x.x with the version that you want
    (e.async = !0),
    (e.onload = () => {
      window.WebChat.default(
        {
          customData: { language: "en" },
          socketUrl: "https://bf-botfront.development.agents.botfront.cloud",
          // add other props here
        },
        null
      );
    }),
    t.insertBefore(e, t.firstChild);
})();
</script>

⚠️ We recommend adding a version tag to prevent breaking changes from major versions, e.g for version 1.0.0 https://cdn.jsdelivr.net/npm/rasa-webchat@1.0.0/lib/index.js, however this will not work with versions below 1.0.0. If you do not specify a version, you will get served the latest available version of the rasa-webchat.

About images: width and height define the size in pixels that images in messages are crop-scaled to. If not present, the image will scale to the maximum width of the container and the image.

As a React component

Install the npm package:

npm install rasa-webchat

Then:

import Widget from 'rasa-webchat';

function CustomWidget = () => {
  return (
    <Widget
      initPayload={"/get_started"}
      socketUrl={"http://localhost:5005"}
      socketPath={"/socket.io/"}
      customData={{1,2}} // arbitrary custom data. Stay minimal as this will be added to the socket
      title={"Title"}
    />
  )
}
  • Make sure to have the prop embedded set to true if you don't want to see the launcher.

Parameters

Prop / ParamDefault valueDescription
initPayloadnullPayload sent to Rasa when conversation starts
socketUrlnullSocket URL
socketPathnullClose the chat window
customDatanullArbitrary object sent with the socket. If using with Botfront, it must include the language (e.g. {"language": "en"})
docViewerfalseIf you add this prop to the component or to the init script, docViewer=true , this will treat links in received messages as links to a document ( .pdf .doc .xlsx etc. ) and will open them in a popup using https://docs.google.com/viewer service
title'Welcome"Title shown in the header of the widget
subtitlenullSubtitle shown under the title in the header of the widget
inputTextFieldHint"Type a message"User message input field placeholder
hideWhenNotConnectedtrueIf true the widget will hide when the connection to the socket is lost
connectOn"mount"This prop lets you choose when the widget will try connecting to the server. By default, it tries connecting as soon as it mounts. If you select connectOn='open' it will only attempt connection when the widget is opened. it can only take the values mount and open.
onSocketEventnullcall custom code on a specific socket event
embeddedfalseSet to true if you want to embed the in a web page. The widget will always be open and the initPayload will be triggered immediately
showFullScreenButtonfalseShow a full screen toggle
displayUnreadCountfalsePath to an image displayed on the launcher when the widget is closed
showMessageDatefalseShow message date. Can be overriden with a function: (timestamp, message) => return 'my custom date'
customMessageDelaySee belowThis prop is a function, the function take a message string as an argument. The defined function will be called everytime a message is received and the returned value will be used as a milliseconds delay before displaying a new message.
paramsSee belowEssentially used to customize the image size, also used to change storage options.
storage"local"⚠️ This is not a prop, it has to be passed inside the params object above.
Specifies the storage location of the conversation state in the browser. "session" defines the state to be stored in the session storage. The session storage persists on reload of the page, and is cleared after the browser or tab is closed, or when sessionStorage.clear()is called. "local" defines the state to be stored in the local stoage. The local storage persists after the the browser is closed, and is cleared when the cookies of the browser are cleared, or when localStorage.clear()is called.
customComponentnullCustom component to be used with custom responses. E.g.: customComponent={ (messageData) => (<div>Custom React component</div>)}. Please note that this can only be used if you call the webchat from a React application as you can't write a component in pure Javscript.
onWidgetEvent{}call custom code on a specific widget event ( onChatOpen, onChatClose, onChatHidden, are available for now ), add a function to the desired object property in the props to have it react to the event.

Additional Examples

customMessageDelay
(message) => {
    let delay = message.length * 30;
    if (delay > 2 * 1000) delay = 3 * 1000;
    if (delay < 400) delay = 1000;
    return delay;
}
onSocketEvent
onSocketEvent={{
  'bot_uttered': () => console.log('the bot said something'),
  'connect': () => console.log('connection established'),
  'disconnect': () => doSomeCleanup(),
}}
params

The params props only allows to specify custom image dimensions:

params={{
        images: {
          dims: {
            width: 300,
            height: 200
          }
        }
      }}

Other features

Tooltips

Text messages received when the widget is closed will be shown as a tooltip.

Sending a message on page load

When reconnecting to an existing chat session, the bot will send a message contained in the localStorage key specified by the NEXT_MESSAGE constant. The message should be stringified JSON with a message property describing the message and an expiry property set to a UNIX timestamp in milliseconds after which this message should not be sent. This is useful if you would like your bot to be able to offer your user to navigate around the site.

Sending a payload from your React app

function myComponent() {
    const webchatRef = useRef(null);

    // triggered when something happens in your app
    function callback() {
        if (webchatRef.current && webchatRef.current.sendMessage) {
            webchatRef.current.sendMessage('/myIntent{"entityName":"value"}');
        }
    }

    return <RasaWebchat
        ref={webchatRef}
    />;
}

The payload can be any message that the user would normally send, but if you want to force an intent and maybe some entities, you can use that format /myIntent{"entity1":"value1","entity2":"value2"}

Backends

The widget can be used with any backend but is primarily designed to be used with Rasa or Botfront.

Rasa

Use the socketio channel: See instructions in the Rasa documentation

If you want to process customData in Rasa you have to create a new channel. Use channel rasa_core.channels.socketio as a template for your new channel. In this channel, customData can be retrieved via data['customData']. Then you can modify sender_id, save customData to the database, fill slots or whatever you need to with your additional data.

Botfront

The Rasa Webchat is developped by the Botfront team and it works with Botfront. If your bot is multilingual, make sure to specificy the current language in the customData prop. E.g. customData={{language: 'en'}}. See in Botfront docs for more details.

Styles

From version 0.8 we started prefixing all css classes, if you already had css styling for the widget, just prepend rw- to all the classes you changed.

hierarchy:

.rw-conversation-container
  |-- .rw-header
        |-- .rw-title
        |-- .rw-close-function
        |-- .rw-loading
  |-- .rw-messages-container
        |-- .rw-message
              |-- .rw-client
              |-- .rw-response
        |-- .rw-replies
              |-- .rw-reply
              |-- .rw-response
        |-- .rw-snippet
              |-- .rw-snippet-title
              |-- .rw-snippet-details
              |-- .rw-link
        |-- .rw-imageFrame
        |-- .rw-videoFrame
  |-- .rw-sender
        |-- .rw-new-message
        |-- .rw-send
ClassDescription
.rw-widget-containerThe div containing the chatbox of the default version
.rw-widget-embeddeddiv of the embedded chatbox (using embedded prop)
.rw-full-screendiv of the fullscreen chatbox (using fullScreenMode prop)
.rw-conversation-containerthe parent div containing the header, message-container and sender
.rw-messages-containerthe central area where the messages appear
.rw-senderdiv of the bottom area which prompts user input
.rw-new-messagethe text input element of sender
.rw-sendthe send icon element of sender
.rw-headerdiv of the top area with the chatbox header
.rw-titlethe title element of the header
.rw-close-buttonthe close icon of the header
.rw-loadingthe loading status element of the header
.rw-messagethe boxes holding the messages of client and response
.rw-repliesthe area that gives quick reply options
.rw-snippeta component for describing links
.rw-imageFramea container for sending images
.rw-videoFramea container for sending video

Contributors

@PHLF @znat @TheoTomalty @Hub4IT @dliuproduction @MatthieuJnon @mofortin @GuillaumeTech


License

Copyright (C) 2021 Dialogue Technologies Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.(C) 2021 Dialogue Technologies Inc. All rights reserved.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文