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!

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

    Add the script action in chatbot
    Test the return value of the script you stored in an attribute

1. Creating Scripts for your bot

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.

Get the list of system attributes

Learn more about custom attributes

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?

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

Last updated

Was this helpful?