const API_BASE = process.env.STOAT_API_URL || "https://api.stoat.chat/0.8"; const BOT_TOKEN = process.env.BOT_TOKEN; const MAX_CHARS = parseInt(process.env.STOAT_MAX_CHARS) || 2000; const VERBOSE = process.env.VERBOSE_LOGGING === "true" || process.env.VERBOSE_LOGGING === "1"; const MAX_DICE = 1000; const MAX_REPEATS = 100; const MAX_EXPR_LENGTH = 1000; if (!BOT_TOKEN) { console.error("Fatal: BOT_TOKEN is not set. Add it to your .env file."); process.exit(1); } function verboseLog(...args) { if (VERBOSE) console.log(...args); } class AutoDice { constructor() { this.user = null; this.users = new Map(); this.config = null; this.ws = null; this.wsPing = -1; this.heartbeatTimer = null; this.pongTimer = null; this.reconnectTimer = null; this.reconnectAttempts = 0; this._lastMsgId = null; } async api(method, path, body) { const url = new URL(path, API_BASE); const opts = { method, headers: { "X-Bot-Token": BOT_TOKEN }, }; if (body != null) { opts.headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(body); } const res = await fetch(url, opts); if (!res.ok) { const text = await res.text(); throw new Error(`API ${method} ${path} → ${res.status}: ${text}`); } if (res.status === 204) return null; return res.json(); } async apiGet(path) { return this.api("GET", path); } async apiPost(path, body) { return this.api("POST", path, body); } async apiPatch(path, body) { return this.api("PATCH", path, body); } connectWS() { if (!this.config?.ws) { console.error("No WebSocket URL in config"); return; } this.disconnectWS(false); const url = new URL(this.config.ws); url.searchParams.set("version", "1"); url.searchParams.set("format", "json"); url.searchParams.set("token", BOT_TOKEN); verboseLog(`Connecting to ${url.origin}${url.pathname}...`); this.ws = new WebSocket(url); this.wsPing = -1; this.ws.onopen = () => { this.heartbeatTimer = setInterval(() => { this.sendWS({ type: "Ping", data: Date.now() }); this.pongTimer = setTimeout(() => { verboseLog("WebSocket pong timeout"); this.ws?.close(); }, 10_000); }, 30_000); }; this.ws.onmessage = (event) => { let msg; try { msg = JSON.parse(event.data); } catch (e) { console.error("WebSocket: invalid JSON frame:", e); return; } this.handleWSEvent(msg); }; this.ws.onerror = (err) => { console.error("WebSocket error:", err); }; this.ws.onclose = () => { verboseLog("WebSocket disconnected"); this.disconnectWS(true); }; } disconnectWS(reconnect) { clearInterval(this.heartbeatTimer); clearTimeout(this.pongTimer); this.heartbeatTimer = null; this.pongTimer = null; clearTimeout(this.reconnectTimer); this.reconnectTimer = null; if (this.ws) { this.ws.onopen = null; this.ws.onmessage = null; this.ws.onerror = null; this.ws.onclose = null; try { this.ws.close(); } catch (_) {} this.ws = null; } if (reconnect) { this.scheduleReconnect(); } } sendWS(data) { if (this.ws?.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(data)); } } scheduleReconnect() { clearTimeout(this.reconnectTimer); const base = Math.pow(2, Math.min(this.reconnectAttempts, 10)) - 1; const delay = base * (0.8 + Math.random() * 0.4); this.reconnectAttempts++; verboseLog(`Reconnecting in ${Math.round(delay)}s (attempt ${this.reconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connectWS(), delay * 1000); } handleWSEvent(event) { switch (event.type) { case "Ping": this.sendWS({ type: "Pong", data: event.data }); return; case "Pong": clearTimeout(this.pongTimer); this.wsPing = Date.now() - event.data; return; case "Error": console.error("Server error event:", event.data); this.disconnectWS(true); return; case "Authenticated": return; case "Ready": this.handleReady(event); return; case "Message": this.handleMessageEvent(event); return; } } handleReady(event) { this.reconnectAttempts = 0; this._lastMsgId = null; if (event.users) { for (const u of event.users) { this.users.set(u._id, { id: u._id, username: u.username, bot: u.bot ?? null }); if (u.relationship === "User") { this.user = { id: u._id, username: u.username }; } } } console.log(`AutoDice ready as ${this.user?.username} (${this.user?.id})`); this.setStatus(); } handleMessageEvent(event) { if (this._lastMsgId === event._id) return; this._lastMsgId = event._id; const authorId = event.author; let author = this.users.get(authorId); if (!author && event.user) { author = { id: event.user._id, username: event.user.username, bot: event.user.bot ?? null }; this.users.set(author.id, author); } const content = event.content ?? ""; const message = { id: event._id, authorId: authorId, author: author || null, channelId: event.channel, content: content, reply: (data) => this.sendReply(event.channel, event._id, data), edit: (data) => this.editMessage(event.channel, event._id, data), }; this.handleMessage(message).catch((err) => { console.error("handleMessage error:", err); }); } async sendReply(channelId, replyToId, data) { const body = typeof data === "string" ? { content: data } : { ...data }; body.replies = [{ id: replyToId, mention: true }]; const result = await this.apiPost(`/channels/${channelId}/messages`, body); return this.makeMessage(channelId, result); } async editMessage(channelId, messageId, data) { const body = typeof data === "string" ? { content: data } : data; await this.apiPatch(`/channels/${channelId}/messages/${messageId}`, body); } makeMessage(channelId, raw) { const id = raw._id; return { id: id, channelId: channelId, authorId: raw.author, reply: (data) => this.sendReply(channelId, id, data), edit: (data) => this.editMessage(channelId, id, data), }; } async getDMChannel(userId) { try { const data = await this.apiGet(`/users/${userId}/dm`); return data; } catch (error) { console.error("DM Channel Error:", error); return null; } } async sendDM(userId, content) { const dm = await this.getDMChannel(userId); if (!dm) return null; return this.apiPost(`/channels/${dm._id}/messages`, { content }); } async handleMessage(message) { if (message.author?.bot || !message.content) return; let content = message.content.trim(); const botMention = `<@${this.user?.id}>`; if (!content.startsWith(botMention)) return; content = content.slice(botMention.length).trim(); if (!content) { return await this.sendHelp(message); } const args = content.split(/\s+/); const trigger = args[0].toLowerCase(); if (trigger === "help") { return await this.sendHelp(message); } if (trigger === "support") { return await this.sendSupport(message); } if (trigger === "ping") { return await this.handlePing(message); } let isDMRequest = false; let expanded = false; for (let step = 0; step < 3 && args.length; step++) { const head = args[0].toLowerCase(); if (["dm", "secret", "priv", "private"].includes(head)) { isDMRequest = true; args.shift(); continue; } if (["adv", "advantage"].includes(head)) { args[0] = "2d20kh1"; expanded = true; continue; } if (["dis", "disadvantage"].includes(head)) { args[0] = "2d20kl1"; expanded = true; continue; } break; } if (expanded && args.length > 1 && ["dm", "secret", "priv", "private"].includes(args[1]?.toLowerCase())) { isDMRequest = true; args.splice(1, 1); } const tail = args[0]?.toLowerCase(); if (tail === "help") return await this.sendHelp(message); if (tail === "support") return await this.sendSupport(message); if (tail === "ping") return await this.handlePing(message); if (!args.length) { return await message.reply(isDMRequest ? "⚠️ **Invalid Input:** Nothing to roll privately. Add a roll after `private` (eg `private 1d20`)." : "⚠️ **Invalid Input:** Nothing to roll."); } // Extract dice formula + optional label const joined = args.join(" "); const { formula, label } = this.extractFormula(joined); if (!formula) { if (/d[(\df%]/i.test(joined) || /[+\-*/]/.test(joined)) { return await message.reply("⚠️ **Invalid Input:** That dice expression couldn't be parsed. Check `@AutoDice help` for supported syntax."); } return; } await this.processRoll(message, formula, isDMRequest, label); } async handlePing(message) { const now = Date.now(); const wsDisplay = this.wsPing < 0 ? "`Reconnecting/Syncing…`" : `\`${this.wsPing}ms\``; const uptime = process.uptime(); const d = Math.floor(uptime / 86400); const h = Math.floor((uptime % 86400) / 3600); const m = Math.floor((uptime % 3600) / 60); const s = Math.floor(uptime % 60); let uptimeStr = ""; if (d > 0) uptimeStr += `${d}d `; if (h > 0) uptimeStr += `${h}h `; if (m > 0) uptimeStr += `${m}m `; if (uptime < 300) uptimeStr += `${s}s`; try { const msg = await message.reply("⌛ Measuring..."); if (msg) { const messagePing = Math.round(Date.now() - now); const content = ["## Ping Pong!", `WebSocket: ${wsDisplay}`, `Message: \`${messagePing}ms\``, `Uptime: \`${uptimeStr.trim() || "0s"}\``].join("\n"); await msg.edit({ content }); } } catch (error) { console.error("Ping error:", error); } } extractFormula(input) { // Try progressively shorter prefixes to separate formula from label const parts = input.split(/\s+/); for (let i = parts.length; i >= 1; i--) { const candidate = parts.slice(0, i).join(" "); if (this.isDiceString(candidate) || this.isMathString(candidate)) { const label = parts.slice(i).join(" ") || null; if (label && (this.isDiceString(label) || this.isMathString(label))) return { formula: null, label: null }; return { formula: candidate, label }; } } return { formula: null, label: null }; } isMathString(str) { if (!/[+\-*/]/.test(str) || !/\d/.test(str)) return false; if (!/^[0-9\s.+\-*/()]+$/.test(str)) return false; let balance = 0; for (const ch of str) { if (ch === "(") balance++; else if (ch === ")") balance--; if (balance < 0) return false; } return balance === 0; } async processRoll(message, input, isPrivate, label) { const repeatMatch = input.match(/^(\d+)\s+(.*d.*)/i); let output = ""; if (label) { output += `🎲 **${label}**\n`; } if (repeatMatch) { const requested = parseInt(repeatMatch[1]); if (requested < 1) { output += "⚠️ **Invalid Input:** Repeat count must be at least 1."; } else { const count = Math.min(MAX_REPEATS, requested); output += `**Repeating ${count} times${requested > count ? ` (max ${MAX_REPEATS})` : ""}:** \`${repeatMatch[2]}\`\n`; for (let i = 0; i < count; i++) { const res = this.calculateDice(repeatMatch[2]); output += res.total === "Error" ? `${i + 1}. ⚠️ ${res.invalid ? res.breakdown : "Invalid expression"}\n` : `${i + 1}. **${res.total}** – ${res.breakdown}\n`; } } } else { const res = this.calculateDice(input); if (res.total === "Error") { output = res.invalid ? `⚠️ **Invalid Input:** ${res.breakdown}.` : "⚠️ **Invalid Input:** That dice expression couldn't be parsed. Check `@AutoDice help` for supported syntax."; } else if (label) { output += `**${res.total}**${res.noDice ? "" : ` – ${res.breakdown}`}`; } else { output += `🎲 **${res.total}**${res.noDice ? "" : `\n${res.breakdown}`}`; } if (res.math) output += `\n$$ ${res.math} = ${res.total} $$`; } if (output.length > MAX_CHARS) { output = `⚠️ **Error:** The result is too long (${output.length} characters) to be sent.`; } output = output.trimEnd(); if (isPrivate) { const sent = await this.sendDM(message.authorId, output); if (sent) { await message.reply("✅ Sent to DMs."); } else { await message.reply("❌ Unable to send a DM."); } } else { await message.reply(output); } } isDiceString(str) { if (!/d[(\df%]/i.test(str)) return false; let s = str.replace(/(?=\d]*)/gi, ""); let prev; do { prev = s; const idx = s.search(/d\(/i); if (idx === -1) break; let countStart = idx; while (countStart > 0 && /\d/.test(s[countStart - 1])) countStart--; if (countStart > 0 && /[\d.]/.test(s[countStart - 1])) return false; let depth = 0; let close = -1; for (let i = idx + 2; i < s.length; i++) { if (s[i] === "(") depth++; else if (s[i] === ")") { if (depth === 0) { close = i; break; } depth--; } } if (close === -1) break; s = s.slice(0, idx) + s.slice(close + 1); } while (s !== prev); if (!/^[0-9.+\-*/()<>\s!]*$/i.test(s)) return false; let balance = 0; for (const ch of s) { if (ch === "(") balance++; else if (ch === ")") balance--; if (balance < 0) return false; } if (balance !== 0) return false; // Reject terms juxtaposed without an operator (eg "1d20 2" or "2d6 3d8"), while allowing a leading repeat count (eg "3 1d20") let t = str.replace(/(?=\d]*)/gi, "\x00D\x00"); let prevT; do { prevT = t; const idx = t.search(/d\(/i); if (idx === -1) break; let depth = 0; let close = -1; for (let i = idx + 2; i < t.length; i++) { if (t[i] === "(") depth++; else if (t[i] === ")") { if (depth === 0) { close = i; break; } depth--; } } if (close === -1) break; t = t.slice(0, idx) + "\x00D\x00" + t.slice(close + 1); } while (t !== prevT); t = t.replace(/^\d+\s+/, ""); return !/\x00D\x00\s+\d|\x00D\x00\s+\x00D\x00/.test(t); } calculateDice(expression, depth = 0) { if (depth > 10) return { total: "Error", breakdown: "Nesting is too deep", invalid: true }; if (expression.length > MAX_EXPR_LENGTH) return { total: "Error", breakdown: "Expression is too long", invalid: true }; expression = expression .replace(/\s*(\*\*|[+\-*/])\s*/g, " $1 ") .replace(/\s+/g, " ") .trim(); const diceRegex = /(?=\d]*)/gi; const displays = []; const nestedDisplays = []; const nestedValues = []; // Replace nested d(...) blocks with placeholder tokens let offset = 0; for (let guard = 0; guard < 100; guard++) { const m = /d\(/i.exec(expression.slice(offset)); if (!m) break; const dIndex = offset + m.index; const end = dIndex + 2; let parenDepth = 0; let close = -1; for (let i = end; i < expression.length; i++) { if (expression[i] === "(") parenDepth++; else if (expression[i] === ")") { if (parenDepth === 0) { close = i; break; } parenDepth--; } } if (close === -1) break; let countStart = dIndex; while (countStart > 0 && /\d/.test(expression[countStart - 1])) countStart--; if (countStart > 0 && /[\d.]/.test(expression[countStart - 1])) { // The digits before "d(" belong to a decimal (eg 0.7d(6)), so this isn't valid dice syntax. Skip it. offset = end; continue; } const trailing = (expression.slice(close + 1).match(/^[a-z!<>=]+\d*/i) || [""])[0]; if (trailing) { return { total: "Error", breakdown: `\`${expression.slice(countStart, close + 1)}${trailing}\` - modifiers aren't supported on nested dice`, invalid: true }; } const match = expression.slice(countStart, close + 1); const countStr = expression.slice(countStart, dIndex); const rawCount = countStr ? parseInt(countStr) : 1; if (rawCount < 1) { return { total: "Error", breakdown: `\`${match}\` isn't valid dice (dice count must be at least 1)`, invalid: true }; } const count = Math.min(MAX_DICE, rawCount); const inner = expression.slice(end, close); const innerRes = this.calculateDice(inner, depth + 1); if (innerRes.total === "Error" || typeof innerRes.total !== "number" || !isFinite(innerRes.total)) { return { total: "Error", breakdown: `\`${match}\` isn't valid dice`, invalid: true }; } const sides = Math.round(innerRes.total); if (sides < 1) { return { total: "Error", breakdown: `\`${match}\` would have 0 sides`, invalid: true }; } const results = []; for (let i = 0; i < count; i++) { results.push({ val: Math.floor(Math.random() * sides) + 1, kept: true }); } const sum = results.reduce((a, b) => a + b.val, 0); const formatted = results.map((r) => `**${r.val}**`).join(", "); const idx = nestedDisplays.length; if (/d/i.test(inner)) { const resolved = sides === innerRes.total ? `d${sides}` : `**${innerRes.total}** → d${sides}`; nestedDisplays.push(`${match}: ${formatted} [${innerRes.breakdown} = ${resolved}]`); } else { nestedDisplays.push(`${match}: ${formatted}`); } nestedValues.push(sum); expression = expression.slice(0, countStart) + `\x00N${idx}\x00` + expression.slice(close + 1); offset = countStart + `\x00N${idx}\x00`.length; } let diceError = null; const evalString = expression.replace(diceRegex, (match, countStr, sidesStr, mods) => { const rawCount = parseInt(countStr || "1"); const count = Math.min(MAX_DICE, Math.max(1, rawCount)); // Fate/Fudge dice if (/^[fF]$/.test(sidesStr)) { if (mods) { diceError = `\`${match}\` (Fate dice) doesn't support modifiers`; } const fateResults = []; for (let i = 0; i < count; i++) { const r = Math.floor(Math.random() * 3) - 1; // -1, 0, or 1 const symbol = r === -1 ? "−" : r === 0 ? "▯" : "+"; fateResults.push({ val: r, kept: true, symbol }); } const sum = fateResults.reduce((a, d) => a + d.val, 0); const formatted = fateResults.map((d) => d.symbol).join(" "); displays.push({ text: `${match}: ${formatted}`, sum }); return `(${sum})`; } const sides = sidesStr === "%" ? 100 : parseInt(sidesStr); if (!(sides >= 1)) { diceError = `\`${match}\` isn't valid dice (sides must be at least 1)`; displays.push({ text: `${match}: 0`, sum: 0 }); return `(0)`; } if (rawCount < 1) { diceError = `\`${match}\` isn't valid dice (dice count must be at least 1)`; displays.push({ text: `${match}: 0`, sum: 0 }); return `(0)`; } const isExploding = mods && mods.includes("!"); let results = []; for (let i = 0; i < count; i++) { let roll = Math.floor(Math.random() * sides) + 1; let isMax = isExploding && roll === sides && sides > 1; let explosions = 0; while (isMax && explosions < 10) { results.push({ val: roll, kept: true, exploded: true }); explosions++; roll = Math.floor(Math.random() * sides) + 1; isMax = isExploding && roll === sides && sides > 1; } results.push({ val: roll, kept: true, exploded: false }); } if (mods) { const leftover = mods.toLowerCase().replace(/(?:r[<>=]?\d+|[<>]\d+|k[hl]\d+|d[hl]\d+|s[ad]?|!)*/g, ""); if (leftover) { diceError = `\`${match}\` has an invalid modifier: \`${leftover}\``; } else { results = this.applyModifiers(results, mods, sides); } } const sum = results.filter((r) => r.kept).reduce((a, b) => a + b.val, 0); const formatted = results .map((r) => { let display = r.val; if (r.exploded) display = `${r.val}💥`; return r.exploded || !r.kept ? `~~${display}~~` : `**${display}**`; }) .join(", "); displays.push({ text: `${match}: ${formatted}`, sum }); return `(${sum})`; }); if (diceError) return { total: "Error", breakdown: diceError, invalid: true }; // Substitute nested rolls into the eval string let resolved = evalString; for (let i = 0; i < nestedValues.length; i++) { resolved = resolved.split(`\x00N${i}\x00`).join(`(${nestedValues[i]})`); } let total = 0; try { if (/[a-z]/i.test(resolved)) throw new Error("invalid dice expression"); const sanitized = resolved.replace(/[^0-9+\-*/().\s]/g, ""); if (!sanitized) throw new Error("empty expression"); total = new Function(`return ${sanitized}`)(); if (typeof total === "number" && !Number.isInteger(total)) { total = Number(total.toFixed(2)); } } catch (e) { total = "Error"; } // Rebuild the breakdown in expression order let di = 0; let breakdown = expression.replace(diceRegex, () => { const d = displays[di++]; return d ? d.text : ""; }); for (let i = 0; i < nestedDisplays.length; i++) { breakdown = breakdown.split(`\x00N${i}\x00`).join(nestedDisplays[i]); } // Build the arithmetic line (for KaTeX), skipping trivial single-group rolls let mi = 0; let mathExpr = expression.replace(diceRegex, () => { const d = displays[mi++]; return d ? String(d.sum) : ""; }); for (let i = 0; i < nestedValues.length; i++) { mathExpr = mathExpr.split(`\x00N${i}\x00`).join(String(nestedValues[i])); } mathExpr = mathExpr.trim(); const math = total !== "Error" && mathExpr !== String(total) ? this.toKaTeX(mathExpr) : null; const noDice = displays.length === 0 && nestedDisplays.length === 0; return { total, breakdown, math, noDice }; } toKaTeX(expr) { return this.powerify(expr) .replace(/\s*\*\s*/g, " \\times ") .replace(/\s*\/\s*/g, " \\div ") .replace(/\s{2,}/g, " "); } powerify(expr) { const takeForward = (str) => { str = str.replace(/^\s+/, ""); if (!str) return { token: "", rest: "" }; let end; if (str[0] === "(" || str[0] === "{") { const open = str[0]; const close = open === "(" ? ")" : "}"; let depth = 0; end = str.length; for (let i = 0; i < str.length; i++) { if (str[i] === open) depth++; else if (str[i] === close && --depth === 0) { end = i + 1; break; } } } else { end = (str.match(/^\S*/) || [""])[0].length; } let token = str.slice(0, end); let rest = str.slice(end); if (/^[+\-]$/.test(token) && rest.startsWith(" ")) { const next = takeForward(rest.slice(1)); token += next.token; rest = next.rest; } return { token, rest }; }; const takeBackward = (str) => { if (!str) return { token: "", rest: "" }; let start; if (str.endsWith(")") || str.endsWith("}")) { const close = str[str.length - 1]; const open = close === ")" ? "(" : "{"; let depth = 0; start = 0; for (let i = str.length - 1; i >= 0; i--) { if (str[i] === close) depth++; else if (str[i] === open && --depth === 0) { start = i; break; } } } else { const m = str.match(/(\S+)\s*$/); start = m ? str.length - m[0].length : str.length; } return { token: str.slice(start), rest: str.slice(0, start) }; }; let s = expr; while (true) { const idx = s.lastIndexOf(" ** "); if (idx === -1) return s; const before = s.slice(0, idx); const after = s.slice(idx + 4); const rhs = takeForward(after); const lhs = takeBackward(before); s = lhs.rest + `{${lhs.token}}^{${rhs.token}}` + rhs.rest; } } applyModifiers(results, modStr, sides) { modStr = (modStr || "").toLowerCase(); // Reroll (single pass) const rerollMatch = modStr.match(/r([<>=]?)(\d+)/); if (rerollMatch) { const op = rerollMatch[1] || "="; const target = parseInt(rerollMatch[2]); results.forEach((d) => { const trigger = (op === "=" && d.val === target) || (op === "<" && d.val < target) || (op === ">" && d.val > target); if (trigger) d.val = Math.floor(Math.random() * sides) + 1; }); } // Success counting (>N) const successMatch = modStr.match(/(?(\d+)/); if (successMatch) { const threshold = parseInt(successMatch[1]); results.forEach((d) => { d.kept = d.val >= threshold; d.val = d.val >= threshold ? 1 : 0; }); return results; } // Fail counting ( { d.kept = d.val < threshold; d.val = d.val < threshold ? 1 : 0; }); return results; } // Keep highest/lowest const keepMatch = modStr.match(/k([hl])(\d+)/); if (keepMatch) { const type = keepMatch[1]; const num = parseInt(keepMatch[2]); const sorted = [...results].sort((a, b) => b.val - a.val); const toKeep = type === "h" ? sorted.slice(0, num) : sorted.slice(-num); results.forEach((d) => { if (!toKeep.includes(d)) d.kept = false; }); } // Drop highest/lowest const dropMatch = modStr.match(/d([hl])(\d+)/); if (dropMatch) { const type = dropMatch[1]; const num = parseInt(dropMatch[2]); const sorted = [...results].sort((a, b) => b.val - a.val); const toDrop = type === "h" ? sorted.slice(0, num) : sorted.slice(-num); results.forEach((d) => { if (toDrop.includes(d)) d.kept = false; }); } // Sort if (modStr.includes("sd")) results.sort((a, b) => b.val - a.val); else if (["s", "sa"].some((opt) => modStr.includes(opt))) { results.sort((a, b) => a.val - b.val); } return results; } async sendHelp(message) { await message.reply(`## AutoDice Help Visit [the website]() for more usage information and [the AutoMod server](https://stt.gg/automod) for help. - **Basic Rolls:** \`@AutoDice [number]d[sides]\` (eg \`10d6\`). Use \`d%\` for percentile or \`dF\` for Fate dice. - **Plain Maths:** Formulas without dice work too (eg \`2+2\` or \`(2+3)*2\`). - **Repeat:** Prefix a roll with a number to repeat it (eg \`3 1d20+5\`). - **Nested Dice:** Sides can be another roll or formula (eg \`d(d20+20)\` or \`2d(3d6)\`). - **Maths:** Supports \`+\`, \`-\`, \`*\`, \`/\`, \`**\` (exponents), and decimals. (eg \`1d20 + 5\`, \`d20**2\`, or \`d540*0.7\`). - **Advantage/Disadvantage:** Shorthand \`adv\` or \`dis\` (expands to \`2d20kh1\` / \`2d20kl1\`). - **Sorting:** Suffix \`sa\` (ascending) or \`sd\` (descending). (eg \`10d6sd\`). - **Keep/Drop:** \`kh[n]\` / \`kl[n]\` to keep highest/lowest, or \`dh[n]\` / \`dl[n]\` to drop them. (eg \`4d6dl1\`). - **Rerolls:** \`r<[n]\` or \`r>[n]\` to reroll values below/above a threshold. (eg \`1d10r<3\`). - **Exploding Dice:** Suffix \`!\` to reroll and add any maximum results (eg \`4d6!\`). - **Successes/Failures:** \`>[n]\` to count dice meeting a target, \`<[n]\` to count those below. (eg \`5d10>7\`). - **Labels:** Add text after your roll to label it. (eg \`1d20+5 Stealth check\`). - **Private Rolls:** Prefix with \`private\` to receive results in your DMs.`); } async sendSupport(message) { await message.reply( `## Support AutoDice\n AutoDice is developed and provided free of charge, but your financial support is greatly appreciated to allow sustainable development and to cover costs. You can support me via https://vale.rocks/support. Thank you so very much!`, ); } async setStatus() { if (!this.user) return; const text = `@${this.user.username} help`; try { await this.apiPatch("/users/@me", { status: { text } }); verboseLog(`Status set to "${text}"`); } catch (error) { console.error("Failed to set status:", error); } } async start() { verboseLog("Fetching server config..."); this.config = await this.apiGet("/"); verboseLog(`Config loaded, ws=${this.config.ws}`); this.connectWS(); } } new AutoDice().start().catch((err) => { console.error("Fatal startup error:", err); process.exit(1); });