Files
fluxer/commands/radio.mjs
T
NoLogicAlan 092268281a refactor: centralize shared utilities, fix voice intent, and improve error visibility
- extract `cleanId()` to `Utils.mjs` and remove 97+ inline `String(x).replace(/\D/g, "")` duplicates

- add `VoiceStateResolver.mjs` with `iterateVoiceStates`, `hasHumansInChannel`, `getChannelsWithHumans` — eliminates 12+ duplicated voice-state-iteration blocks across `Player`, `PlayerManager`, `GatewayHandler`, `Dashboard`

- add `UI.mjs` for shared color, emoji, and timeout constants

- move `parseInlineProvider` to `providers.mjs`, `getMessageGuildId` to `MessageHandler.mjs`

- fix `VoiceStateCache.removeGuild` and `TrackOptionsManager` cache deletion mutating Maps during iteration

- fix `checkVoiceChannels` now async returning `{channelId, alreadyInVoice, hasHumans}` — all callers updated

- fix `FluxerRevoice` global `console.log` monkey-patch replaced with scoped `withSuppressedLiveKitLogs(fn)`

- fix `Player._get247Mode()` settings resolution chain

- fix `runnables.mjs` validators were no-ops

- promote `Player` magic numbers to named static constants

- replace all silent `catch (_) {}` with `logger.warn()` throughout

- remove unused deps: `express`, `genius-lyrics`, `ws`

- add `@file` JSDoc headers to all modules
2026-06-15 16:56:10 +03:00

156 lines
5.2 KiB
JavaScript

/**
* @file radio.mjs — Play a radio stream or search for radio stations
* @module commands.radio
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs";
export const command = function() {
if (!this.config.radio?.length) return null;
return new CommandBuilder()
.setName("radio")
.setDescription("Play a radio station. Use `${prefix}radio list` to browse all stations.", "commands.radio")
.addAliases("r")
.setCategory("music")
.addTextOption(o =>
o.setName("station")
.setDescription("Station name, 'list' to browse, or leave blank for default.")
.setRequired(false)
);
};
/**
* Execute the radio command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>>} data - Slash-command options map
* @returns {Promise<void>}
*/
export async function run(msg, data) {
const radios = this.config.radio;
if (!radios?.length) return msg.reply(this.t(msg, "responses.radio.noStations"));
const input = (data.get("station")?.value ?? "").trim().toLowerCase();
if (input === "list") {
let page = 0;
const perPage = NUMBER_EMOJIS.length;
const totalPages = Math.ceil(radios.length / perPage);
const buildPage = () => {
const start = page * perPage;
const pickable = radios.slice(start, start + perPage);
let desc = `📻 **Radio Stations (Page ${page + 1}/${totalPages})**\n\n`;
pickable.forEach((r, i) => {
desc += `${NUMBER_EMOJIS[i]} **${r.detailedName}** (\`${r.name}\`)\n`;
desc += ` ${r.description.replaceAll("\n", "\n ")}\n\n`;
});
desc += `⬅️ Previous ➡️ Next ❌ Cancel`;
return { payload: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }, pickable };
};
let { payload, pickable } = buildPage();
const listMsg = await msg.reply(payload);
if (!listMsg) return;
const baseEmojis = [...NUMBER_EMOJIS, PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
for (const e of baseEmojis) await listMsg.message.react(e).catch(() => {});
let settled = false;
const clearReactions = async () => {
const rawMsg = listMsg.message;
try {
await rawMsg.removeAllReactions();
} catch (_) {
for (const emoji of baseEmojis) {
try { await rawMsg.removeReaction(emoji); } catch(e) { }
}
}
};
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
unobserve();
clearReactions().catch(() => {});
listMsg.edit(this.t(msg, "responses.radio.timedOut")).catch(() => {});
}, 60_000);
const normalize = (s) => s.replace(/\uFE0F/g, "");
const unobserve = listMsg.onReaction(baseEmojis, async (e) => {
if (settled) return;
const emoji = normalize(e.emoji_id);
if (emoji === normalize(CANCEL_EMOJI)) {
settled = true;
clearTimeout(timeout);
unobserve();
await clearReactions();
listMsg.edit(this.t(msg, "responses.radio.cancelled")).catch(() => {});
return;
}
if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages;
else if (emoji === normalize(PREV_EMOJI)) page = (page - 1 + totalPages) % totalPages;
else {
const idx = NUMBER_EMOJIS.findIndex(x => normalize(x) === emoji);
if (idx !== -1 && idx < pickable.length) {
settled = true;
clearTimeout(timeout);
unobserve();
await clearReactions();
const selected = radios[page * perPage + idx];
return playStation(this, msg, selected, listMsg);
}
}
const next = buildPage();
pickable = next.pickable;
await listMsg.edit(next.payload).catch(() => {});
}, msg.author);
return;
}
if (input) {
const radio = radios.find(r => r.name.toLowerCase() === input);
if (!radio) {
const names = radios.map(r => `\`${r.name}\``).join(", ");
return msg.reply(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names }));
}
return playStation(this, msg, radio);
}
return playStation(this, msg, radios[0]);
}
async function playStation(ctx, msg, radio, editTarget = null) {
const p = await ctx.getPlayer(msg, true, true, true);
if (!p) return;
const current = p.queue.getCurrent();
const hasRadioQueued = p.queue.data.some(t => t.type === "radio");
if (current?.type === "radio" || hasRadioQueued) await p.switchRadio(radio);
else p.playRadio(radio);
const prefix = ctx.handler.getPrefix(msg?.channel?.channel?.guildId ?? msg?.message?.guildId);
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`📻 ${radio.detailedName}`)
.setDescription(
`**[${radio.detailedName}](${radio.author.url})**\n\n` +
`${radio.description}\n\n` +
`_Use \`${prefix}skip\` to stop the radio, or \`${prefix}radio list\` to switch stations._`
)
;
if (editTarget) editTarget.edit({ embeds: [embed] }).catch(() => {});
else msg.reply({ embeds: [embed] }).catch(() => {});
}