Como lidar com DIRECT_LINE / POST_ACTIVITY_REJECTED

Nov 12 2020

Estou implementando o webchat com token baseado em persistência de chat e tudo funciona bem quando o usuário está online, mas depois de algum tempo ocioso se o usuário estiver offline sem conectividade com a Internet, por cerca de 30-45 minutos depois ele fica online novamente e sempre que enviar mensagens de texto com qualquer coisa que o bot foi para o estado DIRECT_LINE / POST_ACTIVITY_REJECTED e o usuário não conseguiu bater um papo com o bot, ele está dando uma nova tentativa de envio no meu balão de mensagem. Existe alguma maneira possível de lidar ?.

 (async function() {
    'use strict';
    const {
            hooks: { usePostActivity },
            hooks: { useDirection },
            ReactWebChat
    } = window.WebChat;
    
     let { token, conversation_Id } = sessionStorage;
    if ( !token ) {
                    const res = await fetch( 'https:/localhost/api/generateToken', { method: 'POST' } );
                    const { token: directLineToken, conversationId: conversationId } = await res.json();
                    sessionStorage[ 'token' ] = directLineToken;
                    sessionStorage[ 'conversation_Id' ] = conversationId;
                    token = directLineToken;
                    conversation_Id = conversationId;
                    }
                    
    if (token) {
        await setInterval(async () => {
        var myHeaders = new Headers();
        myHeaders.append("Authorization","Bearer "+ sessionStorage[ 'token' ]);
        let res = await fetch( 'https://directline.botframework.com/v3/directline/tokens/refresh', {
                                method: 'POST', 
                                headers: myHeaders,
                                });
        const { token: directLineToken, conversationId } = await res.json();
            sessionStorage[ 'token' ] = directLineToken;
            sessionStorage[ 'conversation_Id' ] = conversationId;
            token = directLineToken;
            conversation_Id = conversationId;
        }, 1000*60*15)}
        
                        
    
    
    const  store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
    if(action.payload && action.payload.directLine) {
        const subscription = action.payload.directLine.connectionStatus$.subscribe({
                error: error => console.log( error ),
                next: value => {
                        if ( value === 0 ) {console.log('Uninitialized')} 
                        else if ( value === 1 ) {console.log('Connecting')} 
                        else if ( value === 2 ) {console.log('Online')}
                        else if  ( value === 3 ) {console.log('Expire Token')}
                        else if ( value === 4 ) {console.log('FailedToConnect')}
                        else if ( value === 5 ) {console.log('Ended')}
                }
            });
        }
     if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
        dispatch({
                type: 'WEB_CHAT/SEND_EVENT',
                payload: {
                    name: 'Welcome',
                    value: { language: window.navigator.language }
                    }
                });
            }
            
    
    if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
                action = window.simpleUpdateIn(action, ['payload', 'activity', 'channelData', 'CustomChannel'], () =>"webchat");
                }
    
        return next(action);
    });
    
    
   const  botconnection = createDirectLine( {token,webSockets: true,watermark: "0" });
    
    window.ReactDOM.render(
    <ReactWebChat directLine={botconnection}
                  store={store}
        />,
        document.getElementById('webchat'));
        document.querySelector('#webchat > *').focus();
        })().catch(err => console.error(err));

nota: o token não expirou e se eu atualizar a página, o bot começa a responder.

Respostas

1 StevenKanberg Nov 17 2020 at 15:02

Fiz alguns ajustes no código que você forneceu. Acredito que seu tokenvalor estava sendo substituído ou corrompido, então separei a atribuição do token na chamada de API ( token) e a atribuição de variável no script ( dl_token).

Eu também estava recebendo um erro na chamada do token de atualização envolvida na setInterval()função, e é por isso que uso o Babel, conforme mostrado abaixo. (Para teste, ajuda a identificar erros que, de outra forma, teriam sido perdidos.). Remover a chamada de API real setInterval()e chamá-la como uma função separada parecia corrigir isso.

Após essas mudanças, tudo parece estar funcionando perfeitamente. Eu testei apenas algumas vezes esperando até 45-50 minutos, mas não tive problemas com o token, necessidade de atualização ou recebimento DIRECT_LINE/POST_ACTIVITY_REJECTED.

(Observe que fiz chamadas para meu próprio servidor de 'token' para gerar e atualizar o token.)

<script crossorigin="anonymous" src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>

<script type="text/babel" data-presets="es2015,react,stage-3">
  ( async function () {
    'use strict';
    const {
      ReactWebChat
    } = window.WebChat;

    let { dl_token, conversation_Id } = sessionStorage;
    
    if ( !dl_token ) {
      const res = await fetch( 'http://localhost:3500/directline/conversations', { method: 'POST' } );
      const { token, conversationId } = await res.json();
      sessionStorage[ 'dl_token' ] = token;
      sessionStorage[ 'conversation_Id' ] = conversationId;
      dl_token = token;
      conversation_Id = conversationId;
    }

    if ( dl_token === sessionStorage['dl_token'] ) {
      setInterval( () => {
        refreshToken()
      }, 1000 * 60 * 1 )
    }
    
    const refreshToken = async () => {
      const res = await fetch( 'http://localhost:3500/directline/refresh', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          token: dl_token
        })
      } );
      const { token, conversationId } = await res.json();
      sessionStorage[ 'dl_token' ] = token;
      sessionStorage[ 'conversation_Id' ] = conversationId;
      dl_token = token;
      conversation_Id = conversationId;
    }


    const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
      if ( action.payload && action.payload.directLine ) {
        const subscription = action.payload.directLine.connectionStatus$.subscribe( {
          error: error => console.log( error ),
          next: value => {
            if ( value === 0 ) { console.log( 'Uninitialized' ) }
            else if ( value === 1 ) { console.log( 'Connecting' ) }
            else if ( value === 2 ) { console.log( 'Online' ) }
            else if ( value === 3 ) { console.log( 'Expire Token' ) }
            else if ( value === 4 ) { console.log( 'FailedToConnect' ) }
            else if ( value === 5 ) { console.log( 'Ended' ) }
          }
        } );
      }
      if ( action.type === 'DIRECT_LINE/CONNECT_FULFILLED' ) {
        dispatch( {
          type: 'WEB_CHAT/SEND_EVENT',
          payload: {
            name: 'Welcome',
            value: { language: window.navigator.language }
          }
        } );
      }


      if ( action.type === 'DIRECT_LINE/POST_ACTIVITY' ) {
        action = window.simpleUpdateIn( action, [ 'payload', 'activity', 'channelData', 'CustomChannel' ], () => "webchat" );
      }

      return next( action );
    } );


    const botconnection = await createDirectLine( { token: dl_token } );

    window.ReactDOM.render(
      <ReactWebChat directLine={botconnection}
        store={store}
      />,
      document.getElementById( 'webchat' ) );
    document.querySelector( '#webchat > *' ).focus();
  } )().catch( err => console.error( err ) );
</script>

Esperança de ajuda!