Session lifetime control
Session — a sequence of client and bot interactions within a single conversation context.
A session begins with the first client request if there is no other active session for this client.
Reasons for a session termination:
- timeout expiry;
- device turning on/off;
- solving a client issue that is being confirmed by filling in a form for feedback etc.
The requirements for a session termination are unique for every bot. Requirement configuration is made at the script level. The script is supposed to determine the moment of the old session ending and the moment of the beginning of a new one. It is possible thanks to the $reaction.newSession.
The newSession reaction throws a specific exception. When such an exception is caught the log is written and a new session is created.
Methods of session control
You can use the methods below to control the session:
$reactions.newSessioncreate a new session from the script;$jsapi.startSession()starts a new session;$jsapi.stopSession()close a session.
How to use
- Creating a new session by timeout.
theme: /
init:
bind("postProcess", function($context) {
$context.session.lastActiveTime = $jsapi.currentTime();
log($context.session.lastActiveTime)
});
bind("preProcess", function($context) {
if ($context.session.lastActiveTime) {
var interval = $jsapi.currentTime() - $context.session.lastActiveTime;
if (interval > 10000) {
$reactions.newSession( {message: 'test 6', session: $context.request.data } );
}
}
});- Here is an example of how a new session can be triggered by an event.
state: sessionStart
event!: newChatStarted
script:
$request.query = $request.rawRequest.messages[0].text;
$request.event = null;
$reactions.newSession({request: $request});The script switched to a state triggered by the newChatStarted event. We need to create a new session but we also must handle the client’s message that accompanied the event.
We override $request.event = null in order to avoid switching to the state once again. We also write the client’s message to $request.query. Then we create a new session ($reactions.newSession) with the client’s message already stored.
- Here is an example of a script that raises the
newSessionExceptionerror.
state: reset
event!: someEvent
script:
$reactions.newSession({message: "some text", data: $request.data});Here, the script switched to a state triggered by the newChatStarted event that will be saved to $request.event. We create a new session, replacing the text. However, we keep the original event. Events are primary triggers for the platform, so we will get into an endless loop in this script.
To avoid this, override the $request.event = null event.