0
votes

For MS Botframework webchat, Is there a way to intercept user message before being rendered in webchat and change it?

1

1 Answers

2
votes

This is easy to accomplish using the createStore() method.

In the web chat script located in your page, create the store using the above method. In it, match the action.type to 'WEB_CHAT/SEND_MESSAGE'. This will capture every message that is passed thru the web chat component before it is displayed.

Be aware, this altered text (or whatever value you are changing) is what is sent to the bot. action is the root object. action.payload, effectively, represents the activity. This is where you will find the text value, etc.

Within the if statement, perform whatever change you are looking to make, then return the action object.

Lastly, include the store object within the renderWebChat component. This should set you up.

In the example below, I am appending text to the text field altering it before it is rendered and displayed.

<script>
  ( async function () {
    const res = await fetch( 'http://somesite/directline/token', { method: 'POST' } );
    const { token } = await res.json();

    // We are using a customized store to add hooks to connect event
    const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
      if ( action.type === 'WEB_CHAT/SEND_MESSAGE' ) {
        action.payload.text = action.payload.text + ' (Hello from behind the curtain)'
      }

      return next( action );
    } );

    window.WebChat.renderWebChat( {
      directLine: window.WebChat.createDirectLine( { token } ),
      userID: 'user123',
      username: 'johndoe',
      botAvatarInitials: 'BB',
      userAvatarInitials: 'JD',
      store
    }, document.getElementById( 'webchat' ) );
    document.querySelector( '#webchat > *' ).focus();

  } )().catch( err => console.error( err ) );
</script>

enter image description here

enter image description here

Hope of help!