I'm implementing webchat with token based along with chat persistence everything works fine when user is online, but after some idle time if user is offline with no internet connectivity, for about 30-45 mins then later he gets back online and when ever he texting anything bot went to state DIRECT_LINE/POST_ACTIVITY_REJECTED and user was unable to chat with the bot its giving away send retry on my message bubble. Is there any way possible to handle?.
(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));
note: token is not expired and If I refresh the page bot starts reponding.
I made a few adjustments to the code you supplied. I believe your token
value was getting overwritten or corrupted, so I separated out the assigning of the token in the API call (token
) and the variable assignment in the script (dl_token
).
I was also getting an error on the refresh token call wrapped in the setInterval()
function, which is why I use Babel, as shown below. (For testing, it helps identify errors that would otherwise have been missed.). Removing the actual API call from setInterval()
and calling it as a separate function seemed to fix this.
After these changes, everything seems to be working smoothly. I only tested a few times waiting until the 45-50 minute, but didn't experience any issues with the token, needing to refresh, or receiving DIRECT_LINE/POST_ACTIVITY_REJECTED
.
(Note that I made calls to my own 'token' server for generating and refreshing the 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>
Hope of help!