Logic Blocks

Logic Blocks allow you to write custom JavaScript code that executes within your chatbot flows. This reference documents all available functions in the Logic Block environment.

The Logic Block environment provides a secure, sandboxed JavaScript runtime with access to user data, messaging capabilities, and external APIs. Code executes on the server with memory and time limits to ensure system stability.

Environment Limitations

This is a limited JavaScript environment. Standard browser APIs (DOM, window, fetch) and Node.js APIs (fs, http, process) are not available. Use the provided functions documented below for all operations.

Getting Started

Understanding the basics of Logic Block execution.

Code Execution

How Logic Block code is executed within your chatbot flow.

Logic Blocks execute when a user reaches that point in your chatbot flow. The code runs synchronously, with asynchronous operations (like API calls) using callbacks.

Basic structure:

// Access the user's message
var message = GetMessageText();

// Process and respond
if (message.toLowerCase() === 'hello') {
  SendTextMessage('Hi there! How can I help you?');
}

// Route to the next flow step
RouteTo('main-menu');

Note
Code execution has a 2-second timeout and 1MB memory limit. Long-running operations will be terminated.

Callback Pattern

How to handle asynchronous operations using callbacks.

Functions that perform network requests use callbacks to return results. The callback receives two parameters: error and data.

GetJSON('https://api.example.com/data', function(error, data) {
  if (error) {
    SendTextMessage('Sorry, something went wrong.');
    LogBotError('API Error: ' + error);
  } else {
    SendTextMessage('Result: ' + data.value);
  }
  RouteTo('next-step');
});

Warning
Only one asynchronous request can be active at a time. Starting a second request before the first completes will result in an error.

User Input

Functions for reading user input and interaction data.

GetMessageText

Get the text message sent by the user.

Syntax:

var text = GetMessageText();

Returns: string - The user's message text.

Example:

var message = GetMessageText();
if (message.includes('pricing')) {
  RouteTo('pricing-info');
} else {
  RouteTo('general-help');
}

GetQuickReply

Get the quick reply option selected by the user.

Syntax:

var selection = GetQuickReply();

Returns: string - The value of the selected quick reply option, or undefined if no quick reply was selected.

Example:

var choice = GetQuickReply();
if (choice === 'sales') {
  RouteTo('sales-team');
} else if (choice === 'support') {
  RouteTo('support-team');
}

GetUserLastBotMessageText

Get the last message the user sent to the bot.

Syntax:

var lastMessage = GetUserLastBotMessageText();

Returns: string - The user's last message to the bot.

Tips
  • Useful when handling flow confusion to understand what the user was trying to say

Sending Messages

Functions for sending messages to the user.

SendTextMessage

Send a text message to the user.

Syntax:

SendTextMessage(message);

Note
This function can be called up to 5 times per Logic Block execution.
ParameterTypeDescription
messagestringThe text message to send

Example:

var user = UserGet();
SendTextMessage('Hello ' + user.first_name + '! Welcome back.');

SendQuickReply

Send a message with quick reply options for the user to select.

Syntax:

SendQuickReply(message, options);

Note
The maximum number of options depends on the messaging channel (e.g., WhatsApp supports up to 3 quick replies).
ParameterTypeDescription
messagestringThe message to display above the options
optionsarrayArray of quick reply option strings

Example:

SendQuickReply('How can I help you today?', [
  'Sales Inquiry',
  'Technical Support',
  'Billing Question',
  'Other'
]);

SendButtonURL

Send a message with a URL button.

Syntax:

SendButtonURL(text, buttonText, url);

Note
This function can be called up to 5 times per Logic Block execution.
ParameterTypeDescription
textstringThe message text
buttonTextstringThe text displayed on the button
urlstringThe URL to open when clicked

Example:

SendButtonURL(
  'Check out our latest products!',
  'View Products',
  'https://example.com/products'
);

SendEmail

Send an email notification.

Syntax:

SendEmail(emailObject);

Note
This function can be called up to 2 times per Logic Block execution.
FieldTypeRequiredDescription
tostringYesRecipient email address
subjectstringYesEmail subject line
contentstringYesEmail body content (plain text or HTML)
replytostringNoReply-to email address

Example:

var user = UserGet();
SendEmail({
  to: 'sales@example.com',
  subject: 'New Lead from Chatbot',
  content: 'Name: ' + user.name + '\nPhone: ' + user.phone + '\nEmail: ' + user.email,
  replyto: user.email
});

SendForm

Send an interactive form to the user.

Syntax:

SendForm(formObject);

Form objects allow you to collect structured data from users through an interactive form interface.

Note
Form availability depends on the messaging channel. Check channel documentation for supported form types.

User Data Management

Functions for reading and updating user information.

UserGet

Get the current user's profile information.

Syntax:

var user = UserGet();

Returns: An object containing user profile fields.

FieldTypeDescription
uidstringUnique user identifier
namestringUser's full name
first_namestringUser's first name
last_namestringUser's last name
emailstringUser's email address
phonestringUser's phone number
notesstringNotes associated with user
langstringUser's language code (e.g., "en")
botstringSource channel (Telegram, Messenger, Web, Line, Viber, WA3)
countrystringUser's country (if available)
urlstringDirect URL to chat with this user

Example:

var user = UserGet();
if (user.lang === 'es') {
  SendTextMessage('¡Hola ' + user.first_name + '!');
} else {
  SendTextMessage('Hello ' + user.first_name + '!');
}

UserSet

Update the current user's profile information.

Syntax:

UserSet(userData);

FieldTypeDescription
namestringUser's full name
first_namestringUser's first name
last_namestringUser's last name
emailstringUser's email address
phonestringUser's phone number
notesstringNotes associated with user
langstringUser's language code

Example:

var email = GetMessageText();
if (ValidateEmail(email)) {
  UserSet({ email: email });
  SendTextMessage('Thanks! Your email has been saved.');
} else {
  SendTextMessage('That doesn\'t look like a valid email address.');
}

UserDataGet

Get custom data stored for the user.

Syntax:

var data = UserDataGet();

Returns: object - Custom user data object, or empty object if none exists.

Example:

var data = UserDataGet();
if (data.preferences) {
  SendTextMessage('Your preferred language is: ' + data.preferences.language);
}

Tips
  • Use this to store conversation state, user preferences, or any custom data
  • Data persists across conversations

UserDataSet

Store custom data for the user.

Syntax:

UserDataSet(dataObject);

Example:

var existingData = UserDataGet();
existingData.lastVisit = new Date().toISOString();
existingData.visitCount = (existingData.visitCount || 0) + 1;
UserDataSet(existingData);

Warning
The data object replaces any existing custom data. Merge with existing data if needed.

UserWebGet

Get web session details for web widget users.

Syntax:

var webData = UserWebGet();

Returns: object - Web session data including browser info and IP location.

Example:

var web = UserWebGet();
if (web.iploc) {
  SendTextMessage('It looks like you are in ' + web.iploc.city);
}

AgentDisplayDataGet

Get custom data displayed to agents in the chat panel.

Syntax:

var displayData = AgentDisplayDataGet();

Returns: object - Custom agent display data, or empty object if none exists.

AgentDisplayDataSet

Set custom data to display to agents in the chat panel.

Syntax:

AgentDisplayDataSet(dataObject);

Example:

// Show customer tier and account info to agents
AgentDisplayDataSet({
  'Customer Tier': 'Premium',
  'Account ID': 'ACC-12345',
  'Open Cases': 2
});

Tips
  • Use simple key-value pairs for best display in the agent interface
  • This data is visible to agents when they handle the chat

CrmIdGet

Get the CRM identifier for the user.

Syntax:

var crmId = CrmIdGet();

Returns: string or object - The CRM ID or object associated with this user.

CrmIdSet

Set the CRM identifier for the user.

Syntax:

CrmIdSet(crmId);

Example:

// After looking up user in CRM
CrmIdSet('SF-CONTACT-12345');

IsUserUnsubscribed

Check if the user has unsubscribed from outgoing messages.

Syntax:

var unsubscribed = IsUserUnsubscribed();

Returns: 1 if unsubscribed, 0 if subscribed.

Example:

if (IsUserUnsubscribed()) {
  SendTextMessage('You are currently unsubscribed from promotional messages.');
}

UserUnsubscribe

Unsubscribe the user from outgoing promotional content.

Syntax:

UserUnsubscribe();

Example:

UserUnsubscribe();
SendTextMessage('You have been unsubscribed. You will no longer receive promotional messages.');

UserSubscribe

Subscribe the user to receive outgoing promotional content.

Syntax:

UserSubscribe();

Routing

Functions for controlling conversation flow and routing to agents.

RouteTo

Route the conversation to a named flow step.

Syntax:

RouteTo(routeName);

Warning
If the route name doesn't match any defined route in the flow, an error message will be sent to the user and logged.
ParameterTypeDescription
routeNamestringThe name of the route defined in the flow editor

Returns: 1 if route exists, undefined if route not found.

Example:

var choice = GetQuickReply();
switch(choice) {
  case 'products':
    RouteTo('product-catalog');
    break;
  case 'support':
    RouteTo('support-menu');
    break;
  default:
    RouteTo('main-menu');
}

RouteToAgent

Route the conversation to a human agent.

Syntax:

RouteToAgent(message);

ParameterTypeDescription
messagestringInitial message to show the agent

Example:

var user = UserGet();
RouteToAgent('Customer ' + user.name + ' needs help with billing');

RouteToBusinessUnit

Route the conversation to agents in a specific business unit.

Syntax:

RouteToBusinessUnit(message, businessUnit);

Warning
If the business unit doesn't exist, an error will be thrown. Use DoesBUExistForOrg to verify first.
ParameterTypeDescription
messagestringInitial message to show the agent
businessUnitstringName of the business unit

Example:

var choice = GetQuickReply();
if (choice === 'technical') {
  RouteToBusinessUnit('Technical support request', 'Tech Support');
} else {
  RouteToBusinessUnit('General inquiry', 'Customer Service');
}

DoesBUExistForOrg

Check if a business unit exists for the organization.

Syntax:

var exists = DoesBUExistForOrg(businessUnitName);

Returns: 1 if exists, 0 if not.

Example:

var bu = 'Premium Support';
if (DoesBUExistForOrg(bu)) {
  RouteToBusinessUnit('VIP customer request', bu);
} else {
  RouteToAgent('Customer request');
}

AllocateToAgent

Allocate the chat to a specific agent by email.

Syntax:

var result = AllocateToAgent(agentEmail);

Returns:

  • 1 - Successfully allocated
  • -1 - Agent not found

Example:

var result = AllocateToAgent('john.smith@company.com');
if (result === 1) {
  SendTextMessage('You have been connected to John.');
} else {
  SendTextMessage('That agent is not available. Connecting you to the next available agent.');
  RouteToAgent('Requested specific agent');
}

Agent Status

Functions for checking agent availability and managing agent assignments.

AreAgentOnline

Check if any agents are currently online.

Syntax:

var online = AreAgentOnline();

Returns: 1 if agents are online, 0 if none are online.

Example:

if (AreAgentOnline()) {
  SendTextMessage('An agent will be with you shortly.');
  RouteToAgent('Customer waiting');
} else {
  SendTextMessage('Our team is currently offline. Please leave a message.');
  RouteTo('leave-message');
}

Note
This only checks if agents are logged in, not whether they are available to take new chats.

AreAgentOnlineAndActive

Check if agents are online and not busy, optionally filtered by business units.

Syntax:

var active = AreAgentOnlineAndActive(bu1, bu2, ...);

ParameterTypeDescription
bu1, bu2, ...stringOptional business unit names to filter by

Returns: 1 if matching agents are available, 0 otherwise.

Example:

// Check if any agent is available
if (AreAgentOnlineAndActive()) {
  RouteToAgent('Customer request');
}

// Check specific business units
if (AreAgentOnlineAndActive('Sales', 'Premium Support')) {
  RouteToBusinessUnit('Sales inquiry', 'Sales');
}

GetLoggedInAgentsWithBU

Get information about all logged-in agents and their business units.

Syntax:

var agents = GetLoggedInAgentsWithBU();

Returns: object - Details of logged-in agents with their business unit assignments.

Tips
  • Useful for logging and debugging routing decisions

OrganizationOutOfHours

Check if it's currently outside the organization's working hours.

Syntax:

var outOfHours = OrganizationOutOfHours();

Returns: 1 if outside working hours, 0 if within working hours.

Example:

if (OrganizationOutOfHours()) {
  SendTextMessage('We are currently closed. Our business hours are 9am-5pm Monday-Friday.');
  RouteTo('after-hours-menu');
} else {
  RouteTo('main-menu');
}

AgentGet

Get details about a specific agent.

Syntax:

var agent = AgentGet(agentEmail);

Returns: object with agent details, or undefined if not found.

FieldTypeDescription
emailstringAgent's email address
buarrayBusiness units the agent belongs to
onlinenumber1 if online, 0 if offline

Example:

var agent = AgentGet('john.smith@company.com');
if (agent && agent.online) {
  SendTextMessage('John is available to help you.');
  AllocateToAgent('john.smith@company.com');
}

IsAgentEmailValid

Check if an agent email exists in the organization.

Syntax:

var valid = IsAgentEmailValid(agentEmail);

Returns: 1 if valid, 0 if not found.

IsUserChattingToAgent

Check if the user is currently chatting with an agent.

Syntax:

var agentEmail = IsUserChattingToAgent();

Returns: Agent's email address if chatting, undefined otherwise.

Example:

var currentAgent = IsUserChattingToAgent();
if (currentAgent) {
  SendTextMessage('You are currently chatting with an agent.');
} else {
  SendTextMessage('You are chatting with our bot.');
}

Sticky Agents

Functions for assigning users to specific agents permanently.

StickUserToAgent

Permanently assign a user to a specific agent.

Syntax:

var result = StickUserToAgent(agentEmail);

Returns: 1 if successful, 0 if agent not found.

Example:

// Assign VIP customers to their account manager
var userData = UserDataGet();
if (userData.accountManager) {
  StickUserToAgent(userData.accountManager);
}

Tips
  • Future chats from this user will be routed to the sticky agent when they are online

UnstickUserFromAgent

Remove the sticky agent assignment for the user.

Syntax:

UnstickUserFromAgent();

IsUserStuckToAgent

Check if the user has a sticky agent assignment.

Syntax:

var agentEmail = IsUserStuckToAgent();

Returns: Agent's email if stuck, undefined otherwise.

Validation

Functions for validating user input.

ValidateEmail

Validate an email address format.

Syntax:

var valid = ValidateEmail(email);

Returns: 1 if valid, undefined if invalid.

Example:

var email = GetMessageText();
if (ValidateEmail(email)) {
  UserSet({ email: email });
  RouteTo('email-confirmed');
} else {
  SendTextMessage('Please enter a valid email address.');
  RouteTo('ask-email');
}

ValidatePhoneNumber

Validate a phone number and get formatted details.

Syntax:

var phoneInfo = ValidatePhoneNumber(phoneNumber);

Returns: Phone information object if valid, undefined if invalid.

FieldTypeDescription
formatstringE.123 formatted number (e.g., "+44 20 8771 2924")
country_codestringCountry dialing code without + (e.g., "44")
countrystringISO country code (e.g., "GB")
numberstringNumber without country code
fullnumberstringFull number with country code

Example:

var input = GetMessageText();
var phone = ValidatePhoneNumber(input);
if (phone) {
  UserSet({ phone: phone.fullnumber });
  SendTextMessage('Phone saved: ' + phone.format);
  RouteTo('phone-confirmed');
} else {
  SendTextMessage('Please enter a valid phone number with country code.');
  RouteTo('ask-phone');
}

Country Information

Functions for looking up country details.

Country

Look up country information by code or name.

Syntax:

var countryInfo = Country(query);

FieldTypeDescription
code_alpha2string2-letter ISO code (e.g., "US")
code_alpha3string3-letter ISO code (e.g., "USA")
code_numericstringNumeric ISO code
namestringCountry name
dialing_codestringPhone dialing code
continentstringContinent name
currencystringCurrency code (e.g., "USD")
timezonestringPrimary timezone name
languagesarrayOfficial languages

Example:

var country = Country({ code_alpha2: 'GB' });
if (country) {
  SendTextMessage('Currency in ' + country.name + ' is ' + country.currency);
}

CountryFromPhoneNumber

Get country information from a phone number.

Syntax:

var country = CountryFromPhoneNumber(phoneNumber);

Returns: Country information object (same as Country function) or undefined.

Example:

var user = UserGet();
var country = CountryFromPhoneNumber(user.phone);
if (country) {
  SendTextMessage('Your local currency is ' + country.currency);
}

CountryCodeFromIP

Get the country code from the user's IP address (web widget users only).

Syntax:

var countryCode = CountryCodeFromIP();

Returns: 2-letter ISO country code, or empty string if unavailable.

Example:

var code = CountryCodeFromIP();
if (code === 'JP') {
  SendTextMessage('こんにちは!');
} else {
  SendTextMessage('Hello!');
}

HTTP Requests

Functions for making HTTP requests to external APIs.

GetJSON

Make an HTTP GET request and parse JSON response.

Syntax (simple):

GetJSON(url, callback);

Syntax (with headers):

GetJSON({ url: url, headers: headers }, callback);

Note
Requests have a 10-second timeout. The response must be valid JSON.
ParameterTypeDescription
urlstringThe URL to request
headersobjectOptional HTTP headers
callbackfunctionCallback function(error, data)

Example (simple):

GetJSON('https://api.example.com/products', function(error, data) {
  if (error) {
    LogBotError('API Error: ' + error);
    SendTextMessage('Sorry, I couldn\'t fetch the data.');
  } else {
    SendTextMessage('Found ' + data.products.length + ' products.');
  }
  RouteTo('next-step');
});

Example (with headers):

GetJSON({
  url: 'https://api.example.com/user/profile',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Accept': 'application/json'
  }
}, function(error, data) {
  if (!error) {
    SendTextMessage('Welcome, ' + data.name);
  }
  RouteTo('next-step');
});

PostJSON

Make an HTTP POST request with JSON body.

Syntax (simple):

PostJSON(url, data, callback);

Syntax (with headers):

PostJSON({ url: url, headers: headers }, data, callback);

FieldTypeDescription
codenumberHTTP status code
dataobjectParsed JSON response

Example:

var user = UserGet();
var payload = {
  name: user.name,
  email: user.email,
  source: 'chatbot'
};

PostJSON('https://api.example.com/leads', payload, function(error, response) {
  if (error) {
    LogBotError('Failed to create lead: ' + error);
  } else if (response.code === 201) {
    SendTextMessage('Thanks! We\'ll be in touch soon.');
    CrmIdSet(response.data.leadId);
  } else {
    SendTextMessage('Something went wrong. Please try again.');
  }
  RouteTo('complete');
});

SendToAPI

Send data to your organization's configured API webhook.

Syntax:

SendToAPI(data, callback);

Note
Requires the Convrs API to be enabled with a webhook URL configured. See the Convrs API documentation.
ParameterTypeDescription
dataobjectCustom data to send to your webhook
callbackfunctionCallback function(error, response)

Example:

var user = UserGet();
SendToAPI({
  action: 'customer_inquiry',
  uid: user.uid,
  topic: GetMessageText()
}, function(error, response) {
  if (!error && response.processed) {
    SendTextMessage(response.message);
  }
  RouteTo('next-step');
});

AI

Generate AI-powered text responses using generative AI.

Syntax:

AI(prompt, callback);

Note
This function requires AI features to be enabled for your organization.
Warning
AI responses may have latency. Keep prompts concise for faster responses.
ParameterTypeDescription
promptstringThe prompt to send to the AI
callbackfunctionCallback function(error, response)

Example:

var question = GetMessageText();
var prompt = 'You are a helpful customer service assistant. Answer this question briefly: ' + question;

AI(prompt, function(error, answer) {
  if (error) {
    SendTextMessage('Sorry, I couldn\'t process that. Let me connect you to an agent.');
    RouteToAgent('AI failed: ' + question);
  } else {
    SendTextMessage(answer);
    RouteTo('follow-up');
  }
});

SalesForce

Call a configured Salesforce function.

Syntax:

SalesForce(functionName, data, callback);

Note
Requires Salesforce integration to be configured for your organization.
ParameterTypeDescription
functionNamestringName of the configured Salesforce function
dataobjectData to pass to the function
callbackfunctionCallback function(error, result)

Example:

var user = UserGet();
SalesForce('lookupContact', { email: user.email }, function(error, contact) {
  if (error) {
    LogBotError('Salesforce lookup failed: ' + error);
  } else if (contact) {
    AgentDisplayDataSet({
      'SF Contact': contact.Name,
      'Account': contact.Account.Name
    });
  }
  RouteTo('next-step');
});

WhatsApp

Functions specific to WhatsApp Business API conversations.

WhatsAppTemplateGet

Get details of the last WhatsApp template the user interacted with.

Syntax:

var template = WhatsAppTemplateGet();

Returns: Template object if available, undefined otherwise.

Example:

var template = WhatsAppTemplateGet();
if (template && template.name === 'order_confirmation') {
  // User clicked a button on the order confirmation template
  RouteTo('order-inquiry');
} else {
  RouteTo('general-menu');
}

Tips
  • Use this to handle template button clicks with contextual routing

Time and Date

Functions for working with time and dates.

TimeNowInUTC

Get the current time in UTC as an integer.

Syntax:

var time = TimeNowInUTC();

Returns: number - Time as HHMMSS integer (e.g., 143052 for 14:30:52).

Example:

var time = TimeNowInUTC();
if (time >= 90000 && time < 170000) {
  // Between 9:00 and 17:00 UTC
  SendTextMessage('Our team is available to help.');
} else {
  SendTextMessage('We are currently outside business hours.');
}

DayOfWeekUTC

Get the current day of the week in UTC.

Syntax:

var day = DayOfWeekUTC();

Returns: number - Day of week (1=Monday, 7=Sunday).

Example:

var day = DayOfWeekUTC();
if (day >= 6) {
  // Saturday or Sunday
  SendTextMessage('Our offices are closed on weekends.');
  RouteTo('weekend-menu');
} else {
  RouteTo('weekday-menu');
}

Utilities

Utility functions for common operations.

RandomString

Generate a random string based on a pattern.

Syntax:

var str = RandomString(pattern);

Pattern CharDescription
cLowercase letter (a-z)
CUppercase letter (A-Z)
nDigit (0-9)
!Punctuation character
.Any character
sAlphanumeric (a-z, A-Z, 0-9)

Example:

// Generate a 6-digit verification code
var code = RandomString('nnnnnn');
UserDataSet({ verificationCode: code });
SendTextMessage('Your verification code is: ' + code);

// Generate a reference number
var ref = 'REF-' + RandomString('CCCCnnnn');
SendTextMessage('Your reference number: ' + ref);

LogBotError

Log an error message to the bot error log.

Syntax:

LogBotError(message);

Example:

GetJSON('https://api.example.com/data', function(error, data) {
  if (error) {
    LogBotError('External API failed: ' + error);
    // Handle gracefully
    RouteTo('fallback');
  } else {
    RouteTo('success');
  }
});

Tips
  • Use for debugging and monitoring bot issues
  • Errors are visible in the Bot Errors section of the dashboard
Create a Chatbot Chatbot Settings