Skip to main content

03.02 Using AI to Generate Code

An AI assistant is provided in the JavaScript node. It helps to generate or adjust the code according to the needs.

To use the assistant, you need to specify a command, i.e. a specific request. The bot will then generate a response based on your query and understanding of the context.

The response will contain the code with comments and explanation of the assistant.

Request to process data from other nodes
note
Generate code to process data from the Trigger on Webhook node so that based on the Name and Count parameters, text is generated based on the following pattern: Hi, Name! Count of your scenarios has been executed in X on the Latenode platform! Instead of X, substitute the name of the current month.

The assistant will provide the answer:

To generate the required text based on the parameters from the "Trigger on Webhook" node, you can follow these steps inside the provided run function. First, we'll extract the Name and Count values from the data provided by the webhook node with ID 4. Then, we'll use JavaScript's Date object to get the current month and format it as a name. Finally, we'll construct the message according to the pattern you've requested.

Here is how you can do it:

export default async function run({execution_id, input, data, store}) {
// Extracting Name and Count from the webhook data
const name = data["{{4.\`body\`.\`Name\`}}"];
const count = data["{{4.\`body\`.\`Count\`}}"];

// Getting the current month as a name
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const currentMonthName = monthNames[new Date().getMonth()];

// Generating the message
const message = \`Hi, ${name}! ${count} of your scenarios has been executed in ${currentMonthName} on the Latenode platform!\`;

// Returning the generated message
return {
message
};
}

Explanation:

  • data["{{4.body.Name}}"] and data["{{4.body.Count}}"] access the Name and Count values from the webhook's body.
  • We use JavaScript's Date object to get the current month as an index (getMonth() returns a zero-based index for the months), and then we use this index to get the month's name from the monthNames array.
  • The message is constructed using template literals, embedding the namecount, and currentMonthName variables into the predefined text pattern.
  • Finally, the function returns an object containing the generated message, which can be used by subsequent nodes in your scenario.
Request for processing global variables
tip

It is assumed that global variables GlobalVar_number1 and GlobalVar_number2 exist in the account. See the section on global variables.

note
Generate code that adds up the values of two global variables GlobalVar_number1 and GlobalVar_number2 and return an array of the values: sum of variables, GlobalVar_number1, GlobalVar_number2. Get global variables using store.getGlobalVariable

The assistant will provide the answer:

To accomplish the task you've described, we will use the store.getGlobalVariable method to retrieve the values of the global variables GlobalVar_number1 and GlobalVar_number2. Then, we'll add these values together, and return an array that includes the sum, GlobalVar_number1, and GlobalVar_number2 in that order. Here's how you can do it:

export default async function run({execution_id, input, data, store}) {
// Retrieve the values of the global variables
const number1 = await store.getGlobalVariable('GlobalVar_number1');
const number2 = await store.getGlobalVariable('GlobalVar_number2');

// Convert the retrieved values to numbers, if they are not already
const num1 = parseFloat(number1);
const num2 = parseFloat(number2);

// Calculate the sum of the two numbers
const sum = num1 + num2;

// Return an array with the sum, GlobalVar_number1, and GlobalVar_number2
return {
result: [sum, num1, num2]
};
}

This code snippet does the following:

Ensure that the global variables GlobalVar_number1 and GlobalVar_number2 are set and contain numeric values. If these variables contain non-numeric values, parseFloat will return NaN, and the sum calculation will not work as expected.

Request to connect to Telegram to send messages
note
Generate a code with a Telegram connection to send a message to the desired chat room with a given ID

The assistant will provide the answer:

To send a message to a Telegram chat room, you will need to use the Telegram Bot API. First, ensure you have created a bot and obtained your bot's API token from BotFather in Telegram. Then, you can use the axios library to make HTTP requests to the Telegram API. Here’s how you can do it:

Here's an example code snippet that sends a message to a specified chat ID using a Telegram bot:

import axios from 'axios';

export default async function run({execution_id, input, data, store}) {
// Your Telegram Bot Token
const botToken = 'YOUR_BOT_TOKEN_HERE';

// The chat ID you want to send a message to
const chatId = 'YOUR_CHAT_ID_HERE';

// The message you want to send
const message = 'Hello, this is a message from my bot!';

// Telegram API URL to send messages
const apiUrl = \`https://api.telegram.org/bot${botToken}/sendMessage\`;

try {
// Making a POST request to the Telegram API to send the message
const response = await axios.post(apiUrl, {
chat_id: chatId,
text: message,
});

// Returning the response from the Telegram API
return {
success: true,
response: response.data,
};
} catch (error) {
// Returning the error if the request failed
return {
success: false,
error: error.message,
};
}
}

Replace 'YOUR_BOT_TOKEN_HERE' with your actual Telegram bot token and 'YOUR_CHAT_ID_HERE' with the chat ID you want to send a message to.

Important Notes:
  • Ensure your bot is added to the chat room you want to send a message to.
  • The chat ID can be a user ID, group ID, or channel username (prepend with @ for channels).
  • This function runs asynchronously, leveraging axios for HTTP requests.
  • The code handles basic success and error cases, returning the API response or error message.