首页 > 解决方案 > 在用户开始与我的机器人聊天之前,如何向机器人发送一些初始数据?

问题描述

我的问题是,如何在用户开始聊天之前代表用户向机器人发送一些数据。

因为不同的客户端会有不同的端点,我希望机器人先获取这个端点并将其保存为 UserState,然后使用这个端点进行 API 调用。

我正在使用“ https://github.com/microsoft/BotFramework-WebChat ”这个网络聊天作为我的客户端,它使用秘密创建直接线路,我是否可以在下面的 html 文件中添加一个发布活动来发送一些数据?

谢谢!

<!DOCTYPE html> <html> <body>
    <div id="webchat" role="main"></div>
    <script src="Scripts/Directline.js"></script>
    <script>
        window.WebChat.renderWebChat({
            directLine: window.WebChat.createDirectLine({
                token: 'my secret'
            }),
            locale: 'en-US',
            botAvatarInitials: 'Bot',
            userAvatarInitials: 'ME',
        },
        document.getElementById('webchat'));
    </script> </body> </html>

标签: botframeworkclient-sidecustom-data-attributeweb-chat

解决方案


您可以将自定义中间件添加到网络聊天的商店,当 DirectLine 连接完成时,该中间件可以向机器人发送包含必要数据的事件。请参阅下面的代码片段。

网络聊天

const store = window.WebChat.createStore({},
  ({ dispatch }) => next => action => {

    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
      // Send event to bot with custom data
      dispatch({
        type: 'WEB_CHAT/SEND_EVENT',
        payload: {
          name: 'webchat/join',
          value: { data: { username: 'TJ'}}
        }
      })
    }
    return next(action);
  });        


window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store,
}, document.getElementById('webchat'));

机器人 - C# SDK

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using  Newtonsoft.Json.Linq;

namespace Microsoft.BotBuilderSamples.Bots
{
    public class EchoBot : ActivityHandler
    {
        protected override async Task OnEventAsync(ITurnContext<IEventActivity> context, CancellationToken cancellationToken)
        {
            if (context.Activity.Name == "webchat/join") {
                var data = JObject.Parse(context.Activity.Value.ToString()).GetValue("data");
                var user = JObject.Parse(data.ToString()).GetValue("username");
                await context.SendActivityAsync($"Hi, {user}!");
            }
        }

    }
}

有关更多详细信息,请参阅Send Backchannel Welcome Event Web Chat 示例。

希望这可以帮助!


推荐阅读