Search code examples
botframeworkdirect-line-botframeworkweb-chat

How to add a listener to every incoming message in 'botframwork-webchat'


I'm using Microsoft chatbot in my react js project, with botframework-webchat. I wanna add a listener to every incoming message.

The requirement is to identify a certain message (Last message) and the content of it. Base on the content, user should be redirected to a result screen. If I can access the result, I can do the navigation. I searched for solutions, but couldn't find any.

Here is my code

const Chatbot = (props) => {
  const directLine = useMemo(
    () => createDirectLine({ token: process.env.REACT_APP_DIRECT_LINE_SECRET, locale: 'sv-se' }),
    []
  );

  const styleOptions = {
    bubbleBackground: 'white',
    bubbleBorder: '#26acab',
    bubbleFromUserBackground: 'white',
    bubbleFromUserBorder: '#26acab',
    botAvatarImage: './Icon.ico',
    botAvatarBackgroundColor: 'transparent',
    userAvatarBackgroundColor: '#26acab',
    userAvatarInitials: bubbleInitials,
    rootHeight: '50%',
    rootWidth: '100%',
    hideUploadButton: true,
    primaryFont: "'Avenir LT Std', sans-serif",
    hideSendBox: true,
  };

  useEffect(() => {
    var initiatingActivity = {
      from: {
        id: '001',
        name: 'noviral',
        token: msalToken,
        locale: language === 'en' ? 'en-US' : 'sv-se',
      },
      name: 'startConversation',
      type: 'event',
      value: 'Hi noviral!',
    };


    directLine.postActivity(initiatingActivity).subscribe(function (id) {
      if (console) {
        console.log('Chat bot initiated');
      }
    });

    
  }, []);

  return (
    <Layout className="login-layout">
      <div className="login-div">
        <div className="chatbot">
          <div className="consent-wrapper">
            <ReactWebChat
              directLine={directLine}
              userID={'001'}
              username="Noviral"
              locale={language === 'en' ? 'en-US' : 'sv-se'}
              styleOptions={styleOptions}
            ></ReactWebChat>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default withTranslation()(Chatbot);

Can anyone help me with this? Thanks in advance


Solution

  • You can pass a custom store to ReactWebChat which will get called whenever you receive message

    import  {  createStoreWithDevTools } from 'botframework-webchat
    
    const store =  createStoreWithDevTools( {},
        ({ dispatch }) => next => action => {
         if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
            console.log(action.payload); //this will have incoming message data
          }
    
          return next(action);
        });
    
    <ReactWebChat directLine={directLine} store={store} userID="YOUR_USER_ID" />;