diff --git a/commands/statustest.mjs b/commands/statustest.mjs new file mode 100644 index 0000000..99a5144 --- /dev/null +++ b/commands/statustest.mjs @@ -0,0 +1,91 @@ +/** + * @module commands/statustest + * @description Owner-only diagnostic command to test the public status channel, + * force-refresh the live health card, and simulate subsystem incidents / resolutions. + */ + +import { CommandBuilder } from "../src/commands/index.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../src/ui/index.mjs"; + +/** @type {CommandBuilder} @description Command definition for statustest (owner-only). */ +export const command = new CommandBuilder() + .setName("statustest") + .setDescription("Test public status channel updates, live cards, and incidents.", "commands.statustest") + .setCategory("util") + .setRequirement(r => r.setOwnerOnly(true)); + +/** + * @async + * Run handler for the statustest command. + * @param {object} msg - The command message wrapper. + * @returns {Promise} + */ +export async function run(msg) { + const statusMgr = this.statusChannel; + if (!statusMgr || !statusMgr.enabled || !statusMgr.channelId) { + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setAuthor({ name: this.t(msg, "responses.statustest.disabledAuthor") }) + .setTitle(this.t(msg, "responses.statustest.disabledTitle")) + .setDescription(this.t(msg, "responses.statustest.disabledDesc")); + return msg.reply({ embeds: [embed] }); + } + + const prefix = this.commands?.getPrefix?.(msg.message?.guildId) || "%"; + const args = (msg.args || []).map(a => String(a).trim().toLowerCase()); + const subCommand = args[0] || "help"; + + if (subCommand === "refresh") { + await statusMgr.updateLiveCard(); + const embed = new EmbedBuilder() + .setColor(0x2ecc71) + .setTitle(this.t(msg, "responses.statustest.refreshedTitle")) + .setDescription(this.t(msg, "responses.statustest.refreshedDesc", { + channelId: statusMgr.channelId, + messageId: statusMgr.liveMessageId || "New", + })); + return msg.reply({ embeds: [embed] }); + } + + if (subCommand === "incident") { + const target = args[1] || "gateway"; + const customReason = msg.args.slice(2).join(" ") || "Manual test incident triggered by bot owner."; + await statusMgr.triggerIncident(target, customReason); + const embed = new EmbedBuilder() + .setColor(0xe74c3c) + .setTitle(this.t(msg, "responses.statustest.incidentTitle")) + .setDescription(this.t(msg, "responses.statustest.incidentDesc", { + target, + channelId: statusMgr.channelId, + prefix, + })); + return msg.reply({ embeds: [embed] }); + } + + if (subCommand === "resolve") { + const target = args[1] || "gateway"; + const customNote = msg.args.slice(2).join(" ") || "Manual test resolution confirmed stable."; + await statusMgr.resolveIncident(target, customNote); + const embed = new EmbedBuilder() + .setColor(0x2ecc71) + .setTitle(this.t(msg, "responses.statustest.resolvedTitle")) + .setDescription(this.t(msg, "responses.statustest.resolvedDesc", { + target, + channelId: statusMgr.channelId, + })); + return msg.reply({ embeds: [embed] }); + } + + /* Default Help */ + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setAuthor({ name: this.t(msg, "responses.statustest.author") }) + .setTitle(this.t(msg, "responses.statustest.helpTitle")) + .setDescription(this.t(msg, "responses.statustest.helpDesc", { + channelId: statusMgr.channelId, + cardId: statusMgr.liveMessageId || "Not yet created", + prefix, + })); + return msg.reply({ embeds: [embed] }); +} diff --git a/config_example.json b/config_example.json index 30ecdd9..ad30dbe 100644 --- a/config_example.json +++ b/config_example.json @@ -20,6 +20,15 @@ "maxQueue": 40, "Comment": "Forward error logs and crash reports to a Fluxer channel. Every logger.error line (and every logger.warn line when forwardWarn=true) is posted there: player failures, node disconnects, database errors, plus fatal crash reports (uncaughtException, unhandledRejection) with uptime and memory. startupMessage=true sends a one-time 'Log channel connected' confirmation at boot through the real send path — if it fails, the console shows the exact permission/ID problem. forwardInfo=true ALSO forwards logger.info lines (boot activity, joins, recoveries) — useful for full visibility but much noisier; keep false for errors-only. Identical messages are deduplicated for 60s, sends are spaced by minIntervalMs, and floods beyond maxQueue pending messages are dropped with a summary line instead of spamming. Test delivery any time with the owner-only 'logtest' command. channelId: enable Developer Mode in the Fluxer app, right-click the target channel and copy its ID — the bot must be able to send messages there. Fully disabled unless enabled=true AND channelId is set." }, + "statusChannel": { + "enabled": false, + "channelId": "paste the ID of the public channel for live bot status and incident alerts", + "mentionRoleId": "", + "liveMessageId": null, + "updateIntervalSeconds": 300, + "statusPageUrl": "https://status.remix.bot", + "Comment": "Public-facing system status & incident reporting. Maintains a self-updating live health card (RAM bar, CPU %, Uptime, Ping, active players and subsystem status) and sends dual-color incident lifecycle embeds (🔴 Outage with Investigating status / ✅ Resolved with exact downtime duration) when subsystems experience disruptions. channelId: target Fluxer channel ID. mentionRoleId: optional role snowflake to mention on outages (e.g. @Status). updateIntervalSeconds: frequency in seconds to edit the live status card (default: 300 / 5 minutes). liveMessageId: set automatically by the bot or paste an existing message ID. Test with the owner-only 'statustest' command." + }, "prefix": "your desired prefix (such as %)", "presenceInterval": null, "presenceContents-Comment": "Each entry can be a plain string (e.g. 'Ping for Prefix') or an object. Objects support: text (required), emoji_name (unicode emoji or custom emoji name), emoji_id (snowflake ID for custom guild emojis only), activity ({ name, type, url? }). Activity types: 0=Playing, 1=Streaming, 2=Listening, 3=Watching, 5=Competing. For custom guild emojis, provide both emoji_name AND emoji_id. For unicode emojis, only emoji_name is needed.", diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index 70435d0..edb89f6 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -30,6 +30,7 @@ import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs"; import { LastFmManager } from "../services/lastfm/LastFmManager.mjs"; import { FluxerListManager } from "../services/FluxerListManager.mjs"; import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs"; +import { StatusChannelManager } from "../services/StatusChannelManager.mjs"; import { TrackStats } from "../music/TrackStats.mjs"; import { configureBilibili } from "../music/bilibili/index.mjs"; import { configureAudio } from "../music/audio/AudioSettings.mjs"; @@ -270,6 +271,7 @@ class Remix { this.lastfm = new LastFmManager(config.lastfm, sharedPromisePool); this.fluxerlist = new FluxerListManager(config.fluxerlist); this.trackOptions = new TrackOptionsManager(sharedPool); + this.statusChannel = new StatusChannelManager(this, config.statusChannel); /* Gateway activity timestamps and status tracking */ this._lastGatewayHeartbeat = Date.now(); @@ -373,21 +375,31 @@ class Remix { this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" }); this.lavalink.on("ready", () => { logger.lavalink("[Lavalink] Session ready"); + this.statusChannel?.resolveIncident("audioNode"); if (this._hasBooted) { this.players?.resumeAllOnNodeReconnect?.(); } }); this.lavalink.on("nodeReconnect", () => { + this.statusChannel?.resolveIncident("audioNode"); if (this._hasBooted) { this.players?.resumeAllOnNodeReconnect?.(); } }); + this.lavalink.on("nodeDisconnect", (node, reason) => { + this.statusChannel?.triggerIncident("audioNode", `Audio engine disconnected: ${reason || "Connection dropped"}`); + }); + this.lavalink.on("nodeError", (node, err) => { + this.statusChannel?.triggerIncident("audioNode", `Audio engine error: ${err?.message || "Unreachable"}`); + }); await this.lavalink.init(); this.playerContext.lavalink = this.lavalink; } this.gatewayHandler.onReady(); this._hasBooted = true; + this.statusChannel?.start(); + this.statusChannel?.resolveIncident("gateway"); this.fluxerlist?.startAutoStats?.(client); @@ -802,8 +814,9 @@ class Remix { logger.error("[Shutdown] Failed to close Dashboard DB:", e.message); } - // 6. Stop 24/7 watchdog + /* 6. Stop 24/7 watchdog and status channel */ try { + this.statusChannel?.destroy?.(); this.gatewayHandler?.stop247Watchdog?.(); } catch (e) { logger.warn("[Shutdown] Watchdog stop error:", e?.message); diff --git a/src/services/StatusChannelManager.mjs b/src/services/StatusChannelManager.mjs new file mode 100644 index 0000000..ccf12b9 --- /dev/null +++ b/src/services/StatusChannelManager.mjs @@ -0,0 +1,593 @@ +/** + * @module src/services/StatusChannelManager + * @description Dedicated status channel and automated incident management for Remix. + * Manages two core operational components: + * 1. A self-editing live status card in a designated Fluxer channel, + * reporting real-time gateway latency, active music channels, listeners, + * RAM/CPU metrics with visual Unicode progress bars, and subsystem status. + * 2. An event-driven incident monitor tracking Gateway, Audio Node (NodeLink), + * Database, Dashboard, and REST API availability with automatic downtime + * calculation and dual-color lifecycle embeds (🔴 Outage / ✅ Resolved). + */ + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { logger } from "../core/Logger.mjs"; + +/** @type {string} Default API endpoint for direct REST fallback */ +const DEFAULT_API_BASE = "https://api.fluxer.app/v1"; + +/** + * @class StatusChannelManager + * @description Oversees public status notifications and live health telemetry. + */ +export class StatusChannelManager { + /** + * @param {object} remix - The main Remix bot instance. + * @param {object} [config] - The statusChannel config section. + */ + constructor(remix, config = {}) { + this.remix = remix; + this.client = remix.client; + this.config = config || {}; + + this.enabled = this.config.enabled === true; + this.channelId = typeof this.config.channelId === "string" && this.config.channelId.trim() + ? this.config.channelId.trim() + : null; + this.mentionRoleId = typeof this.config.mentionRoleId === "string" && this.config.mentionRoleId.trim() + ? this.config.mentionRoleId.trim() + : null; + + const rawInterval = Number(this.config.updateIntervalSeconds); + this.updateIntervalMs = Math.max(60, Number.isFinite(rawInterval) && rawInterval > 0 ? rawInterval : 300) * 1000; + + this.statusPageUrl = typeof this.config.statusPageUrl === "string" && this.config.statusPageUrl.trim() + ? this.config.statusPageUrl.trim() + : "status.remix.bot"; + + this.statePath = path.join(process.cwd(), "storage", "status_card.json"); + this.liveMessageId = typeof this.config.liveMessageId === "string" && this.config.liveMessageId.trim() + ? this.config.liveMessageId.trim() + : null; + + this.apiBase = remix.config?.instanceUrl + ? String(remix.config.instanceUrl).trim().replace(/\/+$/, "") + : DEFAULT_API_BASE; + + this._timer = null; + this._dashboardProbeTimer = null; + this._isUpdating = false; + this._lastCpuUsage = null; + this._lastCpuTime = null; + + this.incidents = new Map([ + ["gateway", { name: "Fluxer Gateway", down: false, startedAt: 0, impact: "Critical" }], + ["audioNode", { name: "Audio Engine (NodeLink)", down: false, startedAt: 0, impact: "High" }], + ["database", { name: "Database (MySQL)", down: false, startedAt: 0, impact: "High" }], + ["dashboard", { name: "Web Dashboard", down: false, startedAt: 0, impact: "Low" }], + ["api", { name: "Fluxer REST API", down: false, startedAt: 0, impact: "Critical" }], + ]); + + this._loadState(); + } + + /** + * Translate a key using the Remix locale system. + * @param {string} key + * @param {object} [data] + * @returns {string} + */ + t(key, data = {}) { + return this.remix?.locale?.translate?.(null, key, data) ?? key; + } + + /** + * Start the periodic health card update loop and dashboard probing. + */ + start() { + if (!this.enabled || !this.channelId) { + logger.info("[StatusChannel] Disabled (enabled=false or missing channelId)."); + return; + } + + logger.info(`[StatusChannel] Active — monitoring channel ${this.channelId} (interval: ${this.updateIntervalMs / 1000}s).`); + + /* Initial update delayed slightly so initial connections settle */ + setTimeout(() => { + this.updateLiveCard().catch((err) => { + logger.warn("[StatusChannel] Initial live card update failed:", err?.message); + }); + }, 5000); + + if (this._timer) clearInterval(this._timer); + this._timer = setInterval(() => { + this.updateLiveCard().catch((err) => { + logger.warn("[StatusChannel] Periodic live card update failed:", err?.message); + }); + }, this.updateIntervalMs); + this._timer.unref?.(); + + this._setupDashboardProbe(); + } + + /** + * Stop background timers and release resources. + */ + destroy() { + if (this._timer) { + clearInterval(this._timer); + this._timer = null; + } + if (this._dashboardProbeTimer) { + clearInterval(this._dashboardProbeTimer); + this._dashboardProbeTimer = null; + } + } + + /** + * Trigger an incident for a given subsystem. + * @param {"gateway"|"audioNode"|"database"|"dashboard"|"api"} key + * @param {string} [reason] + */ + async triggerIncident(key, reason = "") { + if (!this.enabled || !this.channelId) return; + + const inc = this.incidents.get(key); + if (!inc || inc.down) return; + + inc.down = true; + inc.startedAt = Date.now(); + const startedSec = Math.floor(inc.startedAt / 1000); + + const desc = reason || this.t("responses.statusChannel.incidentDefaultDesc", { name: inc.name }); + + const embed = new EmbedBuilder() + .setColor(0xe74c3c) + .setAuthor({ name: this.t("responses.statusChannel.incidentAuthor") }) + .setTitle(this.t("responses.statusChannel.incidentTitle", { name: inc.name })) + .setDescription(desc) + .addFields( + { name: this.t("responses.statusChannel.startedField"), value: ` ()`, inline: true }, + { name: this.t("responses.statusChannel.statusField"), value: this.t("responses.statusChannel.investigating"), inline: true }, + { name: this.t("responses.statusChannel.severityField"), value: inc.impact, inline: true } + ) + .setFooter({ text: `Remix Incident Monitor • ${this.statusPageUrl}` }) + .setTimestamp(new Date()); + + const payload = { + embeds: [embed], + }; + if (this.mentionRoleId) { + payload.content = `<@&${this.mentionRoleId}>`; + } + + try { + await this._postMessage(payload); + logger.warn(`[StatusChannel] Incident published for ${inc.name}: ${desc}`); + } catch (err) { + logger.warn(`[StatusChannel] Failed to post incident for ${inc.name}:`, err?.message); + } + + /* Force an immediate edit on the live card to reflect degraded/critical state */ + this.updateLiveCard().catch(() => {}); + } + + /** + * Resolve an ongoing incident for a given subsystem. + * @param {"gateway"|"audioNode"|"database"|"dashboard"|"api"} key + * @param {string} [resolutionNote] + */ + async resolveIncident(key, resolutionNote = "") { + if (!this.enabled || !this.channelId) return; + + const inc = this.incidents.get(key); + if (!inc || !inc.down) return; + + const resolvedAt = Date.now(); + const durationMs = Math.max(1000, resolvedAt - (inc.startedAt || resolvedAt)); + inc.down = false; + inc.startedAt = 0; + + const resolvedSec = Math.floor(resolvedAt / 1000); + const downtimeStr = this._formatDuration(durationMs); + const desc = resolutionNote || this.t("responses.statusChannel.resolvedDefaultDesc", { name: inc.name }); + + const embed = new EmbedBuilder() + .setColor(0x2ecc71) + .setAuthor({ name: this.t("responses.statusChannel.resolvedAuthor") }) + .setTitle(this.t("responses.statusChannel.resolvedTitle", { name: inc.name })) + .setDescription(desc) + .addFields( + { name: this.t("responses.statusChannel.downtimeField"), value: `**${downtimeStr}**`, inline: true }, + { name: this.t("responses.statusChannel.resolvedField"), value: ` ()`, inline: true }, + { name: this.t("responses.statusChannel.statusField"), value: this.t("responses.statusChannel.stable"), inline: true } + ) + .setFooter({ text: `Remix Incident Monitor • ${this.statusPageUrl}` }) + .setTimestamp(new Date()); + + try { + await this._postMessage({ embeds: [embed] }); + logger.info(`[StatusChannel] Incident resolved for ${inc.name} (Downtime: ${downtimeStr})`); + } catch (err) { + logger.warn(`[StatusChannel] Failed to post incident resolution for ${inc.name}:`, err?.message); + } + + /* Update live card back to operational */ + this.updateLiveCard().catch(() => {}); + } + + /** + * Build and update the live status card in the configured channel. + * @returns {Promise} + */ + async updateLiveCard() { + if (!this.enabled || !this.channelId || this._isUpdating) return; + this._isUpdating = true; + + try { + const embed = this._buildLiveCardEmbed(); + + if (this.liveMessageId) { + try { + await this._patchMessage(this.liveMessageId, { embeds: [embed] }); + return; + } catch (err) { + const status = err?.statusCode ?? err?.status; + /* If message was deleted (404), fall through to post a fresh one */ + if (status !== 404) { + logger.warn("[StatusChannel] Failed to patch status card:", err?.message); + return; + } + this.liveMessageId = null; + } + } + + /* Post a new live card message and persist ID */ + const sent = await this._postMessage({ embeds: [embed] }); + const newId = sent?.id ?? sent?.message?.id ?? null; + if (newId) { + this.liveMessageId = String(newId); + this._saveState(); + logger.info(`[StatusChannel] New status card created (ID: ${this.liveMessageId})`); + } + } finally { + this._isUpdating = false; + } + } + + /** + * Constructs the live status embed with current system and bot metrics. + * @private + * @returns {EmbedBuilder} + */ + _buildLiveCardEmbed() { + const ping = Math.round(Number(this.client?.ws?.ping ?? this.client?.ping ?? 0)); + const uptimeMs = process.uptime() * 1000; + const uptimeStr = this._formatUptime(uptimeMs); + + /* Active music playback metrics */ + const playerMap = this.remix.players?.playerMap; + const activePlayers = playerMap ? [...new Set(playerMap.values())].filter((p) => p && !p._destroyed && !p.leaving).length : 0; + let totalListeners = 0; + if (playerMap) { + for (const p of playerMap.values()) { + if (!p || p._destroyed) continue; + const members = p.getVoiceMembers?.(); + if (Array.isArray(members)) { + totalListeners += members.filter((m) => !m.bot).length; + } + } + } + + /* Hardware metrics */ + const mem = this._getMemoryInfo(); + const cpuPct = this._getCpuUsagePercent(); + const cpuCores = os.cpus()?.length || 1; + const ramBar = this._createProgressBar(mem.systemPct, 10); + const cpuBar = this._createProgressBar(cpuPct, 10); + + /* Subsystem status synthesis */ + const { list: subsystems, overallState } = this._getSubsystemsHealth(); + + let color = 0x2ecc71; + let stateBadge = this.t("responses.statusChannel.operationalDesc"); + if (overallState === "critical") { + color = 0xe74c3c; + stateBadge = this.t("responses.statusChannel.criticalDesc"); + } else if (overallState === "degraded") { + color = 0xf1c40f; + stateBadge = this.t("responses.statusChannel.degradedDesc"); + } + + const guildCount = this.client?.guilds?.cache?.size ?? this.client?.guilds?.size ?? 0; + const intervalSec = Math.round(this.updateIntervalMs / 1000); + + const embed = new EmbedBuilder() + .setColor(color) + .setAuthor({ + name: this.t("responses.statusChannel.liveCardAuthor"), + icon_url: this.client?.user?.avatarURL?.() ?? null, + }) + .setTitle(this.t("responses.statusChannel.liveCardTitle")) + .setDescription(stateBadge) + .addFields( + { name: this.t("responses.statusChannel.gatewayField"), value: `${ping > 0 ? ping : "< 1"} ms`, inline: true }, + { name: this.t("responses.statusChannel.uptimeField"), value: uptimeStr, inline: true }, + { name: this.t("responses.statusChannel.sessionsField"), value: `${activePlayers} active (${totalListeners} listeners)`, inline: true }, + { name: this.t("responses.statusChannel.ramField"), value: `\`${ramBar}\` ${mem.systemPct}%\n${mem.rssMb} MB / ${mem.totalMemMb} MB`, inline: true }, + { name: this.t("responses.statusChannel.cpuField"), value: `\`${cpuBar}\` ${cpuPct}%\n${cpuCores} cores available`, inline: true }, + { name: this.t("responses.statusChannel.guildsField"), value: `${guildCount.toLocaleString()} servers`, inline: true }, + { + name: this.t("responses.statusChannel.subsystemsField"), + value: subsystems.map((s) => `• **${s.name}**: ${s.status}`).join("\n"), + inline: false, + } + ) + .setFooter({ text: `Auto-updates every ${intervalSec}s • ${this.statusPageUrl}` }) + .setTimestamp(new Date()); + + return embed; + } + + /** + * Computes the health overview of monitored dependencies. + * @private + * @returns {{list: Array<{name: string, status: string}>, overallState: "operational"|"degraded"|"critical"}} + */ + _getSubsystemsHealth() { + let hasCriticalDown = false; + let hasMinorDown = false; + const list = []; + + for (const [key, inc] of this.incidents) { + if (key === "dashboard" && !this.remix.config?.dashboard?.enabled) { + list.push({ name: inc.name, status: `⚪ ${this.t("responses.statusChannel.disabled")}` }); + continue; + } + if (inc.down) { + list.push({ name: inc.name, status: `🔴 ${this.t("responses.statusChannel.outage")}` }); + if (inc.impact === "Critical") hasCriticalDown = true; + else hasMinorDown = true; + } else { + list.push({ name: inc.name, status: `🟢 ${this.t("responses.statusChannel.operational")}` }); + } + } + + let overallState = "operational"; + if (hasCriticalDown) overallState = "critical"; + else if (hasMinorDown) overallState = "degraded"; + + return { list, overallState }; + } + + /** + * Background probe for the Web Dashboard if enabled. + * @private + */ + _setupDashboardProbe() { + if (!this.remix.config?.dashboard?.enabled) return; + + const probe = async () => { + try { + const port = this.remix.dashboard?.port || 3000; + const res = await fetch(`http://127.0.0.1:${port}/`, { + signal: AbortSignal.timeout(4000), + }); + if (res.ok || res.status === 401 || res.status === 403 || res.status === 302) { + this.resolveIncident("dashboard"); + } else { + this.triggerIncident("dashboard", `Dashboard HTTP check returned status ${res.status}`); + } + } catch (err) { + this.triggerIncident("dashboard", `Dashboard is unreachable (${err?.message})`); + } + }; + + this._dashboardProbeTimer = setInterval(probe, 60_000); + this._dashboardProbeTimer.unref?.(); + } + + /** + * Helper to format millisecond durations into clean time strings. + * @private + * @param {number} ms + * @returns {string} + */ + _formatDuration(ms) { + const totalSec = Math.max(0, Math.floor(ms / 1000)); + const h = Math.floor(totalSec / 3600); + const m = Math.floor((totalSec % 3600) / 60); + const s = totalSec % 60; + if (h > 0) return `${h}h ${m}m ${s}s`; + if (m > 0) return `${m}m ${s}s`; + return `${s}s`; + } + + /** + * Formats process uptime into human-readable strings. + * @private + * @param {number} ms + * @returns {string} + */ + _formatUptime(ms) { + const totalSec = Math.max(0, Math.floor(ms / 1000)); + const d = Math.floor(totalSec / 86400); + const h = Math.floor((totalSec % 86400) / 3600); + const m = Math.floor((totalSec % 3600) / 60); + if (d > 0) return `${d}d ${h}h ${m}m`; + if (h > 0) return `${h}h ${m}m`; + return `${m}m`; + } + + /** + * Generate a visual Unicode progress bar. + * @private + * @param {number} percent + * @param {number} [length=10] + * @returns {string} + */ + _createProgressBar(percent, length = 10) { + const clamped = Math.max(0, Math.min(100, Math.round(percent))); + const filled = Math.round((clamped / 100) * length); + const empty = Math.max(0, length - filled); + return "█".repeat(filled) + "░".repeat(empty); + } + + /** + * Measures delta CPU percentage over the elapsed update window. + * @private + * @returns {number} + */ + _getCpuUsagePercent() { + const currentUsage = process.cpuUsage(); + const now = Date.now(); + if (!this._lastCpuUsage || !this._lastCpuTime) { + this._lastCpuUsage = currentUsage; + this._lastCpuTime = now; + return 0; + } + const elapsedMs = now - this._lastCpuTime; + const userDiff = (currentUsage.user - this._lastCpuUsage.user) / 1000; + const sysDiff = (currentUsage.system - this._lastCpuUsage.system) / 1000; + const totalDiff = userDiff + sysDiff; + + this._lastCpuUsage = currentUsage; + this._lastCpuTime = now; + + if (elapsedMs <= 0) return 0; + const cores = os.cpus()?.length || 1; + return Math.min(100, Math.max(0, Math.round((totalDiff / (elapsedMs * cores)) * 100))); + } + + /** + * Memory statistics for the host and current process. + * @private + * @returns {{rssMb: number, totalMemMb: number, systemPct: number}} + */ + _getMemoryInfo() { + const mem = process.memoryUsage(); + const rssMb = Math.round(mem.rss / (1024 * 1024)); + const totalMemMb = Math.round(os.totalmem() / (1024 * 1024)); + const freeMemMb = Math.round(os.freemem() / (1024 * 1024)); + const usedSys = Math.max(0, totalMemMb - freeMemMb); + const systemPct = Math.min(100, Math.max(0, Math.round((usedSys / totalMemMb) * 100))); + return { rssMb, totalMemMb, systemPct }; + } + + /** + * Normalizes payload for client REST or raw fetch calls. + * @private + * @param {object} data + * @returns {object} + */ + _normalizePayload(data) { + if (data && typeof data === "object") { + if (Array.isArray(data.embeds)) { + return { + ...data, + embeds: data.embeds.map((e) => (typeof e?.toJSON === "function" ? e.toJSON() : e)), + }; + } + if (data.embed) { + const raw = typeof data.embed.toJSON === "function" ? data.embed.toJSON() : data.embed; + return { embeds: [raw] }; + } + if (typeof data.toJSON === "function") { + return { embeds: [data.toJSON()] }; + } + return data; + } + return { content: String(data ?? "") }; + } + + /** + * Post a message to the status channel with raw fetch fallback. + * @private + * @param {object} payload + * @returns {Promise} + */ + async _postMessage(payload) { + const body = this._normalizePayload(payload); + const rest = this.client?.rest; + if (typeof rest?.post === "function") { + return await rest.post(`/channels/${this.channelId}/messages`, { body }); + } + const token = this.client?.token || this.remix.config?.token; + const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages`, { + method: "POST", + headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), + }); + if (!res.ok) throw new Error("HTTP " + res.status); + return await res.json().catch(() => ({})); + } + + /** + * Patch an existing message in the status channel with raw fetch fallback. + * @private + * @param {string} messageId + * @param {object} payload + * @returns {Promise} + */ + async _patchMessage(messageId, payload) { + const body = this._normalizePayload(payload); + const rest = this.client?.rest; + if (typeof rest?.patch === "function") { + return await rest.patch(`/channels/${this.channelId}/messages/${messageId}`, { body }); + } + const token = this.client?.token || this.remix.config?.token; + const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages/${messageId}`, { + method: "PATCH", + headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), + }); + if (!res.ok) throw new Error("HTTP " + res.status); + return await res.json().catch(() => ({})); + } + + /** + * Load persisted card ID from disk. + * @private + */ + _loadState() { + try { + if (fs.existsSync(this.statePath)) { + const raw = fs.readFileSync(this.statePath, "utf8"); + const parsed = JSON.parse(raw); + if (parsed?.liveMessageId) { + this.liveMessageId = String(parsed.liveMessageId).trim(); + } + } + } catch (_) {} + } + + /** + * Save card ID to disk. + * @private + */ + _saveState() { + try { + const dir = path.dirname(this.statePath); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + this.statePath, + JSON.stringify( + { + liveMessageId: this.liveMessageId, + updatedAt: new Date().toISOString(), + }, + null, + 2 + ), + "utf8" + ); + } catch (_) {} + } +} + +export default StatusChannelManager; \ No newline at end of file diff --git a/src/voice/gateway/GatewayHandler.mjs b/src/voice/gateway/GatewayHandler.mjs index 4f781d2..d508136 100644 --- a/src/voice/gateway/GatewayHandler.mjs +++ b/src/voice/gateway/GatewayHandler.mjs @@ -238,6 +238,7 @@ class GatewayHandler { remix._lastGatewayDisconnect = 0; if (payload.t === "READY") { + remix.statusChannel?.resolveIncident("gateway"); logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`); this._lastReadyAt = Date.now(); remix._lastGatewayHeartbeat = Date.now(); @@ -274,6 +275,7 @@ class GatewayHandler { } if (payload.t === "RESUMED") { + remix.statusChannel?.resolveIncident("gateway"); logger.player("[Gateway] RESUMED received from gateway."); this._lastReadyAt = Date.now(); remix._lastGatewayHeartbeat = Date.now(); @@ -348,6 +350,7 @@ class GatewayHandler { const reason = eventOrCode?.reason ?? maybeReason ?? ""; remix._gatewayConnected = false; if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now(); + remix.statusChannel?.triggerIncident("gateway", `Gateway WebSocket closed (code=${code}). Reconnecting...`); const now = Date.now(); if (now - _wsErrorCooldown.lastLogged >= _wsErrorCooldown.COOLDOWN_MS) { _wsErrorCooldown.lastLogged = now; diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 7285e83..0599a88 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -91,7 +91,8 @@ "pitch": "تعديل طبقة الصوت (النغمة) للمقطع الصوتي الحالي (0.5× إلى 2.0×).", "previous": "تشغيل الأغنية السابقة من سجل التشغيل.", "replay": "إعادة تشغيل الأغنية الحالية من البداية.", - "skipto": "التخطي مباشرة إلى أغنية معينة في قائمة الانتظار." + "skipto": "التخطي مباشرة إلى أغنية معينة في قائمة الانتظار.", + "statustest": "اختبار تحديثات قناة الحالة العامة والبطاقات المباشرة والحوادث." }, "options": { "debug": { @@ -1322,6 +1323,50 @@ "floodTitle": "تم إسقاط رسائل السجل", "floodDesc": "⚠️ تم إسقاط **{{count}}** رسالة سجل إضافية أثناء الفيضان لحماية قيود معدل واجهة برمجة التطبيقات.", "floodFooter": "حارس حد المعدل • ErrorChannel" + }, + "statustest": { + "author": "Remix · تشخيص قناة الحالة", + "disabledAuthor": "مركز حالة Remix", + "disabledTitle": "قناة الحالة معطلة", + "disabledDesc": "❌ قناة الحالة **معطلة** حالياً أو لا يوجد `channelId` محدد.\n\nقم بتهيئة `statusChannel` في ملف `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"معرف_القناة_الخاص_بك\",\n \"mentionRoleId\": \"معرف_الرتبة_الاختياري\",\n \"updateIntervalSeconds\": 300\n}\n```", + "refreshedTitle": "✅ تم تحديث البطاقة المباشرة", + "refreshedDesc": "تم إرسال تحديث القياس المباشر إلى <#{{channelId}}>.\nمعرف رسالة البطاقة: `{{messageId}}`", + "incidentTitle": "🔴 تم إطلاق حادث اختبار", + "incidentDesc": "تم نشر انقطاع الحادث لـ **{{target}}** في <#{{channelId}}>.\nقم بتشغيل `{{prefix}}statustest resolve {{target}}` لحله.", + "resolvedTitle": "✅ تم حل حادث الاختبار", + "resolvedDesc": "تم نشر حل الحادث لـ **{{target}}** في <#{{channelId}}>.", + "helpTitle": "أوامر قناة الحالة", + "helpDesc": "قناة الحالة **نشطة** في <#{{channelId}}>.\nالبطاقة المباشرة الحالية: `{{cardId}}`\n\n**خيارات الاستخدام:**\n• `{{prefix}}statustest refresh` — فرض تحديث رسالة الحالة المباشرة.\n• `{{prefix}}statustest incident ` — إطلاق رسالة انقطاع تجريبية.\n• `{{prefix}}statustest resolve ` — حل الانقطاع وتسجيل وقت التوقف.\n\n*الأهداف الصالحة:* `gateway`, `audioNode`, `database`, `dashboard`, `api`" + }, + "statusChannel": { + "liveCardTitle": "حالة النظام المباشرة", + "liveCardAuthor": "Remix · القياس عن بُعد وحالة النظام", + "operationalDesc": "🟢 **جميع الأنظمة تعمل بكفاءة**\nيعمل Remix بسلاسة عبر جميع السيرفرات.", + "degradedDesc": "🟡 **انقطاع جزئي**\nبعض الأنظمة الفرعية غير الحرجة تواجه اضطرابات.", + "criticalDesc": "🔴 **تم اكتشاف انقطاع كبير**\nإحدى الخدمات الرئيسية أو أكثر غير متصلة حالياً.", + "gatewayField": "🏓 زمن استجابة البوابة (Gateway)", + "uptimeField": "⏱️ وقت التشغيل", + "sessionsField": "🎵 الجلسات النشطة", + "ramField": "📟 الذاكرة (RAM)", + "cpuField": "⚙️ استهلاك المعالج", + "guildsField": "🏰 تواجد السيرفرات", + "subsystemsField": "🛡️ صحة الأنظمة الفرعية", + "incidentAuthor": "🔴 تم اكتشاف حادث", + "incidentTitle": "🔴 {{name}} متوقف حالياً", + "incidentDefaultDesc": "تواجه خدمة {{name}} اضطرابات. فريقنا يحقق في المشكلة بنشاط.", + "resolvedAuthor": "✅ تم حل الحادث", + "resolvedTitle": "✅ عاد {{name}} للعمل مجدداً", + "resolvedDefaultDesc": "تمت استعادة الاتصال بـ {{name}} بالكامل والتحقق من استقراره.", + "downtimeField": "مدة التوقف", + "startedField": "البداية", + "resolvedField": "تم الحل", + "statusField": "الحالة", + "severityField": "مستوى الخطورة", + "investigating": "قيد التحقيق", + "stable": "مستقر", + "operational": "يعمل", + "outage": "اضطرابات", + "disabled": "معطل" } } } diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 02ecdc1..9de4a93 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -91,7 +91,8 @@ "pitch": "دەستکاریکردنی تۆن و ئاستی دەنگی تراکی ئێستا (0.5× بۆ 2.0×).", "previous": "لێدانی گۆرانی پێشوو لە مێژووی لێدان.", "replay": "دووبارە لێدانی گۆرانیی ئێستا لە سەرەتاوە.", - "skipto": "پەڕینەوەی ڕاستەوخۆ بۆ گۆرانییەکی دیاریکراو لە ڕیزبەندی." + "skipto": "پەڕینەوەی ڕاستەوخۆ بۆ گۆرانییەکی دیاریکراو لە ڕیزبەندی.", + "statustest": "تاقیکردنەوەی نوێکردنەوەکانی کەناڵی دۆخی گشتی، کارتی ڕاستەوخۆ و ڕووداوەکان." }, "options": { "debug": { @@ -1322,6 +1323,50 @@ "floodTitle": "پەیامەکانی تۆمار فڕێدران", "floodDesc": "⚠️ **{{count}}** پەیامی زیاتری تۆمار لە کاتی قەرەباڵغیدا فڕێدران بۆ پاراستنی سنووری خێرایی API.", "floodFooter": "پارێزەری سنووری خێرایی • ErrorChannel" + }, + "statustest": { + "author": "Remix · دەستنیشانکردنی کەناڵی دۆخ", + "disabledAuthor": "سەنتەری دۆخی Remix", + "disabledTitle": "کەناڵی دۆخ ناچالاکە", + "disabledDesc": "❌ کەناڵی دۆخ لە ئێستادا **ناچالاکە** یان `channelId` دانەنراوە.\n\nتکایە `statusChannel` لە `config.json` ڕێکبخە:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"ناسنامەی_کەناڵەکەت\",\n \"mentionRoleId\": \"ناسنامەی_ڕۆڵی_ئارەزوومەندانە\",\n \"updateIntervalSeconds\": 300\n}\n```", + "refreshedTitle": "✅ کارتی ڕاستەوخۆ نوێکرایەوە", + "refreshedDesc": "نوێکردنەوەی تێلیمیتریی ڕاستەوخۆ نێردرا بۆ <#{{channelId}}>.\nناسنامەی پەیامی کارت: `{{messageId}}`", + "incidentTitle": "🔴 ڕووداوی تاقیکاری دەستیپێکرد", + "incidentDesc": "پچڕانی ڕووداو بۆ **{{target}}** لە <#{{channelId}}> بڵاوکرایەوە.\nفەرمانی `{{prefix}}statustest resolve {{target}}` جێبەجێ بکە بۆ چارەسەرکردنی.", + "resolvedTitle": "✅ ڕووداوی تاقیکاری چارەسەرکرا", + "resolvedDesc": "چارەسەرکردنی ڕووداو بۆ **{{target}}** لە <#{{channelId}}> بڵاوکرایەوە.", + "helpTitle": "فەرمانەکانی کەناڵی دۆخ", + "helpDesc": "کەناڵی دۆخ **چالاکە** لە <#{{channelId}}>.\nکارتی ڕاستەوخۆی ئێستا: `{{cardId}}`\n\n**هەڵبژاردەکانی بەکارهێنان:**\n• `{{prefix}}statustest refresh` — نوێکردنەوەی زۆرەملێی پەیامی دۆخی ڕاستەوخۆ.\n• `{{prefix}}statustest incident ` — دەستپێکردنی پەیامی پچڕانی تاقیکاری.\n• `{{prefix}}statustest resolve ` — چارەسەرکردنی پچڕان و تۆمارکردنی کاتی وەستان.\n\n*ئامانجە دروستەکان:* `gateway`, `audioNode`, `database`, `dashboard`, `api`" + }, + "statusChannel": { + "liveCardTitle": "دۆخی ڕاستەوخۆی سیستەم", + "liveCardAuthor": "Remix · تێلیمیتری و دۆخی سیستەم", + "operationalDesc": "🟢 **هەموو سیستەمەکان کاردەکەن**\nRemix بە شێوەیەکی باش لە هەموو سێرڤەرەکان کاردەکات.", + "degradedDesc": "🟡 **پچڕانی بەشەکی**\nهەندێک لە ژێر-سیستەمە لاوەکییەکان تووشی کێشە بوون.", + "criticalDesc": "🔴 **پچڕانی گەورە دۆزرایەوە**\nیەک یان چەند خزمەتگوزارییەکی سەرەکی لەسەر هێڵ نین.", + "gatewayField": "🏓 دواکەوتنی دەروازە (Gateway)", + "uptimeField": "⏱️ کاتی کارکردن", + "sessionsField": "🎵 دانیشتنە چالاکەکان", + "ramField": "📟 بیرگە (RAM)", + "cpuField": "⚙️ بەکارهێنانی CPU", + "guildsField": "🏰 سێرڤەرە بەشداربووەکان", + "subsystemsField": "🛡️ تەندروستیی ژێر-سیستەمەکان", + "incidentAuthor": "🔴 ڕووداو دۆزرایەوە", + "incidentTitle": "🔴 {{name}} لە کار کەوتووە", + "incidentDefaultDesc": "{{name}} تووشی پچڕان بووە. تیمەکەمان سەرقاڵی لێکۆڵینەوەیە.", + "resolvedAuthor": "✅ ڕووداو چارەسەرکرا", + "resolvedTitle": "✅ {{name}} گەڕایەوە سەر هێڵ", + "resolvedDefaultDesc": "پەیوەندی لەگەڵ {{name}} بە تەواوی گەڕێندرایەوە و جێگیرکرا.", + "downtimeField": "کاتی وەستان", + "startedField": "دەستپێکردن", + "resolvedField": "چارەسەرکرا", + "statusField": "دۆخ", + "severityField": "ئاستی مەترسی", + "investigating": "لێکۆڵینەوە دەکرێت", + "stable": "جێگیرە", + "operational": "کاردەکات", + "outage": "پچڕان", + "disabled": "ناچالاکە" } } } diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index fb31491..442c1bb 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -91,7 +91,8 @@ "pitch": "Tonhöhe (Pitch) des aktuellen Tracks anpassen (0.5× bis 2.0×).", "previous": "Den vorherigen Titel aus dem Wiedergabeverlauf abspielen.", "replay": "Den aktuellen Titel von vorne starten.", - "skipto": "Direkt zu einem bestimmten Titel in der Warteschlange springen." + "skipto": "Direkt zu einem bestimmten Titel in der Warteschlange springen.", + "statustest": "Öffentliche Statuskanal-Aktualisierungen, Live-Karten und Vorfälle testen." }, "options": { "debug": { @@ -1322,6 +1323,50 @@ "floodTitle": "Protokollnachrichten verworfen", "floodDesc": "⚠️ **{{count}}** zusätzliche Protokollnachricht(en) wurden während einer Flut verworfen, um API-Ratenbegrenzungen zu schützen.", "floodFooter": "Ratenbegrenzungsschutz • ErrorChannel" + }, + "statustest": { + "author": "Remix · Statuskanal-Diagnose", + "disabledAuthor": "Remix Status-Hub", + "disabledTitle": "Statuskanal deaktiviert", + "disabledDesc": "❌ Der Statuskanal ist derzeit **deaktiviert** oder es fehlt eine `channelId`.\n\nKonfiguriere `statusChannel` in `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"DEINE_KANAL_ID\",\n \"mentionRoleId\": \"OPTIONALE_ROLLEN_ID\",\n \"updateIntervalSeconds\": 300\n}\n```", + "refreshedTitle": "✅ Live-Karte aktualisiert", + "refreshedDesc": "Live-Telemetrie-Update an <#{{channelId}}> gesendet.\nKarten-Nachrichten-ID: `{{messageId}}`", + "incidentTitle": "🔴 Test-Vorfall ausgelöst", + "incidentDesc": "Vorfallsausfall für **{{target}}** in <#{{channelId}}> veröffentlicht.\nFühre `{{prefix}}statustest resolve {{target}}` aus, um ihn zu beheben.", + "resolvedTitle": "✅ Test-Vorfall behoben", + "resolvedDesc": "Vorfallsbehebung für **{{target}}** in <#{{channelId}}> veröffentlicht.", + "helpTitle": "Statuskanal-Befehle", + "helpDesc": "Statuskanal ist **aktiv** in <#{{channelId}}>.\nAktuelle Live-Karte: `{{cardId}}`\n\n**Nutzungsoptionen:**\n• `{{prefix}}statustest refresh` — Live-Status-Embed erzwingen.\n• `{{prefix}}statustest incident ` — Test-Ausfall-Embed auslösen.\n• `{{prefix}}statustest resolve ` — Ausfall beheben und Ausfallzeit posten.\n\n*Gültige Ziele:* `gateway`, `audioNode`, `database`, `dashboard`, `api`" + }, + "statusChannel": { + "liveCardTitle": "Live-Systemstatus", + "liveCardAuthor": "Remix · System-Telemetrie & Status", + "operationalDesc": "🟢 **Alle Systeme betriebsbereit**\nRemix läuft auf allen Servern reibungslos.", + "degradedDesc": "🟡 **Teilausfall**\nEinige unkritische Subsysteme weisen Störungen auf.", + "criticalDesc": "🔴 **Schwerer Ausfall festgestellt**\nEin oder mehrere Hauptdienste sind offline.", + "gatewayField": "🏓 Gateway-Latenz", + "uptimeField": "⏱️ Betriebszeit", + "sessionsField": "🎵 Aktive Sitzungen", + "ramField": "📟 Arbeitsspeicher (RAM)", + "cpuField": "⚙️ CPU-Auslastung", + "guildsField": "🏰 Server-Präsenz", + "subsystemsField": "🛡️ Subsystem-Status", + "incidentAuthor": "🔴 Vorfall festgestellt", + "incidentTitle": "🔴 {{name}} ist ausgefallen", + "incidentDefaultDesc": "{{name}} weist Störungen auf. Unser Team untersucht den Vorfall.", + "resolvedAuthor": "✅ Vorfall behoben", + "resolvedTitle": "✅ {{name}} ist wieder online", + "resolvedDefaultDesc": "Die Verbindung zu {{name}} wurde vollständig wiederhergestellt und als stabil verifiziert.", + "downtimeField": "Ausfallzeit", + "startedField": "Begonnen", + "resolvedField": "Behoben", + "statusField": "Status", + "severityField": "Schweregrad", + "investigating": "Untersuchung läuft", + "stable": "Stabil", + "operational": "Betriebsbereit", + "outage": "Störungen", + "disabled": "Deaktiviert" } } } diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index c142da4..b53910e 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -91,7 +91,8 @@ "pitch": "Adjust the audio pitch of the current track (0.5× to 2.0×).", "previous": "Play the previous track from playback history.", "replay": "Restart the current song from the beginning.", - "skipto": "Skip directly to a specific track in the queue." + "skipto": "Skip directly to a specific track in the queue.", + "statustest": "Test public status channel updates, live cards, and incidents." }, "options": { "debug": { @@ -1322,6 +1323,50 @@ "floodTitle": "Log Messages Dropped", "floodDesc": "⚠️ **{{count}}** additional log message(s) were dropped during a flood to protect API rate limits.", "floodFooter": "Rate Limit Guard • ErrorChannel" + }, + "statustest": { + "author": "Remix · Status Channel Diagnostics", + "disabledAuthor": "Remix Status Hub", + "disabledTitle": "Status Channel Disabled", + "disabledDesc": "❌ The status channel is currently **disabled** or missing a `channelId`.\n\nConfigure `statusChannel` in `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"YOUR_CHANNEL_ID\",\n \"mentionRoleId\": \"OPTIONAL_ROLE_ID\",\n \"updateIntervalSeconds\": 300\n}\n```", + "refreshedTitle": "✅ Live Card Refreshed", + "refreshedDesc": "Dispatched live telemetry update to <#{{channelId}}>.\nCard Message ID: `{{messageId}}`", + "incidentTitle": "🔴 Test Incident Triggered", + "incidentDesc": "Published incident outage for **{{target}}** in <#{{channelId}}>.\nRun `{{prefix}}statustest resolve {{target}}` to resolve it.", + "resolvedTitle": "✅ Test Incident Resolved", + "resolvedDesc": "Published incident resolution for **{{target}}** in <#{{channelId}}>.", + "helpTitle": "Status Channel Commands", + "helpDesc": "Status channel is **active** in <#{{channelId}}>.\nCurrent Live Card: `{{cardId}}`\n\n**Usage Options:**\n• `{{prefix}}statustest refresh` — Force-update the live status embed.\n• `{{prefix}}statustest incident ` — Trigger test outage embed.\n• `{{prefix}}statustest resolve ` — Resolve outage and post downtime.\n\n*Valid targets:* `gateway`, `audioNode`, `database`, `dashboard`, `api`" + }, + "statusChannel": { + "liveCardTitle": "Live System Status", + "liveCardAuthor": "Remix · System Telemetry & Status", + "operationalDesc": "🟢 **All Systems Operational**\nRemix is running smoothly across all guilds.", + "degradedDesc": "🟡 **Partial Outage**\nSome non-critical subsystems are experiencing disruptions.", + "criticalDesc": "🔴 **Major Outage Detected**\nOne or more primary services are currently offline.", + "gatewayField": "🏓 Gateway Latency", + "uptimeField": "⏱️ Uptime", + "sessionsField": "🎵 Active Sessions", + "ramField": "📟 Memory (RAM)", + "cpuField": "⚙️ CPU Utilization", + "guildsField": "🏰 Guild Footprint", + "subsystemsField": "🛡️ Subsystem Health", + "incidentAuthor": "🔴 Incident Detected", + "incidentTitle": "🔴 {{name}} is down", + "incidentDefaultDesc": "{{name}} is experiencing disruptions. Our team is actively investigating the incident.", + "resolvedAuthor": "✅ Incident Resolved", + "resolvedTitle": "✅ {{name}} is back online", + "resolvedDefaultDesc": "{{name}} connectivity has been fully restored and verified stable.", + "downtimeField": "Downtime", + "startedField": "Started", + "resolvedField": "Resolved", + "statusField": "Status", + "severityField": "Severity", + "investigating": "Investigating", + "stable": "Stable", + "operational": "Operational", + "outage": "Disruptions", + "disabled": "Disabled" } } } diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 6f4bfcd..f835cbd 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -91,7 +91,8 @@ "pitch": "Ajustar o tom (pitch) do áudio da faixa atual (0.5× a 2.0×).", "previous": "Tocar a faixa anterior do histórico de reprodução.", "replay": "Reiniciar a música atual do início.", - "skipto": "Pular diretamente para uma faixa específica na fila." + "skipto": "Pular diretamente para uma faixa específica na fila.", + "statustest": "Testar atualizações do canal de status público, cartões ao vivo e incidentes." }, "options": { "debug": { @@ -1322,6 +1323,50 @@ "floodTitle": "Mensagens de Registro Descartadas", "floodDesc": "⚠️ **{{count}}** mensagem(ns) de registro adicionais foram descartadas durante uma inundação para proteger os limites de taxa da API.", "floodFooter": "Proteção de Limite de Taxa • ErrorChannel" + }, + "statustest": { + "author": "Remix · Diagnóstico do Canal de Status", + "disabledAuthor": "Remix Status Hub", + "disabledTitle": "Canal de Status Desativado", + "disabledDesc": "❌ O canal de status está atualmente **desativado** ou sem um `channelId` configurado.\n\nConfigure `statusChannel` em `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"SEU_ID_DE_CANAL\",\n \"mentionRoleId\": \"ID_DO_CARGO_OPCIONAL\",\n \"updateIntervalSeconds\": 300\n}\n```", + "refreshedTitle": "✅ Cartão ao Vivo Atualizado", + "refreshedDesc": "Atualização de telemetria ao vivo enviada para <#{{channelId}}>.\nID da Mensagem do Cartão: `{{messageId}}`", + "incidentTitle": "🔴 Incidente de Teste Disparado", + "incidentDesc": "Interrupção por incidente publicada para **{{target}}** em <#{{channelId}}>.\nExecute `{{prefix}}statustest resolve {{target}}` para resolver.", + "resolvedTitle": "✅ Incidente de Teste Resolvido", + "resolvedDesc": "Resolução de incidente publicada para **{{target}}** em <#{{channelId}}>.", + "helpTitle": "Comandos do Canal de Status", + "helpDesc": "O canal de status está **ativo** em <#{{channelId}}>.\nCartão ao Vivo Atual: `{{cardId}}`\n\n**Opções de Uso:**\n• `{{prefix}}statustest refresh` — Forçar atualização da mensagem de status ao vivo.\n• `{{prefix}}statustest incident ` — Disparar mensagem de interrupção de teste.\n• `{{prefix}}statustest resolve ` — Resolver interrupção e registrar tempo de inatividade.\n\n*Alvos válidos:* `gateway`, `audioNode`, `database`, `dashboard`, `api`" + }, + "statusChannel": { + "liveCardTitle": "Status do Sistema ao Vivo", + "liveCardAuthor": "Remix · Telemetria e Status do Sistema", + "operationalDesc": "🟢 **Todos os Sistemas Operacionais**\nO Remix está funcionando perfeitamente em todos os servidores.", + "degradedDesc": "🟡 **Interrupção Parcial**\nAlguns subsistemas não críticos estão enfrentando instabilidades.", + "criticalDesc": "🔴 **Interrupção Crítica Detectada**\nUm ou mais serviços principais estão offline no momento.", + "gatewayField": "🏓 Latência do Gateway", + "uptimeField": "⏱️ Tempo de Atividade", + "sessionsField": "🎵 Sessões Ativas", + "ramField": "📟 Memória (RAM)", + "cpuField": "⚙️ Uso de CPU", + "guildsField": "🏰 Servidores Conectados", + "subsystemsField": "🛡️ Saúde dos Subsistemas", + "incidentAuthor": "🔴 Incidente Detectado", + "incidentTitle": "🔴 {{name}} está fora do ar", + "incidentDefaultDesc": "{{name}} está enfrentando instabilidades. Nossa equipe está investigando o incidente.", + "resolvedAuthor": "✅ Incidente Resolvido", + "resolvedTitle": "✅ {{name}} está online novamente", + "resolvedDefaultDesc": "A conectividade com {{name}} foi totalmente restabelecida e verificada como estável.", + "downtimeField": "Tempo de Inatividade", + "startedField": "Iniciado", + "resolvedField": "Resolvido", + "statusField": "Status", + "severityField": "Gravidade", + "investigating": "Investigando", + "stable": "Estável", + "operational": "Operacional", + "outage": "Instabilidade", + "disabled": "Desativado" } } } diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 45e1046..92fa274 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -91,7 +91,8 @@ "vote": "FluxerList üzerinde sunucunuz/botunuz için oylama bilgilerini görüntüleyin veya oy verenleri kontrol edin", "previous": "Oynatma geçmişindeki önceki şarkıyı çal.", "replay": "Çalan şarkıyı baştan başlat.", - "skipto": "Kuyruktaki belirli bir şarkıya doğrudan atla." + "skipto": "Kuyruktaki belirli bir şarkıya doğrudan atla.", + "statustest": "Herkese açık durum kanalı güncellemelerini, canlı kartları ve olayları test edin." }, "options": { "debug": { @@ -1322,6 +1323,50 @@ "floodTitle": "Günlük Mesajları Düşürüldü", "floodDesc": "⚠️ API hız limitlerini korumak için taşkın sırasında fazladan **{{count}}** günlük mesajı düşürüldü.", "floodFooter": "Hız Limiti Koruması • ErrorChannel" + }, + "statustest": { + "author": "Remix · Durum Kanalı Tanılama", + "disabledAuthor": "Remix Durum Merkezi", + "disabledTitle": "Durum Kanalı Devre Dışı", + "disabledDesc": "❌ Durum kanalı şu anda **devre dışı** veya `channelId` eksik.\n\n`config.json` içinde `statusChannel` öğesini yapılandırın:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"KANAL_ID_NIZ\",\n \"mentionRoleId\": \"ISTEGE_BAGLI_ROL_ID\",\n \"updateIntervalSeconds\": 300\n}\n```", + "refreshedTitle": "✅ Canlı Kart Yenilendi", + "refreshedDesc": "<#{{channelId}}> kanalına canlı telemetri güncellemesi gönderildi.\nKart Mesaj Kimliği: `{{messageId}}`", + "incidentTitle": "🔴 Test Olayı Tetiklendi", + "incidentDesc": "<#{{channelId}}> kanalında **{{target}}** için kesinti olayı yayınlandı.\nÇözmek için `{{prefix}}statustest resolve {{target}}` komutunu çalıştırın.", + "resolvedTitle": "✅ Test Olayı Çözüldü", + "resolvedDesc": "<#{{channelId}}> kanalında **{{target}}** için olay çözümü yayınlandı.", + "helpTitle": "Durum Kanalı Komutları", + "helpDesc": "Durum kanalı <#{{channelId}}> üzerinde **aktif**.\nGeçerli Canlı Kart: `{{cardId}}`\n\n**Kullanım Seçenekleri:**\n• `{{prefix}}statustest refresh` — Canlı durum iletisini zorla güncelle.\n• `{{prefix}}statustest incident ` — Test kesinti iletisi tetikle.\n• `{{prefix}}statustest resolve ` — Kesintiyi çöz ve kesinti süresini paylaş.\n\n*Geçerli hedefler:* `gateway`, `audioNode`, `database`, `dashboard`, `api`" + }, + "statusChannel": { + "liveCardTitle": "Canlı Sistem Durumu", + "liveCardAuthor": "Remix · Sistem Telemetrisi ve Durumu", + "operationalDesc": "🟢 **Tüm Sistemler Çalışıyor**\nRemix tüm sunucularda sorunsuz çalışıyor.", + "degradedDesc": "🟡 **Kısmi Kesinti**\nBazı kritik olmayan alt sistemlerde aksamalar yaşanıyor.", + "criticalDesc": "🔴 **Büyük Kesinti Tespit Edildi**\nBir veya daha fazla ana servis şu anda çevrimdışı.", + "gatewayField": "🏓 Ağ Geçidi Gecikmesi", + "uptimeField": "⏱️ Çalışma Süresi", + "sessionsField": "🎵 Aktif Oturumlar", + "ramField": "📟 Bellek (RAM)", + "cpuField": "⚙️ CPU Kullanımı", + "guildsField": "🏰 Sunucu Varlığı", + "subsystemsField": "🛡️ Alt Sistem Sağlığı", + "incidentAuthor": "🔴 Olay Tespit Edildi", + "incidentTitle": "🔴 {{name}} çöktü", + "incidentDefaultDesc": "{{name}} kesinti yaşıyor. Ekibimiz olayı aktif olarak inceliyor.", + "resolvedAuthor": "✅ Olay Çözüldü", + "resolvedTitle": "✅ {{name}} tekrar çevrimiçi", + "resolvedDefaultDesc": "{{name}} bağlantısı tamamen geri yüklendi ve kararlı olduğu doğrulandı.", + "downtimeField": "Kesinti Süresi", + "startedField": "Başlangıç", + "resolvedField": "Çözüldü", + "statusField": "Durum", + "severityField": "Önem Derecesi", + "investigating": "İnceleniyor", + "stable": "Kararlı", + "operational": "Çalışıyor", + "outage": "Aksama", + "disabled": "Devre Dışı" } } }