ok that alot

This commit is contained in:
NoLogicAlan committed 2026-05-11 22:24:08 +03:00
1 parent df1a783fde
commit 5f33ee231d
17 files changed
+64 -47

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ export async function run(msg, data) {
const guild = guildId ? this.client.guilds.get(String(guildId).replace(/\D/g, "")) : null; const guild = guildId ? this.client.guilds.get(String(guildId).replace(/\D/g, "")) : null;
const conn = s.connection; const conn = s.connection;
const room = conn?.room; const room = conn?.room;
const roomState = room?.state ?? "no-room"; const roomState = room?.connectionState ?? (room?.isConnected ? "connected" : "disconnected");
const hasMediaPlayer = !!s._mediaPlayer && !s._mediaPlayer?.destroyed; const hasMediaPlayer = !!s._mediaPlayer && !s._mediaPlayer?.destroyed;
return { return {
name: channel?.name ?? "unknown", name: channel?.name ?? "unknown",
+1 -1
View File
@@ -4,7 +4,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("forceleave") .setName("forceleave")
.addAlias("fl") .addAliases("fl")
.setDescription("Make Remix leave a channel even if you're not in it.") .setDescription("Make Remix leave a channel even if you're not in it.")
.setRequirement(r => r.addPermission("ManageChannels")) .setRequirement(r => r.addPermission("ManageChannels"))
.setCategory("music") .setCategory("music")
+1 -2
View File
@@ -11,8 +11,7 @@ export const command = new CommandBuilder()
export async function run(message) { export async function run(message) {
const description = this.t(message, "responses.invite.description"); const description = this.t(message, "responses.invite.description");
const botUser = message.handler.client.user; const botUser = this.client?.user;
const botIcon = botUser?.displayAvatarURL?.() || null; const botIcon = botUser?.displayAvatarURL?.() || null;
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
+2 -2
View File
@@ -69,8 +69,8 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
} catch (_) { return "%"; } } catch (_) { return "%"; }
})(); })();
const desc = is247 const desc = is247
? this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId }) ? this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix })
: this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }); : this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId });
const embed = new EmbedBuilder().setColor(getGlobalColor()) const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(desc); .setDescription(desc);
message.channel.send({ embeds: [embed] }); message.channel.send({ embeds: [embed] });
+7 -7
View File
@@ -380,7 +380,7 @@ export async function run(msg, data) {
const statusEmoji = track.now ? "🎵 Now Playing" : "🕐 Last Played"; const statusEmoji = track.now ? "🎵 Now Playing" : "🕐 Last Played";
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setAuthor({ name: `${statusEmoji} on Last.fm`, icon_url: track.image || undefined }) .setAuthor({ name: `${statusEmoji} on Last.fm`, iconURL: track.image || undefined })
.setDescription(`**${track.name}** by **${track.artist}**\n[Open on Last.fm](${track.url})`) .setDescription(`**${track.name}** by **${track.artist}**\n[Open on Last.fm](${track.url})`)
.setFooter({ text: `Last.fm: ${user.username}` }); .setFooter({ text: `Last.fm: ${user.username}` });
@@ -406,7 +406,7 @@ export async function run(msg, data) {
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setAuthor({ name: `Last.fm Profile: ${info.name}`, icon_url: info.image?.[2]?.["#text"] || undefined, url: info.url }) .setAuthor({ name: `Last.fm Profile: ${info.name}`, iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url })
.setDescription([ .setDescription([
`🎵 **${Utils.formatNumber(info.playcount ?? 0)}** scrobbles`, `🎵 **${Utils.formatNumber(info.playcount ?? 0)}** scrobbles`,
`👤 Registered: ${info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown"}`, `👤 Registered: ${info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown"}`,
@@ -504,7 +504,7 @@ export async function run(msg, data) {
}); });
} }
return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks)] }); return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks, false, prefix)] });
} }
// ── Top tracks ───────────────────────────────────────────────────────── // ── Top tracks ─────────────────────────────────────────────────────────
@@ -527,7 +527,7 @@ export async function run(msg, data) {
}); });
} }
return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true)] }); return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true, prefix)] });
} }
// ── Leaderboard ───────────────────────────────────────────────────── // ── Leaderboard ─────────────────────────────────────────────────────
@@ -648,7 +648,7 @@ export async function run(msg, data) {
}); });
} }
return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks)] }); return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks, false, prefix)] });
} }
default: default:
@@ -684,7 +684,7 @@ export async function run(msg, data) {
// ── Track list embed builder ────────────────────────────────────────────────── // ── Track list embed builder ──────────────────────────────────────────────────
function buildTrackList(username, title, tracks, showPlaycount = false) { function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
const lines = tracks.map((t, i) => { const lines = tracks.map((t, i) => {
const num = String(i + 1).padStart(2, " "); const num = String(i + 1).padStart(2, " ");
let name = t.name; let name = t.name;
@@ -700,7 +700,7 @@ function buildTrackList(username, title, tracks, showPlaycount = false) {
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setTitle(`${title} — ${username}`) .setTitle(`${title} — ${username}`)
.setDescription(desc) .setDescription(desc)
.setFooter({ text: `💡 Use %lastfm play loved to play these!` }); .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
} }
// ── Leaderboard embed builder ───────────────────────────────────────────────── // ── Leaderboard embed builder ─────────────────────────────────────────────────
+4 -8
View File
@@ -1,6 +1,4 @@
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("remove") .setName("remove")
@@ -14,10 +12,8 @@ export const command = new CommandBuilder()
export async function run(message, data) { export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false); const p = await this.getPlayer(message, false, false, false);
if (!p) return; if (!p) return;
const res = p.remove(data.options[0].value - 1); const index = data.get("index")?.value;
const embed = new EmbedBuilder() if (index == null) return message.reply("Please provide a valid queue position.");
.setColor(getGlobalColor()) const res = p.remove(index - 1);
.setDescription(res) message.replyEmbed(res);
;
message.reply({ embeds: [embed] });
} }
+7 -4
View File
@@ -91,11 +91,14 @@ function getLivePlayerCount(playerMap) {
if (conn) { if (conn) {
const room = conn.room; const room = conn.room;
if (room) { if (room) {
const state = room.state; // Use @livekit/rtc-node Node.js SDK API:
// room.isConnected — boolean getter (true when connected)
// room.connectionState — ConnectionState enum (0=disconnected, 1=connected, 2=reconnecting)
// room.state does NOT exist in the Node.js SDK (browser-only API)
const isConnected = room.isConnected;
const connectionState = room.connectionState;
// Explicitly dead states → skip // Explicitly dead states → skip
if (state === "disconnected" || state === "failed" || state === 0) continue; if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
// undefined = connected on some LiveKit builds (no persistent state prop)
// "connected" = explicitly connected
} }
// conn exists but no room → still a valid LiveKit connection reference // conn exists but no room → still a valid LiveKit connection reference
} else { } else {
+6 -1
View File
@@ -50,6 +50,11 @@ export class MySqlSettingsManager extends SettingsManager {
constructor(config, defaultsPath) { constructor(config, defaultsPath) {
super(); super();
this.db = mysql.createPool({ connectionLimit: 15, ...config }); this.db = mysql.createPool({ connectionLimit: 15, ...config });
// Without this listener, any pool-level error (connection drop, timeout, protocol error)
// fires an unhandled 'error' event which crashes the entire process with no log output.
this.db.on("error", (err) => {
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
});
if (defaultsPath) this.loadDefaultsSync(defaultsPath); if (defaultsPath) this.loadDefaultsSync(defaultsPath);
this.load(); this.load();
} }
@@ -64,7 +69,7 @@ export class MySqlSettingsManager extends SettingsManager {
this._loadAttempts = (this._loadAttempts || 0) + 1; this._loadAttempts = (this._loadAttempts || 0) + 1;
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error); logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
return setTimeout(() => { this.load(); }, delay); return setTimeout(() => { this.load().catch(err => logger.error("[Settings] Retry load error:", err?.message ?? err)); }, delay);
} }
this._loadAttempts = 0; this._loadAttempts = 0;
res.results.forEach((r) => { res.results.forEach((r) => {
-1
View File
@@ -553,7 +553,6 @@ export class CommandHandler extends EventEmitter {
let usedArgumentCount = 0; let usedArgumentCount = 0;
for (let i = 0, argIndex = 1; i < options.length; i++) { for (let i = 0, argIndex = 1; i < options.length; i++) {
if (options[i] instanceof Flag) i++;
const o = options[i]; const o = options[i];
if (o?.type === "text") { texts.push(o); continue; } if (o?.type === "text") { texts.push(o); continue; }
if ((args[argIndex] || "").startsWith("-")) { if ((args[argIndex] || "").startsWith("-")) {
+3 -3
View File
@@ -538,7 +538,7 @@ export class GatewayHandler {
logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`); logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`);
for (const [channelId, player] of remix.players.playerMap) { for (const [channelId, player] of remix.players.playerMap) {
if (!player._guildId || player._guildId === guildId) { if (!player._guildId || String(player._guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) {
remix.players.playerMap.delete(channelId); remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {} try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {} try { player.destroy(); } catch (_) {}
@@ -547,10 +547,10 @@ export class GatewayHandler {
} }
for (const [userId, info] of [...remix.observedVoiceUsers]) { for (const [userId, info] of [...remix.observedVoiceUsers]) {
if (info.guildId === guildId) remix.observedVoiceUsers.delete(userId); if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) remix.observedVoiceUsers.delete(userId);
} }
for (const [userId, info] of [...remix.observedVoiceBots]) { for (const [userId, info] of [...remix.observedVoiceBots]) {
if (info.guildId === guildId) remix.observedVoiceBots.delete(userId); if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) remix.observedVoiceBots.delete(userId);
} }
for (const [stateKey, info] of [...this._prevVoiceState]) { for (const [stateKey, info] of [...this._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
+1 -1
View File
@@ -319,7 +319,7 @@ export class MessageHandler {
async sendMessage(channel, message) { async sendMessage(channel, message) {
if (this.checkPermissions(["SendMessages"], channel).length !== 0) { if (this.checkPermissions(["SendMessages"], channel).length !== 0) {
logger.warn("[MessageHandler] Missing SendMessages permission in channel", channel.id); logger.warn("[MessageHandler] Missing SendMessages permission in channel", channel.id);
return; return null;
} }
let opts; let opts;
if (typeof message === "string") { if (typeof message === "string") {
+1 -1
View File
@@ -891,7 +891,7 @@ export default class Player extends EventEmitter {
} }
if (![200, 204, 206].includes(res.statusCode)) { if (![200, 204, 206].includes(res.statusCode)) {
res.resume(); res.resume();
return reject(new Error(`HTTP ${res.statusCode} at ${target}`)); return reject(new Error(`HTTP ${res.statusCode}`));
} }
if (returnStream) return resolve(res); if (returnStream) return resolve(res);
+1 -1
View File
@@ -921,7 +921,7 @@ export class PlayerManager {
if (current.title !== song.title && current.url !== song.url) return; if (current.title !== song.title && current.url !== song.url) return;
if (player._paused) return; // don't scrobble if paused if (player._paused) return; // don't scrobble if paused
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs); const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
if (lastfm.shouldScrobble(song, playedMs)) { if (lastfm.shouldScrobble(song, playedMs)) {
for (const userId of humanUserIds) { for (const userId of humanUserIds) {
lastfm.scrobble(userId, song, startedAtMs).catch(() => {}); lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
+1 -1
View File
@@ -71,7 +71,7 @@ export class RemoteSettingsManager extends EventEmitter {
// exponential backoff with a cap of 30s instead of forever-at-2s // exponential backoff with a cap of 30s instead of forever-at-2s
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error); logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
return setTimeout(() => { this.load(); }, delay); return setTimeout(() => { this.load().catch(err => logger.error("[Settings] Retry load error:", err?.message ?? err)); }, delay);
} }
this._loadAttempts = 0; this._loadAttempts = 0;
res.results.forEach((r) => { res.results.forEach((r) => {
+1
View File
@@ -13,6 +13,7 @@ class StreamMerger extends Transform {
} }
_transform(chunk, _enc, cb) { _transform(chunk, _enc, cb) {
if (!this.ffmpeg) { this.push(chunk); return cb(); } if (!this.ffmpeg) { this.push(chunk); return cb(); }
if (!this.ffmpeg.stdio?.[3]?.writable) { this.push(chunk); return cb(); }
this.ffmpeg.stdio[3].write(chunk); this.ffmpeg.stdio[3].write(chunk);
cb(); cb();
} }
+12 -10
View File
@@ -38,28 +38,30 @@ class Tuna {
}); });
} }
search(query, page = 1, size = 10) { search(query, page = 1, size = 10) {
return new Promise(async res => { return this.get("/v1/sounds/search", { size, page, search: query }).then(results => {
const results = await this.get("/v1/sounds/search", { size, page, search: query });
results.items = results.items.map(s => { results.items = results.items.map(s => {
s.download = function() { s.download = function() {
return new Promise(resolve => { return new Promise((resolve, reject) => {
https.get(this.oggPath, (r) => { resolve(r); }); const req = https.get(this.oggPath, (r) => { resolve(r); });
req.on("error", (err) => { reject(err); });
req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); });
}); });
}; };
return s; return s;
}); });
res(results); return results;
}); });
} }
getSound(id) { getSound(id) {
return new Promise(async res => { return this.get("/v1/sounds/" + id).then(sound => {
const sound = await this.get("/v1/sounds/" + id);
sound.download = function() { sound.download = function() {
return new Promise(res => { return new Promise((resolve, reject) => {
https.get(this.oggPath, (result) => { res(result); }); const req = https.get(this.oggPath, (result) => { resolve(result); });
req.on("error", (err) => { reject(err); });
req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); });
}); });
}; };
res(sound); return sound;
}); });
} }
} }
+15 -3
View File
@@ -300,7 +300,7 @@ class YTUtils extends EventEmitter {
let tracks = []; let tracks = [];
if (data.loadType === "search") tracks = data.data ?? []; if (data.loadType === "search") tracks = data.data ?? [];
else if (data.loadType === "track") tracks = [data.data]; else if (data.loadType === "track") tracks = data.data ? [data.data] : [];
else if (data.loadType === "playlist") tracks = data.data?.tracks ?? []; else if (data.loadType === "playlist") tracks = data.data?.tracks ?? [];
const resultTracks = this._rankTracks(tracks, provider); const resultTracks = this._rankTracks(tracks, provider);
@@ -335,12 +335,18 @@ class YTUtils extends EventEmitter {
} }
// Handle single track // Handle single track
if (data.loadType === "track") { if (data.loadType === "track" && data.data) {
const video = trackToVideo(data.data); const video = trackToVideo(data.data);
if (!video) return { type: "error", data: "Failed to parse track data." };
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`); this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video }; return { type: "video", data: video };
} }
if (data.loadType === "track" && !data.data) {
this.emit("message", `**Track data was empty for '${query}'.**`);
return { type: "error", data: "Empty track data returned." };
}
// Handle search results (take first) // Handle search results (take first)
if (data.loadType === "search" && data.data?.length) { if (data.loadType === "search" && data.data?.length) {
const bestTrack = this._pickBestTrack(data.data, provider) ?? data.data[0]; const bestTrack = this._pickBestTrack(data.data, provider) ?? data.data[0];
@@ -383,12 +389,18 @@ class YTUtils extends EventEmitter {
} }
// Single track from search // Single track from search
if (data.loadType === "track") { if (data.loadType === "track" && data.data) {
const video = trackToVideo(data.data); const video = trackToVideo(data.data);
if (!video) return { type: "error", data: "Failed to parse track data." };
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`); this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video }; return { type: "video", data: video };
} }
if (data.loadType === "track" && !data.data) {
this.emit("message", `**Track data was empty for '${query}'.**`);
return { type: "error", data: "Empty track data returned." };
}
// Nothing found // Nothing found
this.emit("message", `**No results found for '${query}'.**`); this.emit("message", `**No results found for '${query}'.**`);
return { type: "error", data: null, error: "No results found" }; return { type: "error", data: null, error: "No results found" };