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 LimitationsThis 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');
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');
});
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.
- 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);
| Parameter | Type | Description |
|---|---|---|
message | string | The 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);
| Parameter | Type | Description |
|---|---|---|
message | string | The message to display above the options |
options | array | Array 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);
| Parameter | Type | Description |
|---|---|---|
text | string | The message text |
buttonText | string | The text displayed on the button |
url | string | The 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);
| Field | Type | Required | Description |
|---|---|---|---|
to | string | Yes | Recipient email address |
subject | string | Yes | Email subject line |
content | string | Yes | Email body content (plain text or HTML) |
replyto | string | No | Reply-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.
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.
| Field | Type | Description |
|---|---|---|
uid | string | Unique user identifier |
name | string | User's full name |
first_name | string | User's first name |
last_name | string | User's last name |
email | string | User's email address |
phone | string | User's phone number |
notes | string | Notes associated with user |
lang | string | User's language code (e.g., "en") |
bot | string | Source channel (Telegram, Messenger, Web, Line, Viber, WA3) |
country | string | User's country (if available) |
url | string | Direct 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);
| Field | Type | Description |
|---|---|---|
name | string | User's full name |
first_name | string | User's first name |
last_name | string | User's last name |
email | string | User's email address |
phone | string | User's phone number |
notes | string | Notes associated with user |
lang | string | User'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);
}
- 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);
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
});
- 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);
| Parameter | Type | Description |
|---|---|---|
routeName | string | The 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);
| Parameter | Type | Description |
|---|---|---|
message | string | Initial 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);
| Parameter | Type | Description |
|---|---|---|
message | string | Initial message to show the agent |
businessUnit | string | Name 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');
}
AreAgentOnlineAndActive
Check if agents are online and not busy, optionally filtered by business units.
Syntax:
var active = AreAgentOnlineAndActive(bu1, bu2, ...);
| Parameter | Type | Description |
|---|---|---|
bu1, bu2, ... | string | Optional 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.
- 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.
| Field | Type | Description |
|---|---|---|
email | string | Agent's email address |
bu | array | Business units the agent belongs to |
online | number | 1 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);
}
- 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.
| Field | Type | Description |
|---|---|---|
format | string | E.123 formatted number (e.g., "+44 20 8771 2924") |
country_code | string | Country dialing code without + (e.g., "44") |
country | string | ISO country code (e.g., "GB") |
number | string | Number without country code |
fullnumber | string | Full 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);
| Field | Type | Description |
|---|---|---|
code_alpha2 | string | 2-letter ISO code (e.g., "US") |
code_alpha3 | string | 3-letter ISO code (e.g., "USA") |
code_numeric | string | Numeric ISO code |
name | string | Country name |
dialing_code | string | Phone dialing code |
continent | string | Continent name |
currency | string | Currency code (e.g., "USD") |
timezone | string | Primary timezone name |
languages | array | Official 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);
| Parameter | Type | Description |
|---|---|---|
url | string | The URL to request |
headers | object | Optional HTTP headers |
callback | function | Callback 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);
| Field | Type | Description |
|---|---|---|
code | number | HTTP status code |
data | object | Parsed 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);
| Parameter | Type | Description |
|---|---|---|
data | object | Custom data to send to your webhook |
callback | function | Callback 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);
| Parameter | Type | Description |
|---|---|---|
prompt | string | The prompt to send to the AI |
callback | function | Callback 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);
| Parameter | Type | Description |
|---|---|---|
functionName | string | Name of the configured Salesforce function |
data | object | Data to pass to the function |
callback | function | Callback 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');
});
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');
}
- 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 Char | Description |
|---|---|
c | Lowercase letter (a-z) |
C | Uppercase letter (A-Z) |
n | Digit (0-9) |
! | Punctuation character |
. | Any character |
s | Alphanumeric (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');
}
});
- Use for debugging and monitoring bot issues
- Errors are visible in the Bot Errors section of the dashboard