UNPKG

@getsolara/solara.js

Version:

A lightweight and modular Discord bot framework built on discord.js v14, with truly optional feature packages.

64 lines (54 loc) 2.79 kB
const StopExecutionError = require('../errors/StopExecutionError'); module.exports = { name: "$loop", description: "Executes Solara code repeatedly with a delay between the end of one execution and the start of the next. Args: delayMs;code;iterations;[stopOnError=true]", takesBrackets: true, execute: async (context, args) => { if (args.length < 3) return "[Error: $loop requires delayMs, code, and iterations]"; const delayMs = parseInt(args[0], 10); const codeToLoop = args[1]; const iterations = parseInt(args[2], 10); const stopOnError = (args[3]?.trim().toLowerCase() !== 'false'); const MAX_ITERATIONS = context.client.solaraOptions?.loopMaxIterations || 100; const MIN_DELAY = context.client.solaraOptions?.loopMinDelay || 100; if (isNaN(delayMs) || delayMs < MIN_DELAY) return `[Error: Invalid delay for $loop. Minimum is ${MIN_DELAY}ms]`; if (!codeToLoop || codeToLoop.trim() === "") return "[Error: No code provided to $loop]"; if (isNaN(iterations) || iterations <= 0 || iterations > MAX_ITERATIONS) return `[Error: Invalid iteration count for $loop. Must be between 1 and ${MAX_ITERATIONS}]`; let count = 0; let timeoutId = null; const executeLoopIteration = async () => { if (count >= iterations) { return; } count++; const iterationParseContext = { ...context, messageSent: false, replied: false, deferred: false, embedData: {}, components: [], modal: null, finalResult: '', }; try { await context.client.functionParser.parse(codeToLoop, iterationParseContext); } catch (error) { console.error(`$loop: Error during iteration ${count} of ${iterations}:`, error.message); if (stopOnError) { console.warn(`$loop: Stopping loop due to error.`); const loopErrorMessage = `⚠️ Loop was stopped at iteration ${count} due to an error: ${error.message}`; if (context.channel?.isTextBased()) { context.channel.send(loopErrorMessage).catch(e => console.error("$loop: Failed to send loop error message to channel:", e.message)); } return; } } if (count < iterations) { timeoutId = setTimeout(executeLoopIteration, delayMs); } }; timeoutId = setTimeout(executeLoopIteration, delayMs); return ""; } };