Skip to main content

$jsapi.startSession

This method starts a new session.

Calling the $jsapi.startSession method causes an immediate new session start:

  • The current user request and all bot reactions fall into the new session.
  • The contents of the $session variable are cleared immediately.

Syntax

The method is called without arguments:

$jsapi.startSession();

Usage details

In the phone channel, a call to $jsapi.startSession is ignored in the state triggered by the /start pattern. JAICP automatically starts a new session at the beginning of a phone call.

How to use

New session on dialog start

require: patternsEn.sc
module = sys.zb-common

theme: /

state: Hello
q!: $regex</start>
q!: * $hello *
script:
$jsapi.startSession();
random:
a: Hi! How can I help you?
a: Pleased to meet you. What’s up?

Creating a new session after a timeout

In this example, we use the bind function to set up two handlers that will be called on each user request:

  • postProcess handler that calls the $jsapi.currentTime method and saves its result in $session as the last user activity time.
  • preProcess handler that calculates the difference between the current time and the last activity time. If it is greater than the specified timeout, the script starts a new session.
init:
var SESSION_TIMEOUT_MS = 172800000; // Two days

bind("postProcess", function($context) {
$context.session.lastActiveTime = $jsapi.currentTime();
});

bind("preProcess", function($context) {
if ($context.session.lastActiveTime) {
var interval = $jsapi.currentTime() - $context.session.lastActiveTime;
if (interval > SESSION_TIMEOUT_MS) $jsapi.startSession();
}
});