mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
rollback yes
This commit is contained in:
1 parent
73c290e59c
commit
f402237ad3
9 files changed
+502
-185
No files matched your search
+106
-8
@@ -1,23 +1,116 @@
|
|||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import Player from "../src/Player.mjs";
|
||||||
|
|
||||||
|
export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||||
|
if (!this.client.channels.cache.has(cid)) {
|
||||||
|
ecb();
|
||||||
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
|
.setDescription("Couldn't find the channel `" + cid + "`\nUse the help command to learn more about this. (`%help join`)")
|
||||||
|
.toJSON();
|
||||||
|
return message.replyEmbed({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
if (this.players.playerMap.has(cid)) {
|
||||||
|
cb(this.players.playerMap.get(cid));
|
||||||
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
|
.setDescription("Already joined <#" + cid + ">.")
|
||||||
|
.toJSON();
|
||||||
|
return message.replyEmbed({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Guard: moonlink must be ready before we can play anything
|
||||||
|
if (!this.moonlink) {
|
||||||
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
|
.setDescription("⚠️ Audio node is still connecting — please try again in a few seconds.")
|
||||||
|
.toJSON();
|
||||||
|
ecb();
|
||||||
|
return message.replyEmbed({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const p = new Player(this.config.token, {
|
||||||
|
client: this.client,
|
||||||
|
config: this.config,
|
||||||
|
nodelink: this.config.nodelink,
|
||||||
|
moonlink: this.moonlink ?? null,
|
||||||
|
messageChannel: message.channel,
|
||||||
|
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
||||||
|
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
|
p.on("autoleave", () => {
|
||||||
|
const guildId = message.channel?.guildId
|
||||||
|
?? message.channel?.guild?.id
|
||||||
|
?? message.message?.guildId
|
||||||
|
?? message.channel?.server_id
|
||||||
|
?? message.channel?.serverId;
|
||||||
|
const is247 = (() => {
|
||||||
|
try {
|
||||||
|
const raw = this.settingsMgr?.getServer?.(guildId)?.get?.("stay_247");
|
||||||
|
return raw && raw !== "none";
|
||||||
|
} catch (_) { return false; }
|
||||||
|
})();
|
||||||
|
const prefix = (() => {
|
||||||
|
try {
|
||||||
|
return this._commands?.getPrefix?.(message.channel?.guild?.id) ?? "%";
|
||||||
|
} catch (_) { return "%"; }
|
||||||
|
})();
|
||||||
|
const desc = is247
|
||||||
|
? `Left channel <#${cid}> because of inactivity.`
|
||||||
|
: `Left channel <#${cid}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
|
||||||
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
|
.setDescription(desc)
|
||||||
|
.toJSON();
|
||||||
|
message.channel.sendEmbed({ embeds: [embed] });
|
||||||
|
this.players.playerMap.delete(cid);
|
||||||
|
p.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
p.on("message", m => {
|
||||||
|
const guildId = message.channel?.guild?.id ?? message.channel?.server_id ?? message.channel?.serverId;
|
||||||
|
const raw = this.settingsMgr?.getServer?.(guildId)?.get("songAnnouncements");
|
||||||
|
const disabled = raw === false || raw === 0 ||
|
||||||
|
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||||
|
if (disabled) return;
|
||||||
|
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(m).toJSON();
|
||||||
|
message.channel.sendEmbed({ embeds: [embed] });
|
||||||
|
});
|
||||||
|
|
||||||
|
this.players.playerMap.set(cid, p);
|
||||||
|
|
||||||
|
const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription("⏳ Joining Channel...").toJSON();
|
||||||
|
const statusMsg = await message.replyEmbed({ embeds: [joiningEmbed] });
|
||||||
|
try {
|
||||||
|
await p.join(cid);
|
||||||
|
const okEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(`✅ Successfully joined <#${cid}>`).toJSON();
|
||||||
|
await statusMsg.editEmbed({ embeds: [okEmbed] });
|
||||||
|
cb(p);
|
||||||
|
} catch (e) {
|
||||||
|
this.players.playerMap.delete(cid);
|
||||||
|
p.destroy();
|
||||||
|
const errEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(`❌ Failed to join: ${e.message}`).toJSON();
|
||||||
|
await statusMsg.editEmbed({ embeds: [errEmbed] });
|
||||||
|
ecb(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("join")
|
.setName("join")
|
||||||
.setDescription("Make the bot join your voice channel, or specify one.")
|
.setDescription("Make the bot join your voice channel, or specify one.", "commands.join")
|
||||||
.setId("join")
|
.setId("join")
|
||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addTextOption(option =>
|
.addTextOption(option =>
|
||||||
option.setName("channel")
|
option.setName("channel")
|
||||||
.setDescription("A voice channel mention, ID, or name to join.")
|
.setDescription("A voice channel mention, ID, or name to join. Defaults to your current channel.")
|
||||||
.setRequired(false)
|
.setRequired(false)
|
||||||
);
|
);
|
||||||
|
|
||||||
export async function run(message, data) {
|
export function run(message, data) {
|
||||||
|
// Check if a channel argument was provided (mention like <#123456>, bare ID, or name)
|
||||||
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
||||||
|
|
||||||
if (rawArg) {
|
if (rawArg) {
|
||||||
// Parse channel mention, ID, or name
|
// Parse channel mention <#ID>, bare numeric ID, or channel name
|
||||||
const mentionMatch = rawArg.match(/^<#(\d+)>$/);
|
const mentionMatch = rawArg.match(/^<#(\d+)>$/);
|
||||||
const idMatch = rawArg.match(/^(\d{15,})$/);
|
const idMatch = rawArg.match(/^(\d{15,})$/);
|
||||||
let resolvedId = null;
|
let resolvedId = null;
|
||||||
@@ -27,7 +120,7 @@ export async function run(message, data) {
|
|||||||
} else if (idMatch) {
|
} else if (idMatch) {
|
||||||
resolvedId = idMatch[1];
|
resolvedId = idMatch[1];
|
||||||
} else {
|
} else {
|
||||||
// Lookup by name
|
// Try to look up by name
|
||||||
const serverId = message.channel?.server_id ?? message.channel?.serverId;
|
const serverId = message.channel?.server_id ?? message.channel?.serverId;
|
||||||
const allChannels = [
|
const allChannels = [
|
||||||
...(this._commands?.client?.channels?.values?.() ??
|
...(this._commands?.client?.channels?.values?.() ??
|
||||||
@@ -46,7 +139,7 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
if (!resolvedId) {
|
if (!resolvedId) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
.setDescription("❌ Couldn't find that voice channel.")
|
.setDescription("❌ Couldn't find that voice channel. Try using a mention like `<#channelid>` or the exact channel name.")
|
||||||
.toJSON();
|
.toJSON();
|
||||||
return message.replyEmbed({ embeds: [embed] });
|
return message.replyEmbed({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -54,8 +147,8 @@ export async function run(message, data) {
|
|||||||
return this.players.initPlayer(message, resolvedId);
|
return this.players.initPlayer(message, resolvedId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// No argument — auto-detect (CRITICAL: must await here)
|
// No argument — auto-detect the user's current voice channel
|
||||||
const cid = await this.players.checkVoiceChannels(message);
|
const cid = this.players.checkVoiceChannels(message);
|
||||||
|
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
const prefix = this._commands?.getPrefix?.(message.channel?.guild?.id ?? message.channel?.server_id ?? message.channel?.serverId) ?? "%";
|
const prefix = this._commands?.getPrefix?.(message.channel?.guild?.id ?? message.channel?.server_id ?? message.channel?.serverId) ?? "%";
|
||||||
@@ -67,3 +160,8 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
this.players.initPlayer(message, cid);
|
this.players.initPlayer(message, cid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const exportDef = {
|
||||||
|
name: "joinChannel",
|
||||||
|
object: joinChannel
|
||||||
|
};
|
||||||
+16
-25
@@ -16,35 +16,26 @@ function embed(desc) {
|
|||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const guildId = msg.channel?.guild?.id ?? msg.message?.guildId;
|
const guildId = msg.channel?.guild?.id ?? msg.message?.guildId;
|
||||||
|
|
||||||
// Get all players in this guild
|
const userChannelId = this.players.checkVoiceChannels(msg);
|
||||||
const guildPlayers = [...this.players.playerMap.entries()]
|
if (!userChannelId) return msg.replyEmbed(embed("⚠️ Please join a voice channel first."));
|
||||||
.filter(([chId, p]) => p._guildId === guildId);
|
|
||||||
|
|
||||||
if (guildPlayers.length === 0) {
|
const cid = String(userChannelId).replace(/\D/g, "");
|
||||||
return msg.replyEmbed(embed("❌ I'm not in a voice channel in this server."));
|
|
||||||
|
if (!this.players.playerMap.has(cid)) {
|
||||||
|
const guildChannels = [...this.players.playerMap.entries()]
|
||||||
|
.filter(([chId, p]) => p._guildId === guildId)
|
||||||
|
.map(([chId]) => `<#${chId}>`);
|
||||||
|
|
||||||
|
if (guildChannels.length === 0) return msg.replyEmbed(embed("I'm not in a voice channel."));
|
||||||
|
if (guildChannels.length === 1) return msg.replyEmbed(embed(`⚠️ Please join ${guildChannels[0]} to use this command.`));
|
||||||
|
return msg.replyEmbed(embed(
|
||||||
|
`⚠️ I'm playing in multiple channels! Please join one of them:\n` +
|
||||||
|
guildChannels.map(c => `• ${c}`).join("\n")
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let cid;
|
|
||||||
|
|
||||||
// Try to find the channel the user is in (optional, for convenience)
|
|
||||||
const userChannelId = await this.players.checkVoiceChannels(msg);
|
|
||||||
|
|
||||||
if (userChannelId && guildPlayers.some(([chId]) => chId === userChannelId)) {
|
|
||||||
// User is in a channel where the bot is playing - use that one
|
|
||||||
cid = userChannelId;
|
|
||||||
} else if (guildPlayers.length === 1) {
|
|
||||||
// Only one player in guild - use that one
|
|
||||||
cid = guildPlayers[0][0];
|
|
||||||
} else {
|
|
||||||
// Multiple channels - use the first one found
|
|
||||||
// Or you could implement a selection menu here
|
|
||||||
cid = guildPlayers[0][0];
|
|
||||||
}
|
|
||||||
|
|
||||||
cid = String(cid).replace(/\D/g, "");
|
|
||||||
|
|
||||||
const player = this.players.playerMap.get(cid);
|
const player = this.players.playerMap.get(cid);
|
||||||
if (!player?.connection) return msg.replyEmbed(embed("❌ Player not initialized."));
|
if (!player?.connection) return msg.replyEmbed(embed("Player not initialized."));
|
||||||
|
|
||||||
const set = this.getSettings(msg);
|
const set = this.getSettings(msg);
|
||||||
const raw = set?.get("stay_247");
|
const raw = set?.get("stay_247");
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ export const command = new CommandBuilder()
|
|||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const res = p.resume();
|
const res = p.resume();
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ export const command = new CommandBuilder()
|
|||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const res = p.shuffle();
|
const res = p.shuffle();
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ export const command = new CommandBuilder()
|
|||||||
// ── User count ────────────────────────────────────────────────────────────────
|
// ── User count ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
async function fetchUserCount(client) {
|
async function fetchUserCount(client) {
|
||||||
|
// client.rest is a concept and is not available on @fluxerjs/core.
|
||||||
|
// Use guild.memberCount (a cached integer Fluxer exposes on every Guild object)
|
||||||
|
// instead of paginating the REST members endpoint.
|
||||||
|
// Falls back to 0 per guild if the property is absent so the stat still renders.
|
||||||
try {
|
try {
|
||||||
let total = 0;
|
let total = 0;
|
||||||
for (const guild of client.guilds.cache.values()) {
|
for (const guild of client.guilds.cache.values()) {
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ class Remix {
|
|||||||
this.moonlink = null;
|
this.moonlink = null;
|
||||||
|
|
||||||
// Guards for one-time setup inside Events.Ready (which fires on every reconnect).
|
// Guards for one-time setup inside Events.Ready (which fires on every reconnect).
|
||||||
|
// Without these, each reconnect stacks another listener / interval.
|
||||||
let wsListenerAttached = false;
|
let wsListenerAttached = false;
|
||||||
let moonlinkInitialised = false;
|
let moonlinkInitialised = false;
|
||||||
let presenceTimer = null;
|
let presenceTimer = null;
|
||||||
@@ -121,6 +122,8 @@ class Remix {
|
|||||||
try {
|
try {
|
||||||
let channel = client.channels.cache.get(cleanChannelId);
|
let channel = client.channels.cache.get(cleanChannelId);
|
||||||
if (!channel) {
|
if (!channel) {
|
||||||
|
// voiceAdapterCreator is a concept and not meaningful in Fluxer.
|
||||||
|
// A simple cache-miss check is sufficient — fetch only when not already cached.
|
||||||
try {
|
try {
|
||||||
channel = await client.channels.fetch(cleanChannelId);
|
channel = await client.channels.fetch(cleanChannelId);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -157,6 +160,9 @@ class Remix {
|
|||||||
try {
|
try {
|
||||||
const prefix = this.handler?.getPrefix?.(guildId) ?? "%";
|
const prefix = this.handler?.getPrefix?.(guildId) ?? "%";
|
||||||
const guild = this.client.guilds.cache.get(guildId);
|
const guild = this.client.guilds.cache.get(guildId);
|
||||||
|
// isTextBased() and permissionsFor() are APIs — use optional
|
||||||
|
// chaining so missing implementations fail gracefully. Fall back to channel_type
|
||||||
|
// string check which is the raw Fluxer gateway field.
|
||||||
const ch = guild?.channels?.cache?.find(c =>
|
const ch = guild?.channels?.cache?.find(c =>
|
||||||
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
|
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
|
||||||
(c.permissionsFor?.(this.client.user)?.has?.("SendMessages") ?? true)
|
(c.permissionsFor?.(this.client.user)?.has?.("SendMessages") ?? true)
|
||||||
@@ -177,12 +183,17 @@ class Remix {
|
|||||||
|
|
||||||
p.on("message", (m) => {
|
p.on("message", (m) => {
|
||||||
const raw = this.settingsMgr.getServer(guildId).get("songAnnouncements");
|
const raw = this.settingsMgr.getServer(guildId).get("songAnnouncements");
|
||||||
|
// Centralised falsy check — mirrors the canonical list in settings/runnables.mjs
|
||||||
|
// so both places stay in sync if valid values ever change.
|
||||||
const disabled = raw === false || raw === 0 ||
|
const disabled = raw === false || raw === 0 ||
|
||||||
["false", "0", "no", "off", "disable"].includes(String(raw).toLowerCase().trim());
|
["false", "0", "no", "off", "disable"].includes(String(raw).toLowerCase().trim());
|
||||||
if (disabled) return;
|
if (disabled) return;
|
||||||
const guild = this.client.guilds.cache.get(guildId);
|
const guild = this.client.guilds.cache.get(guildId);
|
||||||
|
// _announcementChannelCache is always a Map — no null check needed.
|
||||||
const cachedChId = this._announcementChannelCache.get(guildId);
|
const cachedChId = this._announcementChannelCache.get(guildId);
|
||||||
let ch = cachedChId ? guild?.channels?.cache?.get(cachedChId) : null;
|
let ch = cachedChId ? guild?.channels?.cache?.get(cachedChId) : null;
|
||||||
|
// if cached channel is gone (deleted/uncached), clear the stale
|
||||||
|
// entry immediately so we don't re-scan on every subsequent message event.
|
||||||
if (cachedChId && !ch) {
|
if (cachedChId && !ch) {
|
||||||
this._announcementChannelCache.delete(guildId);
|
this._announcementChannelCache.delete(guildId);
|
||||||
}
|
}
|
||||||
@@ -301,6 +312,9 @@ class Remix {
|
|||||||
const botId = client.user?.id ?? "0";
|
const botId = client.user?.id ?? "0";
|
||||||
|
|
||||||
// Guard Moonlink creation exactly like wsListenerAttached guards the WS listener.
|
// Guard Moonlink creation exactly like wsListenerAttached guards the WS listener.
|
||||||
|
// Previously new MoonlinkManager() + .on("ready") ran on every gateway reconnect,
|
||||||
|
// creating a fresh instance each time and stacking an extra "ready" listener on it.
|
||||||
|
// The old orphaned instance kept its listener alive → duplicate session updates + memory leak.
|
||||||
if (!moonlinkInitialised) {
|
if (!moonlinkInitialised) {
|
||||||
moonlinkInitialised = true;
|
moonlinkInitialised = true;
|
||||||
this.moonlink = new MoonlinkManager(config.nodelink ?? {}, client);
|
this.moonlink = new MoonlinkManager(config.nodelink ?? {}, client);
|
||||||
@@ -329,6 +343,9 @@ class Remix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const [gId, guild] of client.guilds.cache) {
|
for (const [gId, guild] of client.guilds.cache) {
|
||||||
|
// guild.voice_states — raw snake_case array from @fluxerjs/core gateway payload (preferred).
|
||||||
|
// guild.voiceStates?.cache — voiceStateManager collection (fallback, may not exist).
|
||||||
|
// guild.voiceStates — bare iterable fallback if cache sub-property is absent.
|
||||||
const voiceStatesRaw =
|
const voiceStatesRaw =
|
||||||
guild.voice_states ??
|
guild.voice_states ??
|
||||||
guild.voiceStates?.cache ??
|
guild.voiceStates?.cache ??
|
||||||
@@ -351,9 +368,16 @@ class Remix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Guard WS listener registration so it only runs once across all reconnects.
|
// Guard WS listener registration so it only runs once across all reconnects.
|
||||||
|
// Without this, each reconnect stacks a new listener on the same socket, causing
|
||||||
|
// every WS frame to be processed N times after N reconnects.
|
||||||
if (!wsListenerAttached) {
|
if (!wsListenerAttached) {
|
||||||
wsListenerAttached = true;
|
wsListenerAttached = true;
|
||||||
try {
|
try {
|
||||||
|
// NOTE: client.ws.shards is declared private in @fluxerjs/ws, but there is
|
||||||
|
// no public API for attaching a raw message listener to the underlying socket.
|
||||||
|
// ws.send(shardId, payload) exists for sending, but not for receiving.
|
||||||
|
// This access is intentional — if @fluxerjs/core ever exposes a public
|
||||||
|
// onRawMessage() hook, replace these two lines with that API instead.
|
||||||
const shard0 = client.ws?.shards?.get?.(0);
|
const shard0 = client.ws?.shards?.get?.(0);
|
||||||
const wsObj = shard0?.ws ?? null;
|
const wsObj = shard0?.ws ?? null;
|
||||||
|
|
||||||
@@ -367,6 +391,29 @@ class Remix {
|
|||||||
|
|
||||||
if (payload?.op !== 0) return;
|
if (payload?.op !== 0) return;
|
||||||
|
|
||||||
|
// READY payload contains an unavailable-guilds summary, but some
|
||||||
|
// Fluxer gateway implementations include voice_states inside each
|
||||||
|
// guild object in the READY d.guilds array — seed them here so the
|
||||||
|
// bot knows who is in voice immediately on reboot, before the
|
||||||
|
// individual GUILD_CREATE bursts complete.
|
||||||
|
if (payload.t === "READY") {
|
||||||
|
const readyGuilds = payload.d?.guilds;
|
||||||
|
if (Array.isArray(readyGuilds)) {
|
||||||
|
for (const g of readyGuilds) {
|
||||||
|
const gId = g?.id;
|
||||||
|
if (!gId || !Array.isArray(g.voice_states)) continue;
|
||||||
|
for (const state of g.voice_states) {
|
||||||
|
const userId = state.user_id;
|
||||||
|
const channelId = state.channel_id;
|
||||||
|
if (!userId || !channelId) continue;
|
||||||
|
const isBot = state.member?.user?.bot ?? false;
|
||||||
|
const target = isBot ? this.observedVoiceBots : this.observedVoiceUsers;
|
||||||
|
target.set(userId, { channelId, guildId: gId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (payload.t === "GUILD_CREATE") {
|
if (payload.t === "GUILD_CREATE") {
|
||||||
const d = payload.d;
|
const d = payload.d;
|
||||||
const gId = d?.id;
|
const gId = d?.id;
|
||||||
@@ -391,6 +438,8 @@ class Remix {
|
|||||||
const isBot = d?.member?.user?.bot ?? false;
|
const isBot = d?.member?.user?.bot ?? false;
|
||||||
if (!userId) return;
|
if (!userId) return;
|
||||||
const target = isBot ? this.observedVoiceBots : this.observedVoiceUsers;
|
const target = isBot ? this.observedVoiceBots : this.observedVoiceUsers;
|
||||||
|
// WS path correctly deletes on channelId=null,
|
||||||
|
// keeping observedVoice* from growing unbounded.
|
||||||
if (channelId) target.set(userId, { channelId, guildId });
|
if (channelId) target.set(userId, { channelId, guildId });
|
||||||
else target.delete(userId);
|
else target.delete(userId);
|
||||||
}
|
}
|
||||||
@@ -409,6 +458,9 @@ class Remix {
|
|||||||
tryAutoJoin();
|
tryAutoJoin();
|
||||||
|
|
||||||
if (presenceContents.length > 0) {
|
if (presenceContents.length > 0) {
|
||||||
|
// setPresence now uses the outer presenceIndex so rotation
|
||||||
|
// continues from where it left off after a reconnect instead of
|
||||||
|
// restarting from 0 each time.
|
||||||
const setPresence = () => {
|
const setPresence = () => {
|
||||||
const presence = {
|
const presence = {
|
||||||
status: "online",
|
status: "online",
|
||||||
@@ -416,23 +468,34 @@ class Remix {
|
|||||||
afk: false,
|
afk: false,
|
||||||
custom_status: { text: presenceContents[presenceIndex] },
|
custom_status: { text: presenceContents[presenceIndex] },
|
||||||
};
|
};
|
||||||
|
// Use the public ws.send(shardId, payload) API instead of accessing the
|
||||||
|
// private shards Map directly — shards is declared private in @fluxerjs/ws
|
||||||
|
// and accessing it works at runtime but breaks on any internal refactor.
|
||||||
if (client.ws?.send) {
|
if (client.ws?.send) {
|
||||||
client.ws.send(0, { op: GatewayOpcodes.PresenceUpdate, d: presence });
|
client.ws.send(0, { op: GatewayOpcodes.PresenceUpdate, d: presence });
|
||||||
} else {
|
} else {
|
||||||
|
// Fallback: access shards directly only if public API is unavailable
|
||||||
const shard = client.ws?.shards?.get?.(0);
|
const shard = client.ws?.shards?.get?.(0);
|
||||||
if (shard) shard.send({ op: GatewayOpcodes.PresenceUpdate, d: presence });
|
if (shard) shard.send({ op: GatewayOpcodes.PresenceUpdate, d: presence });
|
||||||
}
|
}
|
||||||
presenceIndex = (presenceIndex + 1) % presenceContents.length;
|
presenceIndex = (presenceIndex + 1) % presenceContents.length;
|
||||||
};
|
};
|
||||||
setPresence();
|
setPresence();
|
||||||
|
// Clear any existing interval before creating a new one.
|
||||||
|
// Without this, each reconnect stacks another setInterval, eventually
|
||||||
|
// spamming the gateway with duplicate presence updates.
|
||||||
if (presenceTimer) clearInterval(presenceTimer);
|
if (presenceTimer) clearInterval(presenceTimer);
|
||||||
presenceTimer = setInterval(setPresence, presenceInterval);
|
presenceTimer = setInterval(setPresence, presenceInterval);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Voice state tracking ──────────────────────────────────────────────────
|
// ── Voice state tracking ──────────────────────────────────────────────────
|
||||||
|
// Both maps are cleaned up in the WS handleRaw VOICE_STATE_UPDATE path
|
||||||
|
// (channelId=null → delete) and in GuildDelete, so they don't grow unbounded.
|
||||||
this.observedVoiceUsers = new Map();
|
this.observedVoiceUsers = new Map();
|
||||||
this.observedVoiceBots = new Map();
|
this.observedVoiceBots = new Map();
|
||||||
|
// initialise announcement channel cache eagerly alongside other caches
|
||||||
|
// so the hot path never needs a null-check allocation.
|
||||||
this._announcementChannelCache = new Map();
|
this._announcementChannelCache = new Map();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -441,12 +504,15 @@ class Remix {
|
|||||||
*/
|
*/
|
||||||
this.intentionalLeaves = new Map();
|
this.intentionalLeaves = new Map();
|
||||||
|
|
||||||
// GuildCreate handler - voice state population ALWAYS runs
|
// Merged the two separate GuildCreate handlers into one.
|
||||||
|
// Previously there were two client.on(Events.GuildCreate) registrations.
|
||||||
|
// Every GuildCreate event was firing both handlers — doubling voice-state work and
|
||||||
|
// triggering a burst of parallel DB queries on startup for every guild.
|
||||||
client.on(Events.GuildCreate, async (guild) => {
|
client.on(Events.GuildCreate, async (guild) => {
|
||||||
const guildId = guild?.id ?? guild?._id;
|
const guildId = guild?.id ?? guild?._id;
|
||||||
if (!guildId) return;
|
if (!guildId) return;
|
||||||
|
|
||||||
// ── Voice state population (ALWAYS RUN THIS) ────────────────────
|
// ── Part 1: Voice state population ──────────────────────────────────────
|
||||||
const voiceStatesRaw =
|
const voiceStatesRaw =
|
||||||
guild.voice_states ??
|
guild.voice_states ??
|
||||||
guild.voiceStates?.cache ??
|
guild.voiceStates?.cache ??
|
||||||
@@ -468,10 +534,11 @@ class Remix {
|
|||||||
const target = isBot ? this.observedVoiceBots : this.observedVoiceUsers;
|
const target = isBot ? this.observedVoiceBots : this.observedVoiceUsers;
|
||||||
target.set(userId, { channelId, guildId: sgid });
|
target.set(userId, { channelId, guildId: sgid });
|
||||||
}
|
}
|
||||||
logger.voiceState(`[GuildCreate] Populated ${entries.length} voice states for ${guildId}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Settings init for NEW servers only ─────────────────────────
|
// ── Part 2: Settings init for new/re-joined servers ──────────────────────
|
||||||
|
// GuildCreate fires on initial join AND on gateway resume for existing servers.
|
||||||
|
// Only act when the guild is missing from our cache (new join or post-GuildDelete).
|
||||||
if (!this.settingsMgr.guilds.has(guildId)) {
|
if (!this.settingsMgr.guilds.has(guildId)) {
|
||||||
logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`);
|
logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`);
|
||||||
try {
|
try {
|
||||||
@@ -489,6 +556,7 @@ class Remix {
|
|||||||
const server = new ServerSettings(guildId, this.settingsMgr);
|
const server = new ServerSettings(guildId, this.settingsMgr);
|
||||||
server.checkDefaults(this.settingsMgr.defaults);
|
server.checkDefaults(this.settingsMgr.defaults);
|
||||||
this.settingsMgr.guilds.set(guildId, server);
|
this.settingsMgr.guilds.set(guildId, server);
|
||||||
|
// Persist the new row so settings survive restarts from the first join.
|
||||||
await this.settingsMgr.create(guildId, server);
|
await this.settingsMgr.create(guildId, server);
|
||||||
logger.guild(`[GuildCreate] Fresh settings initialised for server ${guildId}.`);
|
logger.guild(`[GuildCreate] Fresh settings initialised for server ${guildId}.`);
|
||||||
}
|
}
|
||||||
@@ -505,6 +573,10 @@ class Remix {
|
|||||||
|
|
||||||
logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`);
|
logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`);
|
||||||
|
|
||||||
|
// Use player._guildId directly instead of resolving the channel from
|
||||||
|
// client.channels.cache (which may already be evicted at this point).
|
||||||
|
// The old approach fell through 4 property-chain guesses and silently leaked the
|
||||||
|
// player when all of them were undefined (e.g. after a partial cache eviction).
|
||||||
for (const [channelId, player] of this.players.playerMap) {
|
for (const [channelId, player] of this.players.playerMap) {
|
||||||
if (!player._guildId || player._guildId === guildId) {
|
if (!player._guildId || player._guildId === guildId) {
|
||||||
this.players.playerMap.delete(channelId);
|
this.players.playerMap.delete(channelId);
|
||||||
@@ -514,6 +586,7 @@ class Remix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clear voice-state tracking for this server
|
||||||
for (const [userId, info] of [...this.observedVoiceUsers]) {
|
for (const [userId, info] of [...this.observedVoiceUsers]) {
|
||||||
if (info.guildId === guildId) this.observedVoiceUsers.delete(userId);
|
if (info.guildId === guildId) this.observedVoiceUsers.delete(userId);
|
||||||
}
|
}
|
||||||
@@ -521,16 +594,22 @@ class Remix {
|
|||||||
if (info.guildId === guildId) this.observedVoiceBots.delete(userId);
|
if (info.guildId === guildId) this.observedVoiceBots.delete(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Drop the cached settings so stale data can't be read back
|
||||||
this.settingsMgr.removeServer(guildId);
|
this.settingsMgr.removeServer(guildId);
|
||||||
|
|
||||||
|
// Clear announcement channel cache for this guild
|
||||||
this._announcementChannelCache.delete(guildId);
|
this._announcementChannelCache.delete(guildId);
|
||||||
|
|
||||||
logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`);
|
logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Track previous voice state per-user so we can detect channel moves.
|
// Track previous voice state per-user so we can detect channel moves.
|
||||||
|
// @fluxerjs/core fires VoiceStateUpdate with ONE arg (raw gateway data),
|
||||||
|
// not two args (oldState, newState) We maintain prev state manually.
|
||||||
const _prevVoiceState = new Map(); // userId → { channelId, guildId }
|
const _prevVoiceState = new Map(); // userId → { channelId, guildId }
|
||||||
|
|
||||||
client.on(Events.VoiceStateUpdate, (data) => {
|
client.on(Events.VoiceStateUpdate, (data) => {
|
||||||
|
// data is the raw GatewayVoiceStateUpdateDispatchData — always snake_case
|
||||||
const userId = data?.user_id;
|
const userId = data?.user_id;
|
||||||
if (!userId) return;
|
if (!userId) return;
|
||||||
|
|
||||||
@@ -538,19 +617,24 @@ class Remix {
|
|||||||
const guildId = data?.guild_id;
|
const guildId = data?.guild_id;
|
||||||
const isBot = data?.member?.user?.bot ?? null;
|
const isBot = data?.member?.user?.bot ?? null;
|
||||||
|
|
||||||
|
// Capture old channel BEFORE updating prev state
|
||||||
const prev = _prevVoiceState.get(userId);
|
const prev = _prevVoiceState.get(userId);
|
||||||
const oldChannelId = prev?.channelId ?? null;
|
const oldChannelId = prev?.channelId ?? null;
|
||||||
|
|
||||||
|
// Update prev state
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
_prevVoiceState.set(userId, { channelId, guildId });
|
_prevVoiceState.set(userId, { channelId, guildId });
|
||||||
} else {
|
} else {
|
||||||
_prevVoiceState.delete(userId);
|
_prevVoiceState.delete(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Always update/delete the voice maps so they never accumulate stale entries
|
||||||
const target = isBot === true ? this.observedVoiceBots : this.observedVoiceUsers;
|
const target = isBot === true ? this.observedVoiceBots : this.observedVoiceUsers;
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
target.set(userId, { channelId, guildId });
|
target.set(userId, { channelId, guildId });
|
||||||
} else {
|
} else {
|
||||||
|
// On leave, delete from BOTH maps — isBot can be null/inconsistent
|
||||||
|
// between join and leave events, so the user may be in either map.
|
||||||
this.observedVoiceUsers.delete(userId);
|
this.observedVoiceUsers.delete(userId);
|
||||||
this.observedVoiceBots.delete(userId);
|
this.observedVoiceBots.delete(userId);
|
||||||
}
|
}
|
||||||
@@ -558,6 +642,7 @@ class Remix {
|
|||||||
const isBotUser = isBot === true && userId === client.user?.id;
|
const isBotUser = isBot === true && userId === client.user?.id;
|
||||||
|
|
||||||
if (!isBotUser) {
|
if (!isBotUser) {
|
||||||
|
// Resolve guildId from prev state too — leave events may have null guild_id
|
||||||
const resolvedGuildId = guildId ?? prev?.guildId;
|
const resolvedGuildId = guildId ?? prev?.guildId;
|
||||||
if (!resolvedGuildId) return;
|
if (!resolvedGuildId) return;
|
||||||
|
|
||||||
@@ -574,6 +659,7 @@ class Remix {
|
|||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Human LEFT a voice channel → check if bot is now alone
|
||||||
if (oldChannelId && oldChannelId !== channelId) {
|
if (oldChannelId && oldChannelId !== channelId) {
|
||||||
try {
|
try {
|
||||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||||
@@ -589,6 +675,7 @@ class Remix {
|
|||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Human JOINED the bot's channel → cancel inactivity timer
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
try {
|
try {
|
||||||
const cleanId = String(channelId).replace(/\D/g, "");
|
const cleanId = String(channelId).replace(/\D/g, "");
|
||||||
@@ -603,7 +690,9 @@ class Remix {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bot-only logic below
|
// ── Bot-only logic below ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Auto-save channel when bot moves (247 active)
|
||||||
if (channelId && guildId && oldChannelId && oldChannelId !== channelId) {
|
if (channelId && guildId && oldChannelId && oldChannelId !== channelId) {
|
||||||
try {
|
try {
|
||||||
const set = this.settingsMgr.getServer(guildId);
|
const set = this.settingsMgr.getServer(guildId);
|
||||||
@@ -625,6 +714,7 @@ class Remix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bot disconnected unexpectedly — rejoin if 247 active
|
||||||
if (!channelId && oldChannelId && guildId) {
|
if (!channelId && oldChannelId && guildId) {
|
||||||
try {
|
try {
|
||||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||||
@@ -703,13 +793,13 @@ class Remix {
|
|||||||
nodelink: config.nodelink,
|
nodelink: config.nodelink,
|
||||||
moonlink: null,
|
moonlink: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
// FIXED: Initialize PlayerManager with proper references
|
|
||||||
this.players = new PlayerManager(settings, commands, { config, player: this.playerContext });
|
this.players = new PlayerManager(settings, commands, { config, player: this.playerContext });
|
||||||
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||||
this.players.client = client; // CRITICAL: Ensure client reference is set
|
|
||||||
|
|
||||||
// ── Periodic alone-check ───────────────────────────────────────────────────
|
// ── Periodic alone-check ───────────────────────────────────────────────────
|
||||||
|
// Every 30 seconds, scan all active players. If the bot is alone in a voice
|
||||||
|
// channel (no humans) and 247 is NOT on/auto, leave immediately.
|
||||||
|
// This is the authoritative leave mechanism — does not rely on voice state events.
|
||||||
const ALONE_CHECK_INTERVAL = T.aloneCheckInterval;
|
const ALONE_CHECK_INTERVAL = T.aloneCheckInterval;
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
for (const [channelId, player] of this.players.playerMap) {
|
for (const [channelId, player] of this.players.playerMap) {
|
||||||
@@ -717,8 +807,11 @@ class Remix {
|
|||||||
const guildId = player._guildId;
|
const guildId = player._guildId;
|
||||||
if (!guildId) continue;
|
if (!guildId) continue;
|
||||||
|
|
||||||
|
// Skip if 247 is on or auto
|
||||||
if (player._is247Enabled()) continue;
|
if (player._is247Enabled()) continue;
|
||||||
|
|
||||||
|
// Read directly from observedVoiceUsers — bypass any cache issues
|
||||||
|
// Normalize both sides to digits-only to avoid format mismatch
|
||||||
const cleanChanId = String(channelId).replace(/\D/g, "");
|
const cleanChanId = String(channelId).replace(/\D/g, "");
|
||||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||||
let hasHuman = false;
|
let hasHuman = false;
|
||||||
@@ -734,18 +827,92 @@ class Remix {
|
|||||||
logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`);
|
logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`);
|
||||||
|
|
||||||
if (!hasHuman && !player._paused) {
|
if (!hasHuman && !player._paused) {
|
||||||
|
// If the bot is playing (queue has a current track), start the
|
||||||
|
// inactivity timer so it waits the configured timeout before leaving.
|
||||||
|
// _startInactivityTimer is a no-op if the timer is already running,
|
||||||
|
// so this is safe to call on every interval tick.
|
||||||
|
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||||
|
logger.aloneCheck(`[AloneCheck] Bot alone in ${channelId} (guild ${guildId}) with songs in queue — starting inactivity timer.`);
|
||||||
|
player._startInactivityTimer?.();
|
||||||
|
} else {
|
||||||
logger.aloneCheck(`[AloneCheck] Bot alone in ${channelId} (guild ${guildId}), leaving.`);
|
logger.aloneCheck(`[AloneCheck] Bot alone in ${channelId} (guild ${guildId}), leaving.`);
|
||||||
player._stopInactivityTimer?.();
|
player._stopInactivityTimer?.();
|
||||||
player.emit("autoleave");
|
player.emit("autoleave");
|
||||||
}
|
}
|
||||||
|
} else if (hasHuman) {
|
||||||
|
// A human rejoined — cancel any pending inactivity leave.
|
||||||
|
player._stopInactivityTimer?.();
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[AloneCheck] Error checking channel", channelId, e.message);
|
logger.warn("[AloneCheck] Error checking channel", channelId, e.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, ALONE_CHECK_INTERVAL);
|
}, ALONE_CHECK_INTERVAL);
|
||||||
|
|
||||||
// REMOVED: The duplicate checkVoiceChannels override that was here
|
const self = this;
|
||||||
// The checkVoiceChannels method is now properly defined inside PlayerManager.mjs
|
this.players.checkVoiceChannels = function (message) {
|
||||||
|
const userId = message?.author?.id ?? message?.message?.author?.id;
|
||||||
|
const guildId = message?.channel?.server_id ??
|
||||||
|
message?.channel?.serverId ??
|
||||||
|
message?.channel?.guild?.id ??
|
||||||
|
message?.message?.server_id ??
|
||||||
|
message?.message?.serverId ??
|
||||||
|
message?.message?.guildId;
|
||||||
|
if (!userId || !guildId) return null;
|
||||||
|
|
||||||
|
const seed = (channelId) => {
|
||||||
|
// Only seed if no entry exists — never overwrite fresh gateway voice state
|
||||||
|
// with potentially stale member-cache data.
|
||||||
|
if (!self.observedVoiceUsers.has(userId)) {
|
||||||
|
self.observedVoiceUsers.set(userId, { channelId, guildId });
|
||||||
|
}
|
||||||
|
return self.observedVoiceUsers.get(userId)?.channelId ?? channelId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const observed = self.observedVoiceUsers.get(userId);
|
||||||
|
if (observed && observed.guildId === guildId) return observed.channelId;
|
||||||
|
|
||||||
|
// vm.getVoiceChannelId() is an unverified @fluxerjs/voice method — optional-chained
|
||||||
|
// so it fails silently and falls through to the next strategy if absent.
|
||||||
|
try {
|
||||||
|
const vm = getVoiceManager(client);
|
||||||
|
const channelId = vm?.getVoiceChannelId?.(guildId, userId);
|
||||||
|
if (channelId) return seed(channelId);
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
// @fluxerjs/core member objects may not carry a .voice property.
|
||||||
|
// Optional-chained so it's a silent no-op if absent.
|
||||||
|
const memberVoice =
|
||||||
|
message?.member?.voice?.channelId ??
|
||||||
|
message?.message?.member?.voice?.channelId ??
|
||||||
|
null;
|
||||||
|
if (memberVoice) return seed(memberVoice);
|
||||||
|
|
||||||
|
// @fluxerjs/core may expose voice states differently (e.g. raw voice_states array
|
||||||
|
// on the guild object from the gateway payload, which is handled in GuildCreate).
|
||||||
|
// The dual snake_case/camelCase probe covers both shapes.
|
||||||
|
try {
|
||||||
|
const guild = client.guilds.cache.get(guildId);
|
||||||
|
// guild.voice_states = raw array from gateway (Fluxer-native)
|
||||||
|
// guild.voiceStates?.cache = VoiceStateManager (fallback)
|
||||||
|
const voiceStates = guild?.voice_states ?? guild?.voiceStates?.cache ?? guild?.voiceStates ?? null;
|
||||||
|
if (voiceStates) {
|
||||||
|
const entries = Array.isArray(voiceStates)
|
||||||
|
? voiceStates
|
||||||
|
: typeof voiceStates.values === "function"
|
||||||
|
? voiceStates.values()
|
||||||
|
: Object.values(voiceStates);
|
||||||
|
for (const state of entries) {
|
||||||
|
const sid = state.userId ?? state.user_id ?? state.id;
|
||||||
|
const sch = state.channelId ?? state.channel_id;
|
||||||
|
const sgid = state.guildId ?? state.guild_id ?? guildId;
|
||||||
|
if (sid === userId && sgid === guildId && sch) return seed(sch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||||
|
|
||||||
@@ -777,6 +944,7 @@ class Remix {
|
|||||||
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean))
|
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean))
|
||||||
: new Set([String(raw).replace(/\D/g, "")]);
|
: new Set([String(raw).replace(/\D/g, "")]);
|
||||||
|
|
||||||
|
// If mode is auto, block the leave command
|
||||||
if (channels.has(cleanId) && !force) {
|
if (channels.has(cleanId) && !force) {
|
||||||
if (mode === "auto") {
|
if (mode === "auto") {
|
||||||
if (message) {
|
if (message) {
|
||||||
@@ -789,6 +957,7 @@ class Remix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If mode is 'on' or it's forced, allow leaving & remove from 24/7 list
|
||||||
if (channels.has(cleanId)) {
|
if (channels.has(cleanId)) {
|
||||||
channels.delete(cleanId);
|
channels.delete(cleanId);
|
||||||
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
||||||
@@ -819,6 +988,9 @@ class Remix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getSharedServers(user) {
|
getSharedServers(user) {
|
||||||
|
// guild.members.cache.has() only works for cached members (requires privileged intents).
|
||||||
|
// Instead, use the settings guilds map — any guild the bot is in and has settings for
|
||||||
|
// is one we actually serve, which is a reliable proxy for "shared server".
|
||||||
const mutualGuilds = this.client.guilds.cache.filter(g =>
|
const mutualGuilds = this.client.guilds.cache.filter(g =>
|
||||||
this.settingsMgr.guilds.has(g.id)
|
this.settingsMgr.guilds.has(g.id)
|
||||||
);
|
);
|
||||||
@@ -871,6 +1043,8 @@ const saveAndExit = () => {
|
|||||||
if (current) tracksToSave.push(current);
|
if (current) tracksToSave.push(current);
|
||||||
tracksToSave.push(...queueData);
|
tracksToSave.push(...queueData);
|
||||||
|
|
||||||
|
// Save ALL active sessions unconditionally so the bot always rejoins
|
||||||
|
// the channel it was in before rebooting (queue or not, 24/7 or not)
|
||||||
state.push({
|
state.push({
|
||||||
guildId: player._guildId,
|
guildId: player._guildId,
|
||||||
channelId: channelId,
|
channelId: channelId,
|
||||||
@@ -882,6 +1056,8 @@ const saveAndExit = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (state.length > 0) {
|
if (state.length > 0) {
|
||||||
|
// Write to a temp file then rename atomically to prevent partial writes
|
||||||
|
// if the OS sends SIGKILL before writeFileSync finishes on large queue states.
|
||||||
const recoveryPath = "./storage/recovery.json";
|
const recoveryPath = "./storage/recovery.json";
|
||||||
const tmpPath = recoveryPath + ".tmp";
|
const tmpPath = recoveryPath + ".tmp";
|
||||||
fs.writeFileSync(tmpPath, JSON.stringify(state, null, 2));
|
fs.writeFileSync(tmpPath, JSON.stringify(state, null, 2));
|
||||||
|
|||||||
+36
-6
@@ -26,6 +26,34 @@ function mkEmbed(desc) {
|
|||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
|
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip NodeLink host, port, and password from a string so they are never
|
||||||
|
* shown to end-users in Discord messages.
|
||||||
|
* @param {string} msg
|
||||||
|
* @param {Object} nl - The player's _nl config object { host, port, password }
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function sanitizeError(msg, nl = {}) {
|
||||||
|
if (!msg) return msg;
|
||||||
|
let s = String(msg);
|
||||||
|
const host = nl.host;
|
||||||
|
const port = nl.port;
|
||||||
|
const password = nl.password;
|
||||||
|
if (host && host !== "localhost") {
|
||||||
|
const escapedHost = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]");
|
||||||
|
if (port) s = s.replace(new RegExp(`${escapedHost}:${port}`, "g"), "[internal]");
|
||||||
|
}
|
||||||
|
if (port) {
|
||||||
|
s = s.replace(new RegExp(`https?://localhost:${port}[^\\s"']*`, "gi"), "[internal]");
|
||||||
|
}
|
||||||
|
if (password && password !== "youshallnotpass") {
|
||||||
|
const escapedPw = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
s = s.replace(new RegExp(escapedPw, "g"), "[redacted]");
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
// Queue Class
|
// Queue Class
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -539,7 +567,7 @@ export default class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
if (res.statusCode !== 200 && res.statusCode !== 204) {
|
if (res.statusCode !== 200 && res.statusCode !== 204) {
|
||||||
res.resume();
|
res.resume();
|
||||||
return reject(new Error(`HTTP ${res.statusCode} at NodeLink Server`));
|
return reject(new Error(`HTTP ${res.statusCode} at ${target}`));
|
||||||
}
|
}
|
||||||
if (returnStream) return resolve(res);
|
if (returnStream) return resolve(res);
|
||||||
|
|
||||||
@@ -547,11 +575,11 @@ export default class Player extends EventEmitter {
|
|||||||
res.on("data", d => chunks.push(d));
|
res.on("data", d => chunks.push(d));
|
||||||
res.on("end", () => {
|
res.on("end", () => {
|
||||||
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
|
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
|
||||||
catch (e) { reject(new Error(`JSON parse error from NodeLink Server`)); }
|
catch (e) { reject(new Error(`JSON parse error from ${target}`)); }
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
req.on("error", () => reject(new Error("Request error to NodeLink Server")));
|
req.on("error", reject);
|
||||||
req.setTimeout(options.timeout || 30_000, () => {
|
req.setTimeout(options.timeout || 30_000, () => {
|
||||||
req.destroy();
|
req.destroy();
|
||||||
reject(new Error("Request timeout"));
|
reject(new Error("Request timeout"));
|
||||||
@@ -694,7 +722,9 @@ export default class Player extends EventEmitter {
|
|||||||
return this._streamViaRevoice(json.url);
|
return this._streamViaRevoice(json.url);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error("[Player] NodeLink resolve error:", err.message);
|
logger.error("[Player] NodeLink resolve error:", err.message);
|
||||||
throw err;
|
// Sanitize before re-throwing — this error eventually becomes a user-visible
|
||||||
|
// "Error streaming X — skipping..." message, so the NodeLink URL must not appear.
|
||||||
|
throw new Error(sanitizeError(err.message, this._nl));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1309,7 +1339,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
if (data.type === "error") {
|
if (data.type === "error") {
|
||||||
logger.worker("[Player] Worker returned error:", data.error);
|
logger.worker("[Player] Worker returned error:", data.error);
|
||||||
events.emit("message", data.error || "Failed to load track.");
|
events.emit("message", sanitizeError(data.error, this._nl) || "Failed to load track.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1329,7 +1359,7 @@ export default class Player extends EventEmitter {
|
|||||||
})
|
})
|
||||||
.catch((reason) => {
|
.catch((reason) => {
|
||||||
logger.error("[Player] Worker job failed:", reason);
|
logger.error("[Player] Worker job failed:", reason);
|
||||||
events.emit("message", reason?.message || "An error occurred while loading the track.");
|
events.emit("message", sanitizeError(reason?.message, this._nl) || "An error occurred while loading the track.");
|
||||||
});
|
});
|
||||||
return events;
|
return events;
|
||||||
}
|
}
|
||||||
|
|||||||
+55
-127
@@ -1,14 +1,18 @@
|
|||||||
/**
|
/**
|
||||||
* PlayerManager.mjs — Manages voice channel players across servers
|
* PlayerManager.mjs — Manages voice channel players across servers
|
||||||
|
*
|
||||||
|
* Updated for moonlink.js: passes the MoonlinkManager instance into every
|
||||||
|
* new Player so it can resolve tracks and retrieve session IDs.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import Player from "./Player.mjs";
|
import Player from "./Player.mjs";
|
||||||
import { CommandHandler } from "./CommandHandler.mjs";
|
import { CommandHandler } from "./CommandHandler.mjs";
|
||||||
|
import { Message } from "./MessageHandler.mjs";
|
||||||
import { SettingsManager } from "./Settings.mjs";
|
import { SettingsManager } from "./Settings.mjs";
|
||||||
|
import { Utils } from "./Utils.mjs";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
import { getGlobalColor } from "./MessageHandler.mjs";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
|
||||||
|
|
||||||
/** Helper — build a plain embed payload from a description string */
|
/** Helper — build a plain embed payload from a description string */
|
||||||
function mkEmbed(desc) {
|
function mkEmbed(desc) {
|
||||||
@@ -31,146 +35,57 @@ export class PlayerManager {
|
|||||||
/** @type {Object} */
|
/** @type {Object} */
|
||||||
playerConfig;
|
playerConfig;
|
||||||
|
|
||||||
/** @type {Map<string, Object>} */
|
|
||||||
observedVoiceUsers = null;
|
|
||||||
|
|
||||||
/** @type {import('@fluxerjs/core').Client} */
|
|
||||||
client = null;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {SettingsManager} settings
|
* @param {SettingsManager} settings
|
||||||
* @param {CommandHandler} commands
|
* @param {CommandHandler} commands
|
||||||
* @param {Object} config
|
* @param {Object} config
|
||||||
|
* @param {Object} config.config - Parsed config.json
|
||||||
|
* @param {Object} config.player - Config data passed to new Player instances
|
||||||
*/
|
*/
|
||||||
constructor(settings, commands, config) {
|
constructor(settings, commands, config) {
|
||||||
this.commands = commands;
|
this.commands = commands;
|
||||||
this.settings = settings;
|
this.settings = settings;
|
||||||
this.config = config.config;
|
this.config = config.config;
|
||||||
this.playerConfig = config.player;
|
this.playerConfig = config.player;
|
||||||
// Fix: Ensure we get the client from commands or config
|
|
||||||
this.client = commands.client || config.player?.client || config.config?.client;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Voice Channel Detection
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attempt to detect the voice channel a user is currently in.
|
* Attempt to detect the voice channel a user is currently in.
|
||||||
* Now async to support API fallback when cache is empty after reboot.
|
|
||||||
* @param {Message} message
|
* @param {Message} message
|
||||||
* @returns {Promise<string|null>} Voice channel ID or null
|
* @returns {string|null} Voice channel ID or null
|
||||||
*/
|
*/
|
||||||
async checkVoiceChannels(message) {
|
checkVoiceChannels(message) {
|
||||||
if (!message) return null;
|
if (!message) return null;
|
||||||
|
|
||||||
const userId = message.author?.id ?? message.message?.author?.id;
|
const userId = message.author?.id;
|
||||||
const guildId = message.channel?.server_id ??
|
const serverId = message.channel?.server_id ??
|
||||||
message.channel?.serverId ??
|
message.channel?.serverId ??
|
||||||
message.channel?.guild?.id ??
|
|
||||||
message.message?.server_id ??
|
message.message?.server_id ??
|
||||||
message.message?.serverId ??
|
message.message?.serverId;
|
||||||
message.message?.guildId;
|
|
||||||
|
if (!userId) return null;
|
||||||
|
|
||||||
|
// Fallback: find any existing player in this server
|
||||||
|
if (serverId) {
|
||||||
|
for (const [channelId] of this.playerMap) {
|
||||||
|
const channel = this.commands.client?.channels?.get(channelId) ??
|
||||||
|
this.commands.client?.channels?.cache?.get(channelId);
|
||||||
|
if (channel?.guildId === serverId || channel?.server_id === serverId || channel?.serverId === serverId) {
|
||||||
|
return channelId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!userId || !guildId) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Missing userId or guildId`);
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Checking for user ${userId} in guild ${guildId}`);
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Player Retrieval
|
||||||
// Helper to seed observedVoiceUsers cache
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
const seed = (channelId) => {
|
|
||||||
if (!this.observedVoiceUsers) return channelId;
|
|
||||||
if (!this.observedVoiceUsers.has(userId)) {
|
|
||||||
this.observedVoiceUsers.set(userId, { channelId, guildId });
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Seeded cache: ${userId} -> ${channelId}`);
|
|
||||||
}
|
|
||||||
return this.observedVoiceUsers.get(userId)?.channelId ?? channelId;
|
|
||||||
};
|
|
||||||
|
|
||||||
// 1. Check observedVoiceUsers cache first (populated by GuildCreate)
|
|
||||||
if (this.observedVoiceUsers) {
|
|
||||||
const observed = this.observedVoiceUsers.get(userId);
|
|
||||||
if (observed && observed.guildId === guildId) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Found in cache: ${observed.channelId}`);
|
|
||||||
return observed.channelId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Try VoiceManager
|
|
||||||
try {
|
|
||||||
const vm = getVoiceManager(this.client);
|
|
||||||
const channelId = vm?.getVoiceChannelId?.(guildId, userId);
|
|
||||||
if (channelId) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Found via VoiceManager: ${channelId}`);
|
|
||||||
return seed(channelId);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] VoiceManager failed: ${e.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Try message member voice (if available)
|
|
||||||
const memberVoice =
|
|
||||||
message?.member?.voice?.channelId ??
|
|
||||||
message?.member?.voice?.channel?.id ??
|
|
||||||
message?.message?.member?.voice?.channelId ??
|
|
||||||
null;
|
|
||||||
if (memberVoice) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Found via message.member.voice: ${memberVoice}`);
|
|
||||||
return seed(memberVoice);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Check guild voice states cache
|
|
||||||
try {
|
|
||||||
const guild = this.client?.guilds?.cache?.get(guildId);
|
|
||||||
if (!guild) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Guild ${guildId} not in cache`);
|
|
||||||
} else {
|
|
||||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates?.cache ?? guild?.voiceStates ?? null;
|
|
||||||
if (voiceStates) {
|
|
||||||
const entries = Array.isArray(voiceStates)
|
|
||||||
? voiceStates
|
|
||||||
: typeof voiceStates.values === "function"
|
|
||||||
? [...voiceStates.values()]
|
|
||||||
: Object.values(voiceStates);
|
|
||||||
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Checking ${entries.length} voice states in cache`);
|
|
||||||
|
|
||||||
for (const state of entries) {
|
|
||||||
const sid = state.userId ?? state.user_id ?? state.id;
|
|
||||||
const sch = state.channelId ?? state.channel_id;
|
|
||||||
const sgid = state.guildId ?? state.guild_id ?? guildId;
|
|
||||||
if (sid === userId && sgid === guildId && sch) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Found in guild cache: ${sch}`);
|
|
||||||
return seed(sch);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Guild cache check failed: ${e.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. CRITICAL FIX: Fetch fresh member data from API when cache misses
|
|
||||||
try {
|
|
||||||
const guild = this.client?.guilds?.cache?.get(guildId);
|
|
||||||
if (guild?.members?.fetch) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Fetching member ${userId} from API...`);
|
|
||||||
const member = await guild.members.fetch(userId);
|
|
||||||
const voiceChannelId = member?.voice?.channelId ?? member?.voice?.channel?.id ?? null;
|
|
||||||
if (voiceChannelId) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] API returned voice channel: ${voiceChannelId}`);
|
|
||||||
return seed(voiceChannelId);
|
|
||||||
} else {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] API returned no voice channel for user`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Cannot fetch members - no fetch method`);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
logger.voiceState(`[checkVoiceChannels] API fetch failed: ${err.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.voiceState(`[checkVoiceChannels] Could not find voice channel for ${userId}`);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get or create a player for the user's voice channel.
|
* Get or create a player for the user's voice channel.
|
||||||
@@ -186,8 +101,7 @@ export class PlayerManager {
|
|||||||
message.message?.server_id ??
|
message.message?.server_id ??
|
||||||
message.message?.serverId;
|
message.message?.serverId;
|
||||||
|
|
||||||
// Added await here
|
const userChannelId = this.checkVoiceChannels(message);
|
||||||
const userChannelId = await this.checkVoiceChannels(message);
|
|
||||||
|
|
||||||
if (userChannelId) {
|
if (userChannelId) {
|
||||||
const player = this.playerMap.get(userChannelId);
|
const player = this.playerMap.get(userChannelId);
|
||||||
@@ -209,9 +123,14 @@ export class PlayerManager {
|
|||||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||||
|
|
||||||
if (!userChannelId) {
|
if (!userChannelId) {
|
||||||
if (promptJoin) {
|
// verifyUser=false: allow controlling the bot without being in voice
|
||||||
message.replyEmbed(mkEmbed(`⚠️ Please join a voice channel to use this command.`));
|
// (e.g. volume, clear, remove — admin-style controls).
|
||||||
|
if (!verifyUser) {
|
||||||
|
const first = serverPlayers[0];
|
||||||
|
first[1].textChannel = message.channel;
|
||||||
|
return first[1];
|
||||||
}
|
}
|
||||||
|
message.replyEmbed(mkEmbed(`⚠️ You need to join a voice channel to use this command.`));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,19 +152,16 @@ export class PlayerManager {
|
|||||||
return this.settings.getServer(serverId)?.get("prefix") ?? "%";
|
return this.settings.getServer(serverId)?.get("prefix") ?? "%";
|
||||||
} catch (_) { return "%"; }
|
} catch (_) { return "%"; }
|
||||||
})();
|
})();
|
||||||
if (promptJoin) {
|
|
||||||
message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel or use \`${prefix}play\` to start music in your channel.`));
|
message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel or use \`${prefix}play\` to start music in your channel.`));
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!userChannelId) {
|
if (!userChannelId) {
|
||||||
if (shouldJoin) {
|
if (shouldJoin) {
|
||||||
|
// Auto-detect failed — fall back to interactive channel selection prompt
|
||||||
return this.promptVC(message);
|
return this.promptVC(message);
|
||||||
}
|
}
|
||||||
if (promptJoin) {
|
|
||||||
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
|
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,13 +174,17 @@ export class PlayerManager {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Channel Selection Prompt
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prompt the user to select a voice channel.
|
* Prompt the user to select a voice channel.
|
||||||
* @param {Message} msg
|
* @param {Message} msg
|
||||||
* @returns {Promise<Player|false>}
|
* @returns {Promise<string|false>}
|
||||||
*/
|
*/
|
||||||
async promptVC(msg) {
|
async promptVC(msg) {
|
||||||
const autoDetected = await this.checkVoiceChannels(msg);
|
const autoDetected = this.checkVoiceChannels(msg);
|
||||||
if (autoDetected) {
|
if (autoDetected) {
|
||||||
return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p)));
|
return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p)));
|
||||||
}
|
}
|
||||||
@@ -345,6 +265,10 @@ export class PlayerManager {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Leave
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Make the player leave its current voice channel.
|
* Make the player leave its current voice channel.
|
||||||
* @param {Message} msg
|
* @param {Message} msg
|
||||||
@@ -372,6 +296,10 @@ export class PlayerManager {
|
|||||||
player.destroy();
|
player.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Player Initialisation
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create and register a new Player for the given voice channel.
|
* Create and register a new Player for the given voice channel.
|
||||||
* @param {Message} message
|
* @param {Message} message
|
||||||
|
|||||||
+97
-7
@@ -1,5 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
|
*
|
||||||
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { workerData, parentPort } from "worker_threads";
|
import { workerData, parentPort } from "worker_threads";
|
||||||
@@ -10,13 +12,54 @@ import { Utils } from "./Utils.mjs";
|
|||||||
import { PROVIDERS } from "./constants/providers.mjs";
|
import { PROVIDERS } from "./constants/providers.mjs";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// NodeLink Configuration (forwarded from Player via workerData)
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
const nl = workerData?.data?.nodelink ?? {};
|
const nl = workerData?.data?.nodelink ?? {};
|
||||||
const NL_HOST = nl.host ?? "localhost";
|
const NL_HOST = nl.host ?? "localhost";
|
||||||
const NL_PORT = nl.port ?? 3000;
|
const NL_PORT = nl.port ?? 3000;
|
||||||
const NL_PASSWORD = nl.password ?? "youshallnotpass";
|
const NL_PASSWORD = nl.password ?? "youshallnotpass";
|
||||||
const NL_SESSION_ID = nl.sessionId ?? null;
|
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
|
||||||
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
||||||
|
|
||||||
|
// ─── Error sanitizer ──────────────────────────────────────────────────────────
|
||||||
|
// Strips the NodeLink host, port, and password from any string so they are
|
||||||
|
// never shown to end-users in Discord messages. Called on every user-visible
|
||||||
|
// error string before it is emitted or returned.
|
||||||
|
function sanitizeError(msg) {
|
||||||
|
if (!msg) return msg;
|
||||||
|
let s = String(msg);
|
||||||
|
// Remove full URLs containing the NodeLink host (http://host:port/...)
|
||||||
|
if (NL_HOST && NL_HOST !== "localhost") {
|
||||||
|
// Escape special regex chars in the host string
|
||||||
|
const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]");
|
||||||
|
}
|
||||||
|
// Remove localhost:port combos
|
||||||
|
s = s.replace(new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), "[internal]");
|
||||||
|
// Remove bare host:port if it somehow appears without a protocol
|
||||||
|
if (NL_HOST && NL_HOST !== "localhost") {
|
||||||
|
const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
s = s.replace(new RegExp(`${escapedHost}:${NL_PORT}`, "g"), "[internal]");
|
||||||
|
}
|
||||||
|
// Remove the password just in case it ever leaks into an error message
|
||||||
|
if (NL_PASSWORD && NL_PASSWORD !== "youshallnotpass") {
|
||||||
|
const escapedPw = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
s = s.replace(new RegExp(escapedPw, "g"), "[redacted]");
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// HTTP Helper
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make a GET request to NodeLink and return the parsed JSON body.
|
||||||
|
* @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…")
|
||||||
|
* @returns {Promise<object>}
|
||||||
|
*/
|
||||||
function nlGet(path) {
|
function nlGet(path) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const isHttps = NL_PORT === 443;
|
const isHttps = NL_PORT === 443;
|
||||||
@@ -45,7 +88,7 @@ function nlGet(path) {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
req.on("error", () => reject(new Error("NodeLink connection failed.")));
|
req.on("error", reject);
|
||||||
req.setTimeout(30_000, () => {
|
req.setTimeout(30_000, () => {
|
||||||
req.destroy();
|
req.destroy();
|
||||||
reject(new Error("NodeLink request timeout"));
|
reject(new Error("NodeLink request timeout"));
|
||||||
@@ -53,10 +96,24 @@ function nlGet(path) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call NodeLink /v4/loadtracks.
|
||||||
|
* @param {string} identifier
|
||||||
|
* @returns {Promise<object>}
|
||||||
|
*/
|
||||||
async function loadTracks(identifier) {
|
async function loadTracks(identifier) {
|
||||||
return nlGet(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
|
return nlGet(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// Track Conversion
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a NodeLink track object to the internal video format.
|
||||||
|
* @param {object} track
|
||||||
|
* @returns {object|null}
|
||||||
|
*/
|
||||||
function trackToVideo(track) {
|
function trackToVideo(track) {
|
||||||
if (!track || typeof track !== "object") return null;
|
if (!track || typeof track !== "object") return null;
|
||||||
|
|
||||||
@@ -68,7 +125,7 @@ function trackToVideo(track) {
|
|||||||
encoded: track.encoded ?? "",
|
encoded: track.encoded ?? "",
|
||||||
sourceName: info.sourceName ?? "unknown",
|
sourceName: info.sourceName ?? "unknown",
|
||||||
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
||||||
url: info.uri ?? info.identifier ?? "",
|
url: info.uri ?? `https://www.youtube.com/watch?v=${info.identifier}`,
|
||||||
thumbnail: info.artworkUrl ?? null,
|
thumbnail: info.artworkUrl ?? null,
|
||||||
spotifyUrl: null,
|
spotifyUrl: null,
|
||||||
duration: {
|
duration: {
|
||||||
@@ -83,8 +140,16 @@ function trackToVideo(track) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// Provider Configuration (imported from constants/providers.mjs)
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
|
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// YTUtils Class
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class YTUtils extends EventEmitter {
|
class YTUtils extends EventEmitter {
|
||||||
constructor() { super(); }
|
constructor() { super(); }
|
||||||
|
|
||||||
@@ -102,21 +167,31 @@ class YTUtils extends EventEmitter {
|
|||||||
return `${prefix}:track:${query}`;
|
return `${prefix}:track:${query}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean YouTube Radio/Mix URLs to extract just the video
|
||||||
|
* YouTube Radio URLs (list=RD...) often cause metadata mismatches
|
||||||
|
*/
|
||||||
_cleanYouTubeUrl(url) {
|
_cleanYouTubeUrl(url) {
|
||||||
try {
|
try {
|
||||||
const urlObj = new URL(url);
|
const urlObj = new URL(url);
|
||||||
|
|
||||||
|
// Check if it's a YouTube Radio/Mix URL
|
||||||
const list = urlObj.searchParams.get("list");
|
const list = urlObj.searchParams.get("list");
|
||||||
if (list && list.startsWith("RD")) {
|
if (list && list.startsWith("RD")) {
|
||||||
|
// Extract just the video ID and create clean URL
|
||||||
const videoId = urlObj.searchParams.get("v");
|
const videoId = urlObj.searchParams.get("v");
|
||||||
if (videoId) {
|
if (videoId) {
|
||||||
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
|
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
|
||||||
return `https://www.youtube.com/watch?v=${videoId}`;
|
return `https://www.youtube.com/watch?v=${videoId}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove start_radio parameter if present
|
||||||
if (urlObj.searchParams.has("start_radio")) {
|
if (urlObj.searchParams.has("start_radio")) {
|
||||||
urlObj.searchParams.delete("start_radio");
|
urlObj.searchParams.delete("start_radio");
|
||||||
return urlObj.toString();
|
return urlObj.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
return url;
|
return url;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return url;
|
return url;
|
||||||
@@ -148,9 +223,11 @@ class YTUtils extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getVideoData(query, provider = "ytm") {
|
async getVideoData(query, provider = "ytm") {
|
||||||
|
// Handle URLs (including YouTube Radio/Mix)
|
||||||
if (this.isValidUrl(query)) {
|
if (this.isValidUrl(query)) {
|
||||||
this.emit("message", "Loading...");
|
this.emit("message", "Loading...");
|
||||||
|
|
||||||
|
// Clean YouTube Radio URLs to prevent metadata mismatches
|
||||||
const cleanedUrl = this._cleanYouTubeUrl(query);
|
const cleanedUrl = this._cleanYouTubeUrl(query);
|
||||||
if (cleanedUrl !== query) {
|
if (cleanedUrl !== query) {
|
||||||
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
|
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
|
||||||
@@ -160,10 +237,11 @@ class YTUtils extends EventEmitter {
|
|||||||
try {
|
try {
|
||||||
data = await loadTracks(cleanedUrl);
|
data = await loadTracks(cleanedUrl);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.emit("message", `**Failed to load: ${e.message}**`);
|
this.emit("message", `**Failed to load that track.**`);
|
||||||
return { type: "error", data: null, error: e.message };
|
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle playlist results
|
||||||
if (data.loadType === "playlist") {
|
if (data.loadType === "playlist") {
|
||||||
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
||||||
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
|
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
|
||||||
@@ -171,32 +249,37 @@ class YTUtils extends EventEmitter {
|
|||||||
return { type: "list", data: tracks };
|
return { type: "list", data: tracks };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle single track
|
||||||
if (data.loadType === "track") {
|
if (data.loadType === "track") {
|
||||||
const video = trackToVideo(data.data);
|
const video = trackToVideo(data.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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle search results (take first)
|
||||||
if (data.loadType === "search" && data.data?.length) {
|
if (data.loadType === "search" && data.data?.length) {
|
||||||
const video = trackToVideo(data.data[0]);
|
const video = trackToVideo(data.data[0]);
|
||||||
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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// No recognizable loadType
|
||||||
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
|
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
|
||||||
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
|
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle search queries (non-URLs)
|
||||||
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
|
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
|
||||||
|
|
||||||
let data;
|
let data;
|
||||||
try {
|
try {
|
||||||
data = await loadTracks(this._buildIdentifier(provider, query));
|
data = await loadTracks(this._buildIdentifier(provider, query));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.emit("message", `**Search failed: ${e.message}**`);
|
this.emit("message", `**Search failed. Please try again.**`);
|
||||||
return { type: "error", data: null, error: e.message };
|
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle search results
|
||||||
if (data.loadType === "search" && data.data?.length) {
|
if (data.loadType === "search" && data.data?.length) {
|
||||||
const validTrack = data.data.find(track => {
|
const validTrack = data.data.find(track => {
|
||||||
const info = track.info ?? {};
|
const info = track.info ?? {};
|
||||||
@@ -212,6 +295,7 @@ class YTUtils extends EventEmitter {
|
|||||||
return { type: "video", data: video };
|
return { type: "video", data: video };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle playlist from search
|
||||||
if (data.loadType === "playlist") {
|
if (data.loadType === "playlist") {
|
||||||
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
||||||
if (tracks.length > 0) {
|
if (tracks.length > 0) {
|
||||||
@@ -220,17 +304,23 @@ class YTUtils extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Single track from search
|
||||||
if (data.loadType === "track") {
|
if (data.loadType === "track") {
|
||||||
const video = trackToVideo(data.data);
|
const video = trackToVideo(data.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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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" };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// Worker Entry Point
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
const jobId = workerData?.jobId;
|
const jobId = workerData?.jobId;
|
||||||
const data = workerData?.data;
|
const data = workerData?.data;
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user