BotFramework V4: how to send an event from the bot and catch it in react WebChat?

隐身守侯 提交于 2020-12-09 04:22:42

问题


I send an event named "locationRequest" from my bot (.NET SDK)

            Activity activity = new Activity
            {
                Type = ActivityTypes.Event,
                Name = "locationRequest"
            };
            await stepContext.Context.SendActivityAsync(activity, cancellationToken);

I want to catch this event in the WebChat client application, based on the minizable-web-chat coded in React, and set a boolean locationRequested to True:

const store = createStore({}, ({ dispatch }) => next => action => {
  if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
    dispatch({
      type: 'WEB_CHAT/SEND_EVENT',
      payload: {
        name: 'webchat/join',
      }
    });
  }
  else if(action.name == 'locationRequest'){
    this.setState(() => ({
      locationRequested: true
    }));
  }
  return next(action);
});

I am unable to catch this event, any idea please ?


回答1:


You're going down the right track. Basically, you can monitor for 'DIRECT_LINE/INCOMING_ACTIVITY' events and then check if the incoming activity has the appropriate name. For more details, take a look at the code snippet below and the Incoming Event Web Chat sample.

const store = createStore({}, ({ dispatch }) => next => action => {
  if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
    dispatch({
      type: 'WEB_CHAT/SEND_EVENT',
      payload: {
        name: 'webchat/join',
      }
    });
  }
  else if(action.type === 'DIRECT_LINE/INCOMING_ACTIVITY'){
    if (action.payload.activity.name === 'locationRequest') {
      this.setState(() => ({
        locationRequested: true
      }));
    }
  }
  return next(action);
});



回答2:


You are sending an activity from your bot, which means you can try to catch the activity and then you can check if the name of the activity is "locationRequest", and then you change the value of the locationRequested variable.

It would look something like this:

// We are adding a new middleware to customize the behavior of DIRECT_LINE/INCOMING_ACTIVITY.
    const store = window.WebChat.createStore(
      {},
      ({ dispatch }) => next => action => {
       if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
         if (action.payload.activity.name == "locationRequest") {
           this.setState(() => ({ locationRequested: true }));
         }
       }

        return next(action);
      }
    );

Hope this helps! Btw. I based my answer on this sample



来源:https://stackoverflow.com/questions/59986718/botframework-v4-how-to-send-an-event-from-the-bot-and-catch-it-in-react-webchat

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