How can I send some initial data to the bot before

2019-08-29 08:41发布

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条回答
老娘就宠你
2楼-- · 2019-08-29 09:43

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!

查看更多
登录 后发表回答