How can I send some initial data to the bot before the user start chatting with my bot?

拟墨画扇 提交于 2019-12-11 14:51:57

问题


My problem is, How can I send some data on behalf of user to the bot before user start chatting.

because different client will have different endpoint, I would like bot to get this endpoint first and save it as UserState, then use this endpoint for making API calls later.

I'm using "https://github.com/microsoft/BotFramework-WebChat" this web chat as my client side, it create the directline using the secret, is that possible i add a post activity in the html file below to send some data?

Thank you!

<!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>

回答1:


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.

Web Chat

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.

Hope this helps!



来源:https://stackoverflow.com/questions/56294722/how-can-i-send-some-initial-data-to-the-bot-before-the-user-start-chatting-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!