mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
Compare commits
7
Commits
c1dbda2068
...
618ecb1a0b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
618ecb1a0b | ||
|
|
a780ec22c8 | ||
|
|
70f124294d | ||
|
|
5714f7b2c8 | ||
|
|
a467611e37 | ||
|
|
ec441ea20a | ||
|
|
7bd80e62f7 |
No files matched your search
+6
-4
@@ -39,13 +39,15 @@ export async function run(msg, data) {
|
|||||||
const p = await this.getPlayer(msg, false, false, false);
|
const p = await this.getPlayer(msg, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
const fromVal = data?.get?.("from")?.value;
|
const rawFrom = data?.get?.("from")?.value;
|
||||||
const toVal = data?.get?.("to")?.value;
|
const rawTo = data?.get?.("to")?.value;
|
||||||
|
const fromVal = (typeof rawFrom === "number" && Number.isFinite(rawFrom)) ? rawFrom : null;
|
||||||
|
const toVal = (typeof rawTo === "number" && Number.isFinite(rawTo)) ? rawTo : null;
|
||||||
|
|
||||||
if (fromVal != null && fromVal !== undefined) {
|
if (fromVal !== null) {
|
||||||
if (fromVal < 1) return msg.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
|
if (fromVal < 1) return msg.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
|
||||||
const startIdx = Math.floor(fromVal) - 1;
|
const startIdx = Math.floor(fromVal) - 1;
|
||||||
const endIdx = (toVal != null && toVal !== undefined && toVal >= 1) ? Math.floor(toVal) - 1 : startIdx;
|
const endIdx = (toVal !== null && toVal >= 1) ? Math.floor(toVal) - 1 : startIdx;
|
||||||
const res = p.removeRange(startIdx, endIdx);
|
const res = p.removeRange(startIdx, endIdx);
|
||||||
return msg.replyEmbed(res).catch(() => {});
|
return msg.replyEmbed(res).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-5
@@ -253,11 +253,13 @@ export async function run(message, data) {
|
|||||||
const parsed = parseLastFmUrl(lfUrl);
|
const parsed = parseLastFmUrl(lfUrl);
|
||||||
|
|
||||||
if (parsed && parsed.track) {
|
if (parsed && parsed.track) {
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
const lastfmTrackMeta = {
|
const lastfmTrackMeta = {
|
||||||
artist: parsed.artist,
|
artist: parsed.artist,
|
||||||
name: parsed.track,
|
name: parsed.track,
|
||||||
source: "lastfm",
|
source: "lastfm",
|
||||||
url: parsed.url,
|
url: parsed.url,
|
||||||
|
requester,
|
||||||
};
|
};
|
||||||
|
|
||||||
const p = await this.getPlayer(message, true, true, true);
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
@@ -280,6 +282,7 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (parsed && !parsed.track) {
|
if (parsed && !parsed.track) {
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
const p = await this.getPlayer(message, true, true, true);
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
@@ -290,7 +293,7 @@ export async function run(message, data) {
|
|||||||
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||||
|
|
||||||
const playQuery = parsed.artist;
|
const playQuery = parsed.artist;
|
||||||
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider);
|
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, { requester });
|
||||||
messages.on("message", d => {
|
messages.on("message", d => {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
||||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
||||||
@@ -374,11 +377,13 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
const lastfmTrackMeta = {
|
const lastfmTrackMeta = {
|
||||||
artist: searchResult.artist,
|
artist: searchResult.artist,
|
||||||
name: searchResult.name,
|
name: searchResult.name,
|
||||||
source: "lastfm",
|
source: "lastfm",
|
||||||
url: searchResult.url ?? "",
|
url: searchResult.url ?? "",
|
||||||
|
requester,
|
||||||
};
|
};
|
||||||
|
|
||||||
const playProvider = resolveProvider && resolveProvider !== "lf" && resolveProvider !== "lastfm"
|
const playProvider = resolveProvider && resolveProvider !== "lf" && resolveProvider !== "lastfm"
|
||||||
@@ -400,14 +405,18 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
const resolvedProvider =
|
const resolvedProvider =
|
||||||
provider === "lastfm" || provider === "lf"
|
provider === "lastfm" || provider === "lf"
|
||||||
? (flagProvider && flagProvider !== "lastfm" && flagProvider !== "lf" ? flagProvider : "yt")
|
? (flagProvider && flagProvider !== "lastfm" && flagProvider !== "lf" ? flagProvider : "yt")
|
||||||
: provider;
|
: provider;
|
||||||
const lastfmTrackMeta =
|
const parsedLastfmTrackMeta =
|
||||||
provider === "lastfm" || provider === "lf"
|
provider === "lastfm" || provider === "lf"
|
||||||
? parseLastFmTrackQuery(query)
|
? parseLastFmTrackQuery(query)
|
||||||
: null;
|
: null;
|
||||||
|
const lastfmTrackMeta = parsedLastfmTrackMeta
|
||||||
|
? { ...parsedLastfmTrackMeta, requester }
|
||||||
|
: { requester };
|
||||||
|
|
||||||
const p = await this.getPlayer(message, true, true, true);
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -424,11 +433,11 @@ export async function run(message, data) {
|
|||||||
logger.warn("[Play] Error:", err?.message);
|
logger.warn("[Play] Error:", err?.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const playQuery = lastfmTrackMeta
|
const playQuery = parsedLastfmTrackMeta
|
||||||
? `${lastfmTrackMeta.name} ${lastfmTrackMeta.artist}`.trim()
|
? `${parsedLastfmTrackMeta.name} ${parsedLastfmTrackMeta.artist}`.trim()
|
||||||
: query;
|
: query;
|
||||||
|
|
||||||
const messages = p.play(playQuery, false, resolvedProvider);
|
const messages = p.play(playQuery, false, resolvedProvider, lastfmTrackMeta);
|
||||||
messages.on("message", d => {
|
messages.on("message", d => {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
||||||
if (statusMsg) {
|
if (statusMsg) {
|
||||||
|
|||||||
@@ -67,7 +67,8 @@ export async function run(message, data) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const messages = p.playFirst(query, provider);
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
|
const messages = p.playFirst(query, provider, { requester });
|
||||||
messages.on("message", d => {
|
messages.on("message", d => {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
||||||
if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||||
|
|||||||
@@ -70,7 +70,10 @@ export class CommandHandler extends EventEmitter {
|
|||||||
this.helpHandler = new HelpHandler(this);
|
this.helpHandler = new HelpHandler(this);
|
||||||
this.helpCommand = "help";
|
this.helpCommand = "help";
|
||||||
this.replyHandler = (message, msg) => {
|
this.replyHandler = (message, msg) => {
|
||||||
msg.reply(this.format(message, msg.channel.channel.guildId));
|
const guildId = msg?.channel?.guildId ?? msg?.channel?.channel?.guildId ?? msg?.guildId ?? msg?.message?.guildId ?? null;
|
||||||
|
Promise.resolve(msg.reply(this.format(message, guildId))).catch(err => {
|
||||||
|
logger.warn("[CommandHandler] Failed to reply:", err?.message);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
this.messages.onMessage(this.messageHandler.bind(this));
|
this.messages.onMessage(this.messageHandler.bind(this));
|
||||||
}
|
}
|
||||||
@@ -269,7 +272,10 @@ export class CommandHandler extends EventEmitter {
|
|||||||
if (cmd.requirements.length > 0 && !external) {
|
if (cmd.requirements.length > 0 && !external) {
|
||||||
if (!this.assertRequirements(cmd, msg)) return;
|
if (!this.assertRequirements(cmd, msg)) return;
|
||||||
}
|
}
|
||||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
if (previous === false) {
|
||||||
|
const prevGuildId = msg.channel?.guildId ?? msg.channel?.channel?.guildId ?? msg.message?.guildId ?? null;
|
||||||
|
previous = this.format("$prefix" + cmd.name, prevGuildId);
|
||||||
|
}
|
||||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||||
|
|
||||||
if (cmd.subcommands.length !== 0) {
|
if (cmd.subcommands.length !== 0) {
|
||||||
@@ -406,7 +412,10 @@ export class CommandHandler extends EventEmitter {
|
|||||||
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
||||||
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||||
}
|
}
|
||||||
if (o.empty(value)) value = o.defaultValue;
|
if (o.empty(value)) {
|
||||||
|
if (o.defaultValue === undefined) continue;
|
||||||
|
value = o.defaultValue;
|
||||||
|
}
|
||||||
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
||||||
usedOptions.push(o.uid);
|
usedOptions.push(o.uid);
|
||||||
previous += " " + value;
|
previous += " " + value;
|
||||||
|
|||||||
@@ -44,23 +44,31 @@ export class CommandLoader {
|
|||||||
this.commands.on("run", (data) => {
|
this.commands.on("run", (data) => {
|
||||||
if (!this.runnables.has(data.command.uid)) return;
|
if (!this.runnables.has(data.command.uid)) return;
|
||||||
const runFc = this.runnables.get(data.command.uid);
|
const runFc = this.runnables.get(data.command.uid);
|
||||||
|
const isPermError = (err) => {
|
||||||
|
return err?.code === "MISSING_PERMISSIONS" ||
|
||||||
|
err?.code === "COMMUNICATION_DISABLED" ||
|
||||||
|
err?.statusCode === 403;
|
||||||
|
};
|
||||||
const sendErrorReply = (id) => {
|
const sendErrorReply = (id) => {
|
||||||
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
|
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
|
||||||
.catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message));
|
.catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message));
|
||||||
};
|
};
|
||||||
try {
|
const handleCmdError = (e) => {
|
||||||
const result = runFc.call(this.context, data.message, data);
|
if (isPermError(e)) {
|
||||||
if (result && typeof result.catch === "function") {
|
logger.warn(`[CommandHandler] Missing permissions in channel ${data.message?.channelId ?? data.message?.channel?.id}: ${e.code ?? e.message}`);
|
||||||
result.catch(e => {
|
return;
|
||||||
const id = Utils.uid();
|
|
||||||
logger.error("Error running command; error id #" + id, e);
|
|
||||||
sendErrorReply(id);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
|
||||||
const id = Utils.uid();
|
const id = Utils.uid();
|
||||||
logger.error("Error running command; error id #" + id, e);
|
logger.error("Error running command; error id #" + id, e);
|
||||||
sendErrorReply(id);
|
sendErrorReply(id);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const result = runFc.call(this.context, data.message, data);
|
||||||
|
if (result && typeof result.catch === "function") {
|
||||||
|
result.catch(handleCmdError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleCmdError(e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -211,8 +211,11 @@ export class Option {
|
|||||||
case "text":
|
case "text":
|
||||||
case "string":
|
case "string":
|
||||||
return i;
|
return i;
|
||||||
case "number":
|
case "number": {
|
||||||
return parseFloat(i);
|
if (i === undefined || i === null || i === "") return null;
|
||||||
|
const parsed = parseFloat(i);
|
||||||
|
return Number.isFinite(parsed) ? parsed : null;
|
||||||
|
}
|
||||||
case "boolean":
|
case "boolean":
|
||||||
return i?.toLowerCase() === "true" || i === "1";
|
return i?.toLowerCase() === "true" || i === "1";
|
||||||
case "choice":
|
case "choice":
|
||||||
|
|||||||
+5
-3
@@ -141,6 +141,8 @@ class Remix {
|
|||||||
const sharedPool = getSharedMysqlPool(config.mysql);
|
const sharedPool = getSharedMysqlPool(config.mysql);
|
||||||
const sharedPromisePool = getSharedPromisePool(config.mysql);
|
const sharedPromisePool = getSharedPromisePool(config.mysql);
|
||||||
|
|
||||||
|
TrackStats.setPool(sharedPromisePool);
|
||||||
|
|
||||||
this.dashboard = new Dashboard(this, {
|
this.dashboard = new Dashboard(this, {
|
||||||
enabled: config.dashboard?.enabled,
|
enabled: config.dashboard?.enabled,
|
||||||
redis: config.dashboard?.redis,
|
redis: config.dashboard?.redis,
|
||||||
@@ -233,10 +235,10 @@ class Remix {
|
|||||||
),
|
),
|
||||||
false,
|
false,
|
||||||
{
|
{
|
||||||
icon_url: msg.channel.channel.guild?.icon
|
icon_url: (msg.channel?.channel?.guild?.icon || msg.server?.icon)
|
||||||
? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp`
|
? `https://cdn.fluxer.app/icons/${msg.channel?.channel?.guild?.id ?? msg.server?.id}/${msg.channel?.channel?.guild?.icon ?? msg.server?.icon}.webp`
|
||||||
: null,
|
: null,
|
||||||
title: msg.channel.channel.guild?.name ?? null,
|
title: msg.channel?.channel?.guild?.name ?? msg.server?.name ?? null,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -97,7 +97,12 @@ const PlayerEventsMixin = {
|
|||||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||||
|
|
||||||
if (!player._radioReconnects) {
|
if (!player._radioReconnects) {
|
||||||
TrackStats.increment();
|
let userId = song?.requester ?? null;
|
||||||
|
if (!userId) {
|
||||||
|
const humans = player._getHumanParticipantIdentities?.() ?? [];
|
||||||
|
if (humans.length === 1) userId = humans[0];
|
||||||
|
}
|
||||||
|
TrackStats.increment(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this._lastfm?.enabled && song) {
|
if (this._lastfm?.enabled && song) {
|
||||||
|
|||||||
@@ -557,7 +557,7 @@ const PlayerLifecycleMixin = {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const statusMsg = await message.reply(this._t(message, "responses.join.joining"));
|
const statusMsg = await message.reply(this._t(message, "responses.join.joining")).catch(() => null);
|
||||||
try {
|
try {
|
||||||
await player.join(cid);
|
await player.join(cid);
|
||||||
|
|
||||||
@@ -565,7 +565,7 @@ const PlayerLifecycleMixin = {
|
|||||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
this._pendingJoins.delete(cleanChannelId);
|
this._pendingJoins.delete(cleanChannelId);
|
||||||
|
|
||||||
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
|
await statusMsg?.edit?.(this._t(message, "responses.join.joined", { channel: cid })).catch(() => {});
|
||||||
|
|
||||||
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
this._restorePlayerVolume(player, guildId);
|
this._restorePlayerVolume(player, guildId);
|
||||||
@@ -584,7 +584,7 @@ const PlayerLifecycleMixin = {
|
|||||||
|
|
||||||
this.playerMap.set(cleanChannelId, player);
|
this.playerMap.set(cleanChannelId, player);
|
||||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
|
await statusMsg?.edit?.(this._t(message, "responses.join.joined", { channel: cid })).catch(() => {});
|
||||||
|
|
||||||
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
this._restorePlayerVolume(player, retryGuildId);
|
this._restorePlayerVolume(player, retryGuildId);
|
||||||
@@ -602,7 +602,7 @@ const PlayerLifecycleMixin = {
|
|||||||
} else {
|
} else {
|
||||||
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
|
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
|
||||||
}
|
}
|
||||||
await statusMsg.edit(errorMsg).catch(() => {});
|
await statusMsg?.edit?.(errorMsg).catch(() => {});
|
||||||
this.playerMap.delete(cleanChannelId);
|
this.playerMap.delete(cleanChannelId);
|
||||||
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
player.destroy();
|
player.destroy();
|
||||||
|
|||||||
@@ -151,7 +151,7 @@ export class PlayerManager {
|
|||||||
* @returns {boolean} True if the player is playing/staying for its channel.
|
* @returns {boolean} True if the player is playing/staying for its channel.
|
||||||
*/
|
*/
|
||||||
_isPlayerBusy(player) {
|
_isPlayerBusy(player) {
|
||||||
if (!player || player._destroyed) return false;
|
if (!player || player._destroyed || isPlayerConnectionDead(player)) return false;
|
||||||
try {
|
try {
|
||||||
if (player._get247Mode?.() === "on") return true;
|
if (player._get247Mode?.() === "on") return true;
|
||||||
if (player.queue?.getCurrent?.()) return true;
|
if (player.queue?.getCurrent?.()) return true;
|
||||||
@@ -173,7 +173,7 @@ export class PlayerManager {
|
|||||||
* @returns {boolean} True if audio is actively playing (or paused).
|
* @returns {boolean} True if audio is actively playing (or paused).
|
||||||
*/
|
*/
|
||||||
_isPlayerActivelyPlaying(player) {
|
_isPlayerActivelyPlaying(player) {
|
||||||
if (!player || player._destroyed) return false;
|
if (!player || player._destroyed || isPlayerConnectionDead(player)) return false;
|
||||||
try {
|
try {
|
||||||
if (player.queue?.getCurrent?.()) return true;
|
if (player.queue?.getCurrent?.()) return true;
|
||||||
if (player.queue && !player.queue.isEmpty()) return true;
|
if (player.queue && !player.queue.isEmpty()) return true;
|
||||||
|
|||||||
+167
-9
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* @module src/music/TrackStats
|
* @module src/music/TrackStats
|
||||||
* @description Persistent playback counter tracking total songs and tracks played across shards.
|
* @description Persistent playback counter tracking total and per-user songs and tracks played in MySQL.
|
||||||
* Backed by Redis with atomic INCR and debounced local storage in storage/stats.json.
|
* Backed by MySQL (user_tracks and bot_stats tables), Redis with atomic INCR, and debounced local storage in storage/stats.json.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
@@ -10,11 +10,14 @@ import { logger } from "../core/Logger.mjs";
|
|||||||
|
|
||||||
const STATS_FILE = path.join(process.cwd(), "storage", "stats.json");
|
const STATS_FILE = path.join(process.cwd(), "storage", "stats.json");
|
||||||
const REDIS_KEY = "fluxer:stats:tracks_played";
|
const REDIS_KEY = "fluxer:stats:tracks_played";
|
||||||
|
const REDIS_USER_PREFIX = "fluxer:stats:user_tracks:";
|
||||||
|
const BASELINE_SONGS = 4814;
|
||||||
|
|
||||||
class TrackStatsManager {
|
class TrackStatsManager {
|
||||||
constructor() {
|
constructor() {
|
||||||
this._tracksPlayed = 0;
|
this._tracksPlayed = BASELINE_SONGS;
|
||||||
this._extraData = {};
|
this._extraData = {};
|
||||||
|
this._pool = null;
|
||||||
this._redis = null;
|
this._redis = null;
|
||||||
this._saveTimer = null;
|
this._saveTimer = null;
|
||||||
this._loadFromFile();
|
this._loadFromFile();
|
||||||
@@ -29,7 +32,7 @@ class TrackStatsManager {
|
|||||||
const count = typeof raw.songs === "number"
|
const count = typeof raw.songs === "number"
|
||||||
? raw.songs
|
? raw.songs
|
||||||
: (typeof raw.tracksPlayed === "number" ? raw.tracksPlayed : 0);
|
: (typeof raw.tracksPlayed === "number" ? raw.tracksPlayed : 0);
|
||||||
this._tracksPlayed = Math.max(0, count);
|
this._tracksPlayed = Math.max(BASELINE_SONGS, count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -37,9 +40,69 @@ class TrackStatsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setPool(pool) {
|
||||||
|
this._pool = pool;
|
||||||
|
this._initDatabase().catch((e) => {
|
||||||
|
logger.warn("[TrackStats] Database init error:", e?.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async _initDatabase() {
|
||||||
|
if (!this._pool) return;
|
||||||
|
try {
|
||||||
|
await this._pool.execute(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`user_tracks\` (
|
||||||
|
\`user_id\` VARCHAR(32) NOT NULL PRIMARY KEY,
|
||||||
|
\`tracks_played\` BIGINT NOT NULL DEFAULT 0,
|
||||||
|
\`created_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
\`updated_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
|
||||||
|
await this._pool.execute(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`bot_stats\` (
|
||||||
|
\`id\` VARCHAR(32) NOT NULL PRIMARY KEY DEFAULT 'global',
|
||||||
|
\`tracks_played\` BIGINT NOT NULL DEFAULT 0,
|
||||||
|
\`updated_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
|
||||||
|
await this._pool.execute(`
|
||||||
|
INSERT IGNORE INTO \`bot_stats\` (\`id\`, \`tracks_played\`) VALUES ('global', ?);
|
||||||
|
`, [this._tracksPlayed]);
|
||||||
|
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`tracks_played\` FROM \`bot_stats\` WHERE \`id\` = 'global' LIMIT 1;
|
||||||
|
`);
|
||||||
|
|
||||||
|
if (rows && rows.length > 0 && typeof rows[0].tracks_played === "number") {
|
||||||
|
const dbCount = rows[0].tracks_played;
|
||||||
|
if (dbCount < this._tracksPlayed) {
|
||||||
|
await this._pool.execute(`
|
||||||
|
UPDATE \`bot_stats\` SET \`tracks_played\` = ? WHERE \`id\` = 'global';
|
||||||
|
`, [this._tracksPlayed]);
|
||||||
|
} else {
|
||||||
|
this._tracksPlayed = dbCount;
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this._syncRedis();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[TrackStats] Failed to initialize MySQL tables:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
setRedis(redisHandler) {
|
setRedis(redisHandler) {
|
||||||
this._redis = redisHandler;
|
this._redis = redisHandler;
|
||||||
this._syncRedis();
|
const client = this._redis?.client;
|
||||||
|
if (client) {
|
||||||
|
if (client.isOpen) {
|
||||||
|
this._syncRedis();
|
||||||
|
} else {
|
||||||
|
client.on("ready", () => this._syncRedis());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async _syncRedis() {
|
async _syncRedis() {
|
||||||
@@ -47,20 +110,31 @@ class TrackStatsManager {
|
|||||||
if (!client || !client.isOpen) return;
|
if (!client || !client.isOpen) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await client.set(REDIS_KEY, String(this._tracksPlayed), { NX: true });
|
|
||||||
const val = await client.get(REDIS_KEY);
|
const val = await client.get(REDIS_KEY);
|
||||||
if (val != null) {
|
if (val != null) {
|
||||||
const parsed = parseInt(val, 10);
|
const parsed = parseInt(val, 10);
|
||||||
if (Number.isFinite(parsed)) {
|
if (Number.isFinite(parsed)) {
|
||||||
this._tracksPlayed = Math.max(this._tracksPlayed, parsed);
|
if (parsed > this._tracksPlayed) {
|
||||||
|
this._tracksPlayed = parsed;
|
||||||
|
this.save();
|
||||||
|
if (this._pool) {
|
||||||
|
await this._pool.execute(`
|
||||||
|
UPDATE \`bot_stats\` SET \`tracks_played\` = ? WHERE \`id\` = 'global';
|
||||||
|
`, [parsed]).catch(() => {});
|
||||||
|
}
|
||||||
|
} else if (this._tracksPlayed > parsed) {
|
||||||
|
await client.set(REDIS_KEY, String(this._tracksPlayed));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
await client.set(REDIS_KEY, String(this._tracksPlayed));
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[TrackStats] Redis sync error:", e?.message);
|
logger.warn("[TrackStats] Redis sync error:", e?.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
increment(delta = 1) {
|
async increment(userId = null, delta = 1) {
|
||||||
this._tracksPlayed += delta;
|
this._tracksPlayed += delta;
|
||||||
|
|
||||||
const client = this._redis?.client;
|
const client = this._redis?.client;
|
||||||
@@ -68,11 +142,77 @@ class TrackStatsManager {
|
|||||||
client.incrBy(REDIS_KEY, delta).catch((e) => {
|
client.incrBy(REDIS_KEY, delta).catch((e) => {
|
||||||
logger.warn("[TrackStats] Redis incr error:", e?.message);
|
logger.warn("[TrackStats] Redis incr error:", e?.message);
|
||||||
});
|
});
|
||||||
|
if (userId && typeof userId === "string" && userId !== "system") {
|
||||||
|
client.incrBy(`${REDIS_USER_PREFIX}${userId}`, delta).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
await this._pool.execute(`
|
||||||
|
INSERT INTO \`bot_stats\` (\`id\`, \`tracks_played\`) VALUES ('global', ?)
|
||||||
|
ON DUPLICATE KEY UPDATE \`tracks_played\` = \`tracks_played\` + ?;
|
||||||
|
`, [this._tracksPlayed, delta]);
|
||||||
|
|
||||||
|
if (userId && typeof userId === "string" && userId !== "system") {
|
||||||
|
await this._pool.execute(`
|
||||||
|
INSERT INTO \`user_tracks\` (\`user_id\`, \`tracks_played\`) VALUES (?, ?)
|
||||||
|
ON DUPLICATE KEY UPDATE \`tracks_played\` = \`tracks_played\` + ?;
|
||||||
|
`, [userId, delta, delta]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[TrackStats] MySQL increment error:", err?.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this._scheduleSave();
|
this._scheduleSave();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getUserTracksPlayed(userId) {
|
||||||
|
if (!userId) return 0;
|
||||||
|
const cleanUid = String(userId);
|
||||||
|
|
||||||
|
const client = this._redis?.client;
|
||||||
|
if (client && client.isOpen) {
|
||||||
|
try {
|
||||||
|
const val = await client.get(`${REDIS_USER_PREFIX}${cleanUid}`);
|
||||||
|
if (val != null) {
|
||||||
|
const parsed = parseInt(val, 10);
|
||||||
|
if (Number.isFinite(parsed)) return parsed;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`tracks_played\` FROM \`user_tracks\` WHERE \`user_id\` = ? LIMIT 1;
|
||||||
|
`, [cleanUid]);
|
||||||
|
const count = rows?.[0]?.tracks_played ?? 0;
|
||||||
|
if (client && client.isOpen && count > 0) {
|
||||||
|
client.set(`${REDIS_USER_PREFIX}${cleanUid}`, String(count)).catch(() => {});
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[TrackStats] MySQL getUserTracksPlayed error:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTopUsers(limit = 10) {
|
||||||
|
if (!this._pool) return [];
|
||||||
|
try {
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`user_id\`, \`tracks_played\` FROM \`user_tracks\` ORDER BY \`tracks_played\` DESC LIMIT ?;
|
||||||
|
`, [Math.max(1, Math.min(50, Number(limit) || 10))]);
|
||||||
|
return rows ?? [];
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[TrackStats] MySQL getTopUsers error:", err?.message);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
_scheduleSave() {
|
_scheduleSave() {
|
||||||
if (this._saveTimer) return;
|
if (this._saveTimer) return;
|
||||||
this._saveTimer = setTimeout(() => {
|
this._saveTimer = setTimeout(() => {
|
||||||
@@ -103,12 +243,30 @@ class TrackStatsManager {
|
|||||||
if (val != null) {
|
if (val != null) {
|
||||||
const parsed = parseInt(val, 10);
|
const parsed = parseInt(val, 10);
|
||||||
if (Number.isFinite(parsed)) {
|
if (Number.isFinite(parsed)) {
|
||||||
this._tracksPlayed = Math.max(this._tracksPlayed, parsed);
|
if (parsed > this._tracksPlayed) {
|
||||||
|
this._tracksPlayed = parsed;
|
||||||
|
this._scheduleSave();
|
||||||
|
}
|
||||||
return this._tracksPlayed;
|
return this._tracksPlayed;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
await client.set(REDIS_KEY, String(this._tracksPlayed));
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`tracks_played\` FROM \`bot_stats\` WHERE \`id\` = 'global' LIMIT 1;
|
||||||
|
`);
|
||||||
|
if (rows && rows.length > 0 && typeof rows[0].tracks_played === "number") {
|
||||||
|
this._tracksPlayed = Math.max(this._tracksPlayed, rows[0].tracks_played);
|
||||||
|
return this._tracksPlayed;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
return this._tracksPlayed;
|
return this._tracksPlayed;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -263,6 +263,7 @@ const DisplayMixin = {
|
|||||||
*/
|
*/
|
||||||
announceSong(s) {
|
announceSong(s) {
|
||||||
if (!s) return;
|
if (!s) return;
|
||||||
|
if (this._destroyed || this.leaving || (!this._voiceConn && !this.connection)) return;
|
||||||
|
|
||||||
if (s.type === "radio") {
|
if (s.type === "radio") {
|
||||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", {
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", {
|
||||||
|
|||||||
@@ -720,6 +720,7 @@ class Player extends EventEmitter {
|
|||||||
this._onLavalinkPlayerDisconnect = null;
|
this._onLavalinkPlayerDisconnect = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
this.queue?.reset();
|
||||||
this.leaving = true;
|
this.leaving = true;
|
||||||
this._stopInactivityTimer();
|
this._stopInactivityTimer();
|
||||||
this._autoplay = false;
|
this._autoplay = false;
|
||||||
@@ -747,6 +748,7 @@ class Player extends EventEmitter {
|
|||||||
vm.leaveChannel(this._channelId);
|
vm.leaveChannel(this._channelId);
|
||||||
} catch(e) { /* best effort */ }
|
} catch(e) { /* best effort */ }
|
||||||
}
|
}
|
||||||
|
this.removeAllListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error("[Player] destroy error:", e.message);
|
logger.error("[Player] destroy error:", e.message);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,10 +84,14 @@ export class Queue extends EventEmitter {
|
|||||||
*/
|
*/
|
||||||
removeRange(from, to) {
|
removeRange(from, to) {
|
||||||
if (this.isEmpty()) return "The queue is empty.";
|
if (this.isEmpty()) return "The queue is empty.";
|
||||||
|
if (typeof from !== "number" || typeof to !== "number" || !Number.isFinite(from) || !Number.isFinite(to)) {
|
||||||
|
return "Invalid range.";
|
||||||
|
}
|
||||||
const start = Math.max(0, Math.min(from, to));
|
const start = Math.max(0, Math.min(from, to));
|
||||||
const end = Math.min(this.data.length - 1, Math.max(from, to));
|
const end = Math.min(this.data.length - 1, Math.max(from, to));
|
||||||
if (start >= this.data.length) return "Index out of bounds";
|
if (start >= this.data.length || end < start) return "Index out of bounds";
|
||||||
const deleteCount = (end - start) + 1;
|
const deleteCount = (end - start) + 1;
|
||||||
|
if (deleteCount <= 0) return "Invalid range.";
|
||||||
const removed = this.data.splice(start, deleteCount);
|
const removed = this.data.splice(start, deleteCount);
|
||||||
this.emit("queue", { type: "removeRange", data: { start, end, count: removed.length, old: this.data.slice(), removed, new: this.data } });
|
this.emit("queue", { type: "removeRange", data: { start, end, count: removed.length, old: this.data.slice(), removed, new: this.data } });
|
||||||
return { count: removed.length, removed };
|
return { count: removed.length, removed };
|
||||||
|
|||||||
@@ -333,6 +333,7 @@ const SearchMixin = {
|
|||||||
url: info.uri ?? null,
|
url: info.uri ?? null,
|
||||||
},
|
},
|
||||||
artists: null,
|
artists: null,
|
||||||
|
requester: trackMeta?.requester ?? trackMeta?.userId ?? null,
|
||||||
};
|
};
|
||||||
if (trackMeta) {
|
if (trackMeta) {
|
||||||
video.artist = trackMeta.artist ?? null;
|
video.artist = trackMeta.artist ?? null;
|
||||||
|
|||||||
@@ -395,7 +395,15 @@ export class MessageHandler {
|
|||||||
} else {
|
} else {
|
||||||
opts = { ...message };
|
opts = { ...message };
|
||||||
}
|
}
|
||||||
return new Message(await replyingTo.reply(opts, { ping: false }), this);
|
try {
|
||||||
|
return new Message(await replyingTo.reply(opts, { ping: false }), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot reply in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -409,7 +417,15 @@ export class MessageHandler {
|
|||||||
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
|
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
|
||||||
|
|
||||||
if (typeof message === "object" && Array.isArray(message.embeds)) {
|
if (typeof message === "object" && Array.isArray(message.embeds)) {
|
||||||
return new Message(await replyingTo.reply(message, { ping: false }), this);
|
try {
|
||||||
|
return new Message(await replyingTo.reply(message, { ping: false }), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot replyEmbed in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
options = {
|
options = {
|
||||||
@@ -423,7 +439,15 @@ export class MessageHandler {
|
|||||||
const { embedText, ...rest } = message;
|
const { embedText, ...rest } = message;
|
||||||
payload = { ...payload, ...rest };
|
payload = { ...payload, ...rest };
|
||||||
}
|
}
|
||||||
return new Message(await replyingTo.reply(payload, { ping: false }), this);
|
try {
|
||||||
|
return new Message(await replyingTo.reply(payload, { ping: false }), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot replyEmbed in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -443,7 +467,15 @@ export class MessageHandler {
|
|||||||
} else {
|
} else {
|
||||||
opts = message;
|
opts = message;
|
||||||
}
|
}
|
||||||
return new Message(await channel.send(opts), this);
|
try {
|
||||||
|
return new Message(await channel.send(opts), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot sendMessage in channel ${channel.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -458,7 +490,15 @@ export class MessageHandler {
|
|||||||
return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? "");
|
return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? "");
|
||||||
}
|
}
|
||||||
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
||||||
return new Message(await channel.send(content), this);
|
try {
|
||||||
|
return new Message(await channel.send(content), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot sendEmbed in channel ${channel.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const text = (typeof content === "object") ? content.embedText : content;
|
const text = (typeof content === "object") ? content.embedText : content;
|
||||||
const payload = this.#createEmbed(text, embedOptions);
|
const payload = this.#createEmbed(text, embedOptions);
|
||||||
@@ -466,7 +506,15 @@ export class MessageHandler {
|
|||||||
const { embedText, ...rest } = content;
|
const { embedText, ...rest } = content;
|
||||||
Object.assign(payload, rest);
|
Object.assign(payload, rest);
|
||||||
}
|
}
|
||||||
return new Message(await channel.send(payload), this);
|
try {
|
||||||
|
return new Message(await channel.send(payload), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot sendEmbed in channel ${channel.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -503,6 +551,11 @@ export class MessageHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] editEmbed: missing permissions or communication disabled: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
if (RETRYABLE.has(err.statusCode) && attempt < MAX_ATTEMPTS) {
|
if (RETRYABLE.has(err.statusCode) && attempt < MAX_ATTEMPTS) {
|
||||||
logger.warn(`[MessageHandler] editEmbed: ${err.statusCode} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`);
|
logger.warn(`[MessageHandler] editEmbed: ${err.statusCode} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`);
|
||||||
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
||||||
|
|||||||
@@ -416,6 +416,48 @@ class GatewayHandler {
|
|||||||
client.on(Events.VoiceStatesSync, (data) => {
|
client.on(Events.VoiceStatesSync, (data) => {
|
||||||
this._handleVoiceStatesSync(data);
|
this._handleVoiceStatesSync(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
client.on(Events.ChannelDelete ?? "channelDelete", (channel) => {
|
||||||
|
this._handleChannelDelete(channel);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_handleChannelDelete(channel) {
|
||||||
|
const channelId = cleanId(channel?.id ?? channel?._id);
|
||||||
|
if (!channelId) return;
|
||||||
|
|
||||||
|
const { remix } = this;
|
||||||
|
const guildId = cleanId(channel?.guildId ?? channel?.guild?.id ?? "");
|
||||||
|
|
||||||
|
const player = remix?.players?.playerMap?.get?.(channelId)
|
||||||
|
?? [...(remix?.players?.playerMap?.values?.() ?? [])].find(p => cleanId(p?._channelId) === channelId || cleanId(p?._home247Channel) === channelId);
|
||||||
|
|
||||||
|
if (player) {
|
||||||
|
logger.voice(`[ChannelDelete] Voice channel ${channelId} deleted — destroying associated player.`);
|
||||||
|
remix.players.playerMap.delete(channelId);
|
||||||
|
const homeCh = cleanId(player._home247Channel ?? "");
|
||||||
|
if (homeCh && homeCh !== channelId) remix.players.playerMap.delete(homeCh);
|
||||||
|
remix.players._unindexPlayer?.(player._guildId, channelId);
|
||||||
|
|
||||||
|
const pendingScrobble = remix.players._pendingScrobbleTimers?.get?.(channelId);
|
||||||
|
if (pendingScrobble) {
|
||||||
|
clearTimeout(pendingScrobble.timer);
|
||||||
|
remix.players._pendingScrobbleTimers.delete(channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
player.queue?.reset?.();
|
||||||
|
player.destroy();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[ChannelDelete] Player destroy error:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (guildId) {
|
||||||
|
remix.voiceCache?.removeChannel?.(guildId, channelId);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -373,11 +373,35 @@ const GuildSync = {
|
|||||||
|
|
||||||
logger.guild(
|
logger.guild(
|
||||||
`[GuildDelete] Received GuildDelete for server ${guildId} — ` +
|
`[GuildDelete] Received GuildDelete for server ${guildId} — ` +
|
||||||
`skipping removal (24/7 removal system disabled). ` +
|
`cleaning up active players while preserving settings for potential re-invite.`
|
||||||
`Settings and players are preserved. If the server truly removed the bot, ` +
|
|
||||||
`the GuildCreate handler will re-initialise on re-invite.`
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const guildChannels = remix.players?._guildPlayerIndex?.get?.(cleanGuildId);
|
||||||
|
if (guildChannels) {
|
||||||
|
for (const channelId of [...guildChannels]) {
|
||||||
|
const p = remix.players.playerMap.get(channelId);
|
||||||
|
if (p) {
|
||||||
|
remix.players.playerMap.delete(channelId);
|
||||||
|
const homeCh = cleanId(p._home247Channel ?? "");
|
||||||
|
if (homeCh && homeCh !== channelId) remix.players.playerMap.delete(homeCh);
|
||||||
|
try {
|
||||||
|
p.queue?.reset?.();
|
||||||
|
p.destroy();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
remix.players._guildPlayerIndex.delete(cleanGuildId);
|
||||||
|
}
|
||||||
|
for (const [key, p] of [...(remix.players?.playerMap?.entries?.() ?? [])]) {
|
||||||
|
if (cleanId(p?._guildId) === cleanGuildId) {
|
||||||
|
remix.players.playerMap.delete(key);
|
||||||
|
try {
|
||||||
|
p.queue?.reset?.();
|
||||||
|
p.destroy();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
remix.voiceCache.removeGuild(cleanGuildId);
|
remix.voiceCache.removeGuild(cleanGuildId);
|
||||||
for (const [stateKey, info] of [...this._prevVoiceState]) {
|
for (const [stateKey, info] of [...this._prevVoiceState]) {
|
||||||
if (cleanId(info.guildId) === cleanGuildId)
|
if (cleanId(info.guildId) === cleanGuildId)
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"playlists": 30,
|
"playlists": 30,
|
||||||
"songs": 600
|
"songs": 4814
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user