Product Guide
APIsProductUpdatesPricingFAQs
  • Introduction to REVE Chat
  • Integrations
    • Website
    • Social Media Channels
      • WhatsApp
      • Instagram Messaging and Comment
      • Facebook Messenger and Comment
      • Viber
      • Telegram
    • Direct Chat Page
    • Mobile SDK
      • Native Android SDK
      • Native iOS SDK
      • Flutter Android SDK
      • Flutter iOS SDK
      • React Native iOS SDK
      • React Native Android SDK
    • Email Integration
      • Forward emails to your REVE Chat tickets
      • Integrate Your Business Email
        • Connecting Gmail with POP/IMAP Settings
    • All Integrations
      • CRM Integrations
        • Pipedrive
        • Salesforce
        • HubSpot
        • MS Dynamics
        • Amo CRM
        • Agile CRM
        • Vtiger
        • Capsule
        • Infusionsoft (by Keap)
      • CMS Integration
        • WordPress
        • DotNet Nuke
        • Blogger
        • Joomla
        • Drupal
        • ModX
      • E-commerce
        • Shopify
        • Bigcommerce
        • WooCommerce
        • Prestashop
        • 3dCart
        • Pinnacle Cart
        • Corecommerce
        • BigCartel
        • ECWID
        • LemonStand
        • Ebay
        • Volusion
        • Americommerce
        • osCommerce
        • Magento
          • By Manual Code Injection
        • Zencart
        • XCart
        • OpenCart (V4.0.x)
          • OpenCart (Old Version Integration)
        • CSCart
        • Abantecart
      • Website Builder
        • Wix
      • Hosting Platform
        • Plesk
        • WHMCS
      • Analytics
        • Google Tag Manager
        • Google Analytics
    • Google Integration
      • YouTube Integration
      • Google Play Store
      • Google Business Account
  • Appstore
  • Customization
  • Inbox
    • Breaking Down of Single Inbox
    • Folders of Single Inbox
    • How Conversation Works!
    • Chat Monitoring for All Ongoing Agents' Chat
    • Chat History for All Closed Conversations
    • Proactive Chat Management
    • Voice & Video Call
    • Co-Browsing
    • How to use Shortcuts
    • Inbox Appearance
  • Contacts
    • Manage Your Contacts
    • Segments
  • WhatsApp Campaign
    • What is WhatsApp Campaign?
      • Broadcast: Send Campaigns
      • Templates: Create Campaign
  • Tickets
    • Set up your Ticketing email
    • Create Ticket
    • Knowing your Ticketing tables
    • Managing a Ticket
  • Chatbot
    • Bot Builder
      • Response Elements
        • Text Action
        • Quick Reply Action
        • Carousel Action
        • Button Action
        • Send Email
      • Data Collection
        • Ask Name
        • Ask Phone
        • Ask Email
        • Ask Question
        • Ask OTP
        • Ask File
        • Ask Date
        • Ask Time
        • Forms
        • Ask Number
      • Media
        • Image Action
        • Audio Action
        • Video Action
        • File Action
      • Workflow Action
        • Condition Action
        • Chat Transfer Action
        • Close Chat
        • Appointment Action
        • Attribute Action
        • Business Hour
        • System Attributes
      • Advanced Action
        • Salesforce Bot Action Manual
        • API Connector
        • Goal
        • Dynamic Data
    • Brain AI
      • ChatGPT Integration
    • Settings
      • Bot Profile
      • General Settings
      • Webhook
    • Training
      • Intent Sample
      • Sentiment
      • Synonyms
      • FAQ
      • Untrained
      • Trained
      • Bulk Training
    • Multilingual Bot
  • Reports
    • Summary
    • Chat Satisfaction
    • Chatbot Report
      • Bot Engagement
      • Flow Engagement
      • Goal Analysis
    • Agent Analytics
      • Agent Activity
      • Agent Performance
      • Metrics
      • SLA Breach Analysis
    • Visitor Analytics
    • Enterprise Report
      • Daily Agent Performance
      • Hourly Agent Performance
      • Daily Group Performance
      • Traffic Analysis Report
      • First Response Time
  • User Profile
    • Billing
    • Help & Feedback
  • Settings
    • General Settings
      • Auto Triggers
      • Forms
        • Pre Chat Form
        • Post Chat Form
        • Custom Forms
          • Advanced Forms
        • Ticket Forms
      • Canned Responses
      • Custom Attributes
      • Call Recording
      • Tags
      • Appointment
      • Departments
      • Chat Transcript Forwarding
      • Ban Visitor
      • Trusted IP & Domain
      • Business Hour
    • Chat Widgets
      • Appearance
      • Custom Message
      • Widget Features
      • Forms
      • Code Snippet & Quick Share
    • Ticketing
      • Email Templates
      • Status Management
    • Agent Management
      • Agents
      • Departments
      • Role Management
    • API Settings
      • Json Parse Format
    • Scripts
    • SLA Policy
    • Routing Policy in REVE Chat
      • Chat Routing
      • Advanced Routing
    • Other Settings
Powered by GitBook
On this page
  • Why do you need Scripts?
  • How to use Scripts in Chatbot
  • 1. Creating Scripts for your bot​
  • 2. Script argument to access user data
  • 3. Save values in attribute
  • 4. Publishing a Script
  • How Scripts work
  • 1. Display user ID
  • 2. Process current data and time
  • 3. Custom date range formatter and save value
  • What Next?

Was this helpful?

  1. Settings

Scripts

Scripts enhance your bot’s capabilities by enabling custom logic and actions beyond standard features. Learn how to use Scripts in REVE Chat, it lets you easily add JavaScript code in chatbot!

PreviousJson Parse FormatNextSLA Policy

Last updated 6 months ago

Was this helpful?

Why do you need Scripts?

With Scripts, your bot can perform tasks like formatting dates for readability, extracting specific data from user input, breaking down complex queries responses, modify and update attribute values and much more.

  • Tailored Logic Integration: Scripts allow you to add customized logic to meet specific needs not covered by default bot features.

  • More Flexibility: Custom Scripts let you handle complex operations, and connect with external systems.

  • Smooth Integration: Scripts make it easy to connect with third-party APIs, databases, and external services, expanding the bot’s capabilities.

How to use Scripts in Chatbot

To create a function, follow these steps:

  1. Go to Settings > General Settings > Scripts > Create Script.

  2. Provide a specific name to your script and click on the Create button.

  3. Add your script in the newly created script page

  4. Go to the chatbot and use Script action within the flow

You can create a custom script using JavaScript to implement specific functionality for your bot. Use the following code template and simply replace 'Write your code here' with the actions or logic you want to execute:

You can define a custom function using JavaScript. Here is a sample code snippet. Just replace the placeholder 'Your logic goes here' with the specific functionality you wish to implement.

return new Promise(resolve => {  
      // Write your code here
      resolve();
  }); 

2. Script argument to access user data

In programming, arguments act as inputs that let the bot access specific information or execute defined actions within your code, creating more targeted and dynamic responses.

To access user-specific information, use: data.attribute_name , where <attribute_name> is a variable. Here, you can use any system attribute of REVE Chat or custom attributes you have created to use the variable data directly within the script.

3. Save values in attribute

1. Single Attribute Storage

In some cases, you might want to save all returned data in a single attribute. For example, you might want to store a single piece of information like user_status or a complete return value as a single entry. This is useful for smaller or consolidated data needs.

2. Multiple Attribute Updates (Example Code Below)

If you need to manage several pieces of user data, you can use a custom JavaScript script to assign values to multiple attributes at once. This method is particularly useful when handling several pieces of data, such as user contact details, preferences, or responses, in one go.

Here’s an example of how to update multiple attributes:

// You can set multiple attribute using our script function. A sample script function is given below.
return new Promise(resolve => {  
      //set variables
      let name = data.name;
      let phone = data.phone;

//return below object with type value "set_variables" to update multiple attributes at a time
      let returnObj = {
            type: "set_variables",
            variables: {
                  name: name,
                  phone: phone
            }
      };
      resolve(returnObj);
});

4. Publishing a Script

To publish a script, you need to test the script if it is working fine or not.

  1. Simple Scripts (Returning Only Value or JSON): Click the Test Now button. If everything works correctly, you can then publish the script.

  2. Scripts with Dynamic Values from Attributes:

    • Provide sample values for any attributes referenced in the script. You can use text, numeric, or Json response as your sample variable depending on the type of your script.

    • Click Test Now to verify the script before publishing.

  3. One your script is ready and works perfectly, live the script to use in chatbot.

Note: If you use data.attribute_name to reference attributes, you must define sample values to avoid undefined values during testing.

How Scripts work

This section explains how scripts operate within your bot, starting with simple examples and progressing to more complex scenarios to help you build your skills step-by-step.

The following code examples include some fundamental JavaScript concepts:

  • let: Declares a variable to store data.

  • resolve: Completes a promise and returns the function's output.

  • if/else: Allows the bot to make decisions based on conditions.

1. Display user ID

The following example demonstrates how to display the current user ID:

return new Promise(resolve => {
    let internal_user_id = data.internal_user_id;  // Retrieve the user ID from the data object 
    resolve(`The current user ID is ${internal_user_id}`); // Return a message with the user ID 
});

Explanation

  • Access User ID: The internal_user_id variable is set to the user ID by accessing data.internal_user_id.

  • Display Message: The function returns a message containing the user ID, which will be shown to the user.

Output: The current user ID is [internal_user_id]

2. Process current data and time

The following code snippet captures the current date and time in the Asia/Kolkata time zone, formats it, and logs the results. The function then returns the current date.

return new Promise(resolve => {
    let currentdate = new Date();  // Captures the system’s current date and time
    let currentTime = new Date().toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata' });
   
    
    resolve(currentdate);              // Returns the current date
});

Explanation

  • Retrieve Current Date: currentdate is initialized with the system's current date and time.

  • Set and Format Current Time:

    • let currentTime: Declares a variable for the formatted time.

    • new Date(): Creates a Date object for the current date and time.

    • .toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata' }): Formats the time for the India (en-IN) locale in the Asia/Kolkata time zone, displaying it in Indian Standard Time (IST).

  • Return Date: The function resolves with the current date, completing the operation.

Output: This script logs the current date and formatted time (Asia/Kolkata time zone) to the console and returns the current date.

3. Custom date range formatter and save value

This script calculates and formats a date range, providing the start of the current month and the current date and time in a custom "YYYYMMDDHHMMSS" format.

return new Promise(resolve => {
    function getDatesInCustomFormat() {
        // Get the current date
        const now = new Date();
        
        // Get the timezone offset in milliseconds
        const timezoneOffset = now.getTimezoneOffset() * 60000;

        // Calculate the start date (first day of the current month) in local timezone
        const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        const startDateLocal = new Date(startDate.getTime() - timezoneOffset);

        // Calculate the end date (current date and time) in local timezone
        const endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
        const endDateLocal = new Date(endDate.getTime() - timezoneOffset);

        // Helper function to format date as YYYYMMDDHHMMSS
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}${month}${day}${hours}${minutes}${seconds}`;
        }

        // Return the result as a JSON object with 'from' and 'to' keys
        return {
            start_time: formatDate(startDateLocal),
            current_time: formatDate(endDateLocal)
        };
    }

    // Resolve the promise with the result of the function
    resolve(getDatesInCustomFormat());
});

Explanation

  1. Get Current Date and Time (now): The now variable captures the current date and time for calculating both the start and end dates.

  2. Adjust for Timezone Offset: timezoneOffset converts the timezone offset from minutes to milliseconds. This ensures that calculations adjust for the local time zone.

  3. Calculate Start and End Dates:

    • Start Date: startDate is set to the first day of the current month at midnight. Then, startDateLocal is created by adjusting for the timezone offset.

    • End Date: endDate is set to the current date at 23:59:59 (end of the day). endDateLocal adjusts this date to the local timezone.

  4. Format Dates (Helper Function): The formatDate function converts a Date object into the "YYYYMMDDHHMMSS" format:

    • Formatting Components: The year, month, day, hours, minutes, and seconds are extracted and padded to two digits where needed.

    • Return Formatted String: These values are combined into a formatted string (e.g., "20241027111559").

  5. Return JSON Object: The function returns a JSON object with:

    • start_time: The formatted start date for the month.

    • current_time: The formatted current date and time.

  6. Resolve the Promise: The promise is resolved with the formatted JSON object, making this data available for further use.

Output: This script returns a JSON object with the start time of the month and the current date and time in "YYYYMMDDHHMMSS" format, adjusted for local timezone.

{
  "start_time": "20241001060000",
  "current_time": "20241028055959"
}

What Next?

1. Creating Scripts for your bot

Create your own function and use it by adding an API action in the chatbot flow.

Any questions? Please email us at or .

​
Get the list of system attributes
Learn more about custom attributes
Lean how API works.
issue.support@revechat.com
scan to chat with us
Add the script action in chatbot
Test the return value of the script you stored in an attribute