且构网

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

在用户开始与我的机器人聊天之前,如何向机器人发送一些初始数据?

更新时间:2023-11-19 08:31:25

您可以在Web Chat的商店中添加自定义中间件,当DirectLine连接完成时,该中间件可以将包含必要数据的事件发送到bot.请参见下面的代码段.

You can add a custom middleware to Web Chat's store which can send an event containing the necessary data to the bot when the DirectLine connection is fulfilled. See the code snippets below.

网络聊天

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'));

Bot-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}!");
            }
        }

    }
}

有关更多详细信息,请参见

For more details, take at the Send Backchannel Welcome Event Web Chat sample.

希望这会有所帮助!