Files
fluxer/commands/search.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

163 lines
5.6 KiB
JavaScript

/**
* @file search.mjs — Search for songs with interactive selection menu
* @module commands.search
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { Message, getGlobalColor } from "../src/MessageHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/constants/providers.mjs";
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs";
export const command = new CommandBuilder()
.setName("search")
.setDescription(
"Display search results for a query and pick one to play.\n" +
"Supports all providers — use inline prefix e.g. `sp: song` or `-p dz`.",
"commands.search"
)
.setCategory("music")
.addExamples(
"$prefixsearch never gonna give you up",
"$prefixsearch sp: blinding lights",
"$prefixsearch -p dz get lucky"
)
.addChoiceOption(o =>
o.setName("provider")
.setDescription("The search provider. Default: YouTube Music.", "options.search.provider")
.addChoices(...PROVIDER_CHOICES)
.setDefault("ytm")
.addFlagAliases("p", "u", "use")
, true)
.addTextOption(o =>
o.setName("query")
.setDescription("The query to search for, or a provider-prefixed query like `sp: song name`.", "options.search.query")
.setRequired(true)
);
/**
* Execute the search 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 p = await this.getPlayer(msg, true, true, true);
if (!p) return;
const rawQuery = data.get("query").value;
const flagProvider = data.get("provider")?.value;
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
const provider = inlineProvider ?? flagProvider ?? "ytm";
const name = PROVIDER_NAMES[provider] ?? "YouTube Music";
const channel = msg.channel?.channel ?? msg.message?.channel;
if (!channel?.send) return;
/**
* Build a search-result embed using EmbedBuilder.
* @param {string} description
* @param {string} [footerText]
* @param {string} [authorLabel] - defaults to `name` (provider name)
*/
const makeEmbed = (description, footerText, authorLabel = name) => {
const b = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: authorLabel })
.setDescription(description);
if (footerText) b.setFooter({ text: footerText });
return b;
};
const nativeMsg = msg.message ?? msg;
const rawMsg = await nativeMsg.reply(
{ embeds: [makeEmbed(this.t(msg, "responses.search.loadingResults"), this.t(msg, "responses.play.searchingProvider", { provider: name }), this.t(msg, "responses.search.resultsTitle", { provider: name }))]},
{ ping: false }
).catch(() => null);
if (!rawMsg) return;
const res = await p.fetchResults(query, msg.authorId, provider);
if (!res?.count) {
rawMsg.edit({ embeds: [makeEmbed(this.t(msg, "responses.search.noResults"))] }).catch(() => {});
return;
}
const results = p.searches.get(msg.authorId) ?? [];
const reactions = NUMBER_EMOJIS.slice(0, res.count);
let desc = "";
results.forEach((v, i) => {
const dur = v.duration ? p.getDuration(v.duration) : "?:??";
const title = v.title || "Unknown";
const url = v.url || "";
desc += `${NUMBER_EMOJIS[i]} [${title}](${url}) — \`${dur}\`\n`;
});
desc += `\n${CANCEL_EMOJI} Cancel`;
await rawMsg.edit({
embeds: [makeEmbed(
desc,
this.t(msg, "responses.search.reactHint"),
this.t(msg, "responses.search.resultsTitle", { provider: name })
)]
}).catch(() => {});
for (const emoji of [...reactions, CANCEL_EMOJI]) {
await rawMsg.react(emoji).catch(() => {});
}
const allReactions = [...reactions, CANCEL_EMOJI];
const client = this.client;
const channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
const msgId = rawMsg.id;
const clearReactions = async () => {
try {
await rawMsg.removeAllReactions();
} catch(e) { }
};
const wrapped = new Message(rawMsg, this.messages);
const authorId = msg.message?.author?.id ?? msg.authorId;
const unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => {
const reactorId = e.user_id ?? e.userId ?? e.user?.id ?? null;
if (reactorId && reactorId !== authorId) return;
clearTimeout(timer);
unobserve();
await clearReactions();
if (e.emoji_id === CANCEL_EMOJI) {
rawMsg.edit({
embeds: [makeEmbed(this.t(msg, "responses.search.cancelled"), null, this.t(msg, "responses.search.resultsTitle", { provider: name }))]
}).catch(() => {});
return;
}
const idx = reactions.indexOf(e.emoji_id);
if (idx === -1) return;
const v = p.playResult(msg.authorId, idx);
if (!v) return;
rawMsg.edit({
embeds: [makeEmbed(
this.t(msg, "responses.search.added", { title: v.title, url: v.url }),
null,
this.t(msg, "responses.search.resultsTitle", { provider: name })
)]
}).catch(() => {});
});
const SESSION_MS = this.config?.timers?.searchSessionTimeout ?? 30_000;
const timer = setTimeout(() => {
unobserve();
clearReactions().catch(() => {});
rawMsg.edit({
embeds: [makeEmbed(this.t(msg, "responses.search.timedOut"), this.t(msg, "responses.search.sessionClosed"), this.t(msg, "responses.search.resultsTitle", { provider: name }))]
}).catch(() => {});
}, SESSION_MS);
}