From 90a4d809581b6f323628b58c714a4c9075d0f57a Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:57:48 +0800 Subject: [PATCH] fix(playback): cancel stale retries and scope failure messages --- src/bot/instance.test.ts | 17 +++++ src/bot/instance.ts | 126 +++++++++++++++++--------------------- src/bot/url-retry.ts | 6 +- src/music/netease.test.ts | 6 +- src/music/netease.ts | 4 +- src/music/provider.ts | 61 +++--------------- src/web/api/player.ts | 80 +++++++++++------------- 7 files changed, 126 insertions(+), 174 deletions(-) diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index 184c5a6..adddf54 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -461,6 +461,7 @@ function makeResolveCtx(opts: { config: {}, id: "bot1", voteSkipUsers: new Set(), + queue: { current: vi.fn(() => null) }, autoPaused: false, currentSourceIsSpotify: opts.currentSourceIsSpotify ?? false, effectiveDuration: undefined, @@ -487,6 +488,22 @@ function spotifySong() { }; } +it("does not start a track whose URL resolved after the queue was cleared", async () => { + const player = makePlayer(); + const song = { ...spotifySong(), platform: "netease" }; + const ctx = makeResolveCtx({ controller: makeController(), player, url: "" }); + ctx.queue.current.mockReturnValue(song); + ctx.getProviderFor.mockReturnValue({ + getSongUrl: async () => { + ctx.queue.current.mockReturnValue(null); + return { url: "https://example.com/track" }; + }, + }); + + expect(await resolveAndPlay.call(ctx, song)).toBe(false); + expect(player.play).not.toHaveBeenCalled(); +}); + describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => { it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => { const controller = makeController(); diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 69362cb..fae6a8b 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -204,14 +204,7 @@ export class BotInstance extends EventEmitter { private fmRequesterName: string | undefined; /** Results of the most recent !search, for "#N" selection (issue #90). */ private lastSearchResults: Song[] = []; - /** - * Why the most recent resolveAndPlay produced nothing, or null. - * - * Kept as an instance field rather than a second return value: `resolveAndPlay` - * has ~20 call sites and its boolean is load-bearing in tests, while only the - * web routes need the explanation. They read this right after a false. - */ - private lastPlayFailure: PlayFailure | null = null; + private playbackRequest?: symbol; /** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */ private effectiveDuration: number | undefined; /** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */ @@ -1032,53 +1025,41 @@ export class BotInstance extends EventEmitter { return requestedBy ? { ...song, requestedBy } : { ...song }; } - /** - * Why the last `resolveAndPlay(false)` produced nothing, or null after a - * success. Web routes read this to say what actually went wrong instead of - * the old catch-all 「区域/版权限制」. - */ - getLastPlayFailure(): PlayFailure | null { - return this.lastPlayFailure; - } - - /** Resolve URL for a song and start playing it. Skips to next if URL fails. */ - async resolveAndPlay(song: QueuedSong): Promise { - this.lastPlayFailure = null; + /** Resolve the URL and start playback if this request still owns the queue. */ + async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise { + const request = Symbol(); + this.playbackRequest = request; + const generation = this.lifecycleGeneration; + const current = this.queue.current(); + const isCancelled = () => !this.connected || this.lifecycleGeneration !== generation || + this.playbackRequest !== request || this.queue.current() !== current; + const fail = (message: string) => onFailure?.({ + platform: song.platform, + songId: song.id, + code: "unknown", + message, + }); if (!this.connected) { - this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping"); - // Recorded so the web route can say this instead of blaming copyright: - // every early return used to leave lastPlayFailure null, which made the - // UI fall back to the catch-all 「区域/版权限制」 for unrelated causes. - this.lastPlayFailure = { - platform: song.platform, - songId: song.id, - code: "unknown", - message: "机器人未连接,无法播放", - }; + fail("机器人未连接"); return false; } if (song.platform === "local" && !this.isLocalAudioEnabled()) { - this.logger.warn({ songId: song.id, name: song.name }, "Local audio playback disabled — refusing track"); - this.lastPlayFailure = { - platform: song.platform, - songId: song.id, - code: "unknown", - message: "该机器人已关闭本地音频播放", - }; + fail("该机器人已关闭本地音频播放"); return false; } // Clear any accumulated skip votes — every fresh track starts with a // clean slate, regardless of which code path loaded it (cmdPlay, // cmdPlaylist, cmdAlbum, cmdFm, trackEnd auto-advance, etc.). this.voteSkipUsers.clear(); - const provider = this.getProviderFor(song.platform); try { + const provider = this.getProviderFor(song.platform); if (song.platform === "bilibili" && (!song.id.includes("?p=") || song.duration === 0)) { // Detail is metadata only (duration / canonical id). A failure here used // to abort the whole resolve before the retry budget even started, so a // transient 4xx turned into an instant 「无法播放」. try { const detail = await provider.getSongDetail(song.id); + if (isCancelled()) return false; if (detail) { song.duration = detail.duration; song.name = detail.name; @@ -1101,7 +1082,7 @@ export class BotInstance extends EventEmitter { fallbacks: provider.getFallbackQualities?.() ?? [], // Stop / disconnect must abort the budget: retrying into a dead // connection only delays the queue. - isCancelled: () => !this.connected, + isCancelled, onAttemptFailed: ({ attempt, total, quality, error }) => { const fields = { songId: song.id, name: song.name, attempt, total, quality }; if (error instanceof RiskControlError) { @@ -1130,7 +1111,7 @@ export class BotInstance extends EventEmitter { code: "unknown" as const, message: `没有拿到播放地址(${quality ?? "默认音质"})`, }; - this.lastPlayFailure = failure; + onFailure?.(failure); this.logger.warn( { songId: song.id, @@ -1145,29 +1126,17 @@ export class BotInstance extends EventEmitter { ); }, }); - if (!result?.url) { - return false; - } - // Re-check connection state AFTER the network round-trip — the URL - // resolve can take multiple seconds and the user may have called stop - // during that window. Without this, we'd spawn ffmpeg on a - // disconnected bot and land back in the same "connected=false but - // playing=true" inconsistency that Bug C was about. - if (!this.connected) { - this.logger.warn( - { songId: song.id, name: song.name }, - "bot disconnected during URL resolve — aborting playback", - ); - return false; - } + if (!result?.url || isCancelled()) return false; // Stage 2: a `spotify:` sentinel URI means the go-librespot sidecar // serves the audio, NOT ffmpeg. Start the per-bot sidecar on demand; if // it can't run (disabled / non-Linux / binary missing) keep the Stage-1 // fallback message + skip so the queue keeps moving. if (isSpotifyUri(result.url)) { const ready = await this.spotifyController.ensureStarted(); + if (isCancelled()) return false; if (!ready) { this.logger.info({ songId: song.id, name: song.name }, "Spotify backend unavailable — skipping"); + fail(SPOTIFY_UNAVAILABLE_MESSAGE); await this.tsClient.sendTextMessage(SPOTIFY_UNAVAILABLE_MESSAGE); return false; } @@ -1177,8 +1146,10 @@ export class BotInstance extends EventEmitter { // sidecar failed the play (dead/errored backend): never attach the // player to a dead stream — send the same fallback and skip. const played = await this.spotifyController.playTrack(result.url); + if (isCancelled()) return false; if (!played) { this.logger.info({ songId: song.id, name: song.name }, "Spotify playTrack failed — skipping"); + fail(SPOTIFY_UNAVAILABLE_MESSAGE); await this.tsClient.sendTextMessage(SPOTIFY_UNAVAILABLE_MESSAGE); return false; } @@ -1278,11 +1249,9 @@ export class BotInstance extends EventEmitter { this.emit("stateChange"); return true; } catch (err) { + if (isCancelled()) return false; this.logger.error({ err, songId: song.id }, "Failed to resolve URL"); - // Anything thrown outside the retry budget (detail lookup, spotify - // handoff, player start) still needs a cause, otherwise the web route - // prints the old 「区域/版权限制」 for a cause that is not copyright. - this.lastPlayFailure = toPlayFailure(song.platform, song.id, err); + onFailure?.(toPlayFailure(song.platform, song.id, err)); return false; } } @@ -1466,8 +1435,9 @@ export class BotInstance extends EventEmitter { const { song, error } = await this.resolvePlayQuery(cmd); if (error) return error; const song0 = song!; - const ok = await this.playSingleSong(song0, requesterName); - if (!ok) return `Cannot play: ${song0.name}`; + let why: string | undefined; + const ok = await this.playSingleSong(song0, requesterName, failure => { why = failure.message; }); + if (!ok) return why ? `Cannot play: ${song0.name} — ${why}` : `Cannot play: ${song0.name}`; return `Now playing: ${song0.name} - ${song0.artist}`; } @@ -1483,7 +1453,7 @@ export class BotInstance extends EventEmitter { * Shared by chat !play and the web /play-song route so the toggle decision * lives in exactly one place (#119). Returns true if a track started playing. */ - async playSingleSong(song: QueuedSong, requesterName?: string): Promise { + async playSingleSong(song: QueuedSong, requesterName?: string, onFailure?: (failure: PlayFailure) => void): Promise { const s = this.withRequester(song, requesterName); if (this.config.playKeepsQueue && !this.queue.isEmpty()) { const insertedAt = @@ -1496,7 +1466,7 @@ export class BotInstance extends EventEmitter { this.queue.playAt(insertedAt); this.player.resetFailures(); // No sweep here: the queue is kept, so no local uploads were released. - return this.resolveAndPlay(this.queue.current()!); + return this.resolveAndPlay(this.queue.current()!, onFailure); } // Legacy replace behavior (default). const previous = this.queue.current(); @@ -1510,7 +1480,7 @@ export class BotInstance extends EventEmitter { // Reset failure counter on user-initiated play this.player.resetFailures(); - const ok = await this.resolveAndPlay(this.queue.current()!); + const ok = await this.resolveAndPlay(this.queue.current()!, onFailure); // Sweep AFTER the new song is queued+resolved: the replaced songs are no // longer referenced (and get deleted), but the song — if it is the same // local upload that was already playing — stays referenced and is preserved. @@ -2202,24 +2172,39 @@ export class BotInstance extends EventEmitter { * * Returns true if a song actually started playing, false otherwise. */ - async playNext(maxRetries = 3): Promise { + async playNext(maxRetries = 3, onFailure?: (failure: PlayFailure) => void): Promise { if (this.isAdvancing || !this.connected) return false; this.isAdvancing = true; let started = false; + let riskControlled = false; + const captureFailure = (failure: PlayFailure) => { + riskControlled = failure.code === "risk_control"; + onFailure?.(failure); + }; + const generation = this.lifecycleGeneration; + const unchanged = (song: QueuedSong, request: symbol | undefined) => + this.connected && this.lifecycleGeneration === generation && + this.queue.current() === song && this.playbackRequest === request; try { if (this.player.getState() !== "idle") this.player.stop(true); this.voteSkipUsers.clear(); const next = this.queue.next(); if (next) { - started = await this.resolveAndPlay(next); + const playback = this.resolveAndPlay(next, captureFailure); + const request = this.playbackRequest; + started = await playback; + if (!started && !unchanged(next, request)) return false; if (!started) { - for (let i = 0; i < maxRetries && this.connected; i++) { + for (let i = 0; i < maxRetries && this.connected && !riskControlled; i++) { const retry = this.queue.next(); if (!retry) break; - if (await this.resolveAndPlay(retry)) { + const retryPlayback = this.resolveAndPlay(retry, captureFailure); + const retryRequest = this.playbackRequest; + if (await retryPlayback) { started = true; break; } + if (!unchanged(retry, retryRequest)) return false; } } if (!started) { @@ -2235,7 +2220,10 @@ export class BotInstance extends EventEmitter { await this.refillFm(); const refillNext = this.queue.next(); if (refillNext) { - started = await this.resolveAndPlay(refillNext); + const refillPlayback = this.resolveAndPlay(refillNext, captureFailure); + const refillRequest = this.playbackRequest; + started = await refillPlayback; + if (!started && !unchanged(refillNext, refillRequest)) return false; } if (!started) { this.player.stop(); diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index 0094747..2a2ed5a 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -167,12 +167,14 @@ export async function resolveUrlWithRetry( let error: unknown; requestsMade += 1; + let result: SongUrlResult | null = null; try { - const result = await opts.resolve(step.quality); - if (result?.url) return result; + result = await opts.resolve(step.quality); } catch (err) { error = err; } + if (opts.isCancelled?.()) return null; + if (result?.url) return result; riskControlled = error instanceof RiskControlError; lastError = error; lastQuality = step.quality; diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index bd108bb..cea61e2 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -442,11 +442,11 @@ describe("NetEase risk control (-460)", () => { await expect(p.getSongUrl("1827600686")).rejects.toBeInstanceOf(RiskControlError); }); - it("keeps the upstream message so the log says what happened", async () => { + it("returns a fixed risk-control error without exposing the upstream message", async () => { const p = providerWithApi(async () => { - throw httpError(400, { code: -460, message: "检测到您的网络环境存在风险,请稍后再试" }); + throw httpError(400, { code: -460, message: "upstream sample detail" }); }); - await expect(p.getSongUrl("1827600686")).rejects.toThrow(/风险/); + await expect(p.getSongUrl("1827600686")).rejects.toThrow("网易云请求被风控拦截 (-460)"); }); it("does not disguise a genuine bad request", async () => { diff --git a/src/music/netease.ts b/src/music/netease.ts index 5741d02..18d8dc0 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -124,10 +124,10 @@ export function parseNeteaseTrial(item: any): number | undefined { */ function riskControlFrom(err: unknown): RiskControlError | null { const e = err as { - response?: { status?: number; data?: { code?: number; message?: string } }; + response?: { status?: number; data?: { code?: number } }; }; if (e?.response?.status === 400 && e.response.data?.code === RISK_CONTROL_CODE) { - return new RiskControlError(e.response.data.message ?? "网络环境风险 (-460)"); + return new RiskControlError("网易云请求被风控拦截 (-460)"); } return null; } diff --git a/src/music/provider.ts b/src/music/provider.ts index a2c76d1..c315919 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -34,24 +34,7 @@ export interface SongUrlResult { trialDuration?: number; } -/** - * NetEase rate-limits by IP, not by request shape. When it decides the caller's - * network looks risky it answers **HTTP 400** with - * - * {"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"} - * - * Cloud-host IPs hit this constantly; it clears up on its own after a few - * seconds. Because it is a 4xx, axios reports `ERR_BAD_REQUEST` — identical to - * a genuinely malformed request — so the only way to tell them apart is to read - * the response body. The distinction matters: -460 is worth retrying, a bad - * request never is. - * - * Measured on a live host: the anonymous call `?id=…&level=exhigh` answered - * 400/-460 every time, while the same call with the account cookie answered 200 - * and returned a full 320k URL. Intermittently, the cookie version is also - * rejected — which is exactly the "click play five times until it works" - * behaviour users report. - */ +/** NetEase upstream risk-control response code. */ export const RISK_CONTROL_CODE = -460; export class RiskControlError extends Error { @@ -109,45 +92,17 @@ export class SongUrlUnavailable extends Error { } } -/** Build the -460 flavour. Kept here so every provider names it identically. */ -export function riskControlFailure( - platform: string, - songId: string, - detail?: string, -): PlayFailure { - return { - platform, - songId, - code: "risk_control", - // 「约 5 秒」是有依据的:实测同一 IP 连续请求一般是 -460 几次之后放行, - // 重试预算也已经只留一次(RISK_CONTROL_BACKOFF_MS)。给一个具体的等待值, - // 比「请稍后重试」更能让人知道该干嘛。 - message: "被网易云风控拦截(-460),约 5 秒后再试", - upstream: detail ? { detail } : undefined, - }; -} - -/** - * Normalise anything a failed attempt threw into a `PlayFailure`, so callers - * never have to pattern-match on error classes themselves. - * - * The `unknown` branch truncates the message: axios errors carry the whole - * request config (including the cookie) and would otherwise put kilobytes into - * a UI toast and the log. - */ export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure { if (error instanceof SongUrlUnavailable) return error.failure; if (error instanceof RiskControlError) { - return riskControlFailure(platform, songId, error.message); + return { + platform, + songId, + code: "risk_control", + message: "网易云暂时拒绝播放请求(-460),请稍后重试", + }; } - const raw = error instanceof Error ? error.message : ""; - const short = raw.replace(/\s+/g, " ").trim().slice(0, 120); - return { - platform, - songId, - code: "unknown", - message: short ? `解析播放地址失败:${short}` : "解析播放地址失败", - }; + return { platform, songId, code: "unknown", message: "解析播放地址失败" }; } export interface Playlist { diff --git a/src/web/api/player.ts b/src/web/api/player.ts index 9637e84..ce3880e 100644 --- a/src/web/api/player.ts +++ b/src/web/api/player.ts @@ -1,7 +1,9 @@ import { Router } from "express"; +import type { BotInstance } from "../../bot/instance.js"; +import type { QueuedSong } from "../../audio/queue.js"; import type { BotManager } from "../../bot/manager.js"; import type { BotDatabase } from "../../data/database.js"; -import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js"; +import type { MusicProvider, Song, ArtistSongPage, PlayFailure } from "../../music/provider.js"; import type { Logger } from "../../logger.js"; import { parseCommand } from "../../bot/commands.js"; import { requireBotAccess } from "../middleware/requirePermission.js"; @@ -61,28 +63,20 @@ export function createPlayerRouter( next(); }); - /** - * One line explaining why a track would not play. - * - * Every failure used to say 「(区域/版权限制)」 — including a lapsed - * membership, a delisted track and a quality level the account cannot - * stream. That single string is why three separate investigations went - * hunting for a copyright problem that was not there. The bot now records - * the real cause; this only falls back to the old wording when it has none. - */ - const whyUnplayable = (bot: any, song: { name?: string; id?: string }): string => { + const whyUnplayable = (song: { name?: string; id?: string }, reason?: string): string => { const label = song.name || song.id || "这首歌"; - const reason: string | undefined = bot?.getLastPlayFailure?.()?.message; - return reason - ? `无法播放「${label}」:${reason}` - : `无法播放「${label}」(区域/版权限制)`; + return reason ? `无法播放「${label}」:${reason}` : `无法播放「${label}」`; }; - /** Same, for the batch paths where a cause is context, not the headline. */ - const lastReason = (bot: any): string => { - const failure = bot?.getLastPlayFailure?.(); - return failure?.message ? `,最近一次:${failure.message}` : ""; - }; + async function startCollection(bot: BotInstance, first: QueuedSong | null) { + let failure: PlayFailure | undefined; + const capture = (reason: PlayFailure) => { failure = reason; }; + let started = first ? await bot.resolveAndPlay(first, capture) : false; + if (first && !started && failure?.code !== "risk_control" && bot.getQueueManager().current() === first) { + started = await bot.playNext(20, capture); + } + return { started, reason: failure?.message }; + } /** Map API platform string to the corresponding command flag. */ const platformFlag = (platform: unknown): string => { @@ -393,7 +387,7 @@ export function createPlayerRouter( // the sequential retry path, which still has a chance. } if (queueable.length === 0) { - res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); + res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放` }); return; } @@ -422,19 +416,16 @@ export function createPlayerRouter( // retry-skip behavior. Use a higher retry budget than the default // trackEnd auto-advance because user-initiated playlist plays // commonly have long contiguous runs of unplayable songs. - let started = first ? await bot.resolveAndPlay(first) : false; - if (first && !started) { - started = await bot.playNext(20); - } + const { started, reason } = await startCollection(bot, first); const playing = queue.current(); const loadedMsg = queueable.length < totalCount - ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放${lastReason(bot)})` + ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)` : `已加载 ${queueable.length} 首`; if (started && playing) { res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` }); } else { - res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` }); + res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` }); } } catch (err) { logger.error({ err }, "Play playlist failed"); @@ -479,7 +470,7 @@ export function createPlayerRouter( } } if (queueable.length === 0) { - res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); + res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放` }); return; } @@ -500,19 +491,16 @@ export function createPlayerRouter( first = queue.play(); } - let started = first ? await bot.resolveAndPlay(first) : false; - if (first && !started) { - started = await bot.playNext(20); - } + const { started, reason } = await startCollection(bot, first); const playing = queue.current(); const loadedMsg = queueable.length < totalCount - ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放${lastReason(bot)})` + ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)` : `已加载 ${queueable.length} 首`; if (started && playing) { res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` }); } else { - res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` }); + res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` }); } } catch (err) { logger.error({ err }, "play-album failed"); @@ -569,7 +557,7 @@ export function createPlayerRouter( } } if (queueable.length === 0) { - res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放${lastReason(bot)}` }); + res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放` }); return; } @@ -595,16 +583,15 @@ export function createPlayerRouter( first = queue.play(); } - let started = first ? await bot.resolveAndPlay(first) : false; - if (first && !started) started = await bot.playNext(20); + const { started, reason } = await startCollection(bot, first); const playing = queue.current(); const loadedMsg = queueable.length < totalCount - ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放${lastReason(bot)})` + ? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)` : `已加载 ${queueable.length} 首`; return started && playing ? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` } - : { ok: false, message: `${loadedMsg},但无法开始播放。` }; + : { ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` }; }); res.json(body); } catch (err) { @@ -634,10 +621,11 @@ export function createPlayerRouter( // clear branch — do NOT also call it here, or it would delete retained // local uploads in keep-queue mode. const body = await bot.runExclusive(async () => { - const ok = await bot.playSingleSong({ ...song }, requesterName(req)); + let reason: string | undefined; + const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure: PlayFailure) => { reason = failure.message; }); return ok ? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` } - : { ok: false, message: whyUnplayable(bot, song) }; + : { ok: false, message: whyUnplayable(song, reason) }; }); res.json(body); } catch (err) { @@ -677,9 +665,10 @@ export function createPlayerRouter( // Promote the just-added song to current and start it. queue.playAt(insertedAt); bot.getPlayer().resetFailures(); - const ok = await bot.resolveAndPlay(queue.current()!); + let reason: string | undefined; + const ok = await bot.resolveAndPlay(queue.current()!, (failure: PlayFailure) => { reason = failure.message; }); if (!ok) { - return { ok: false, message: whyUnplayable(bot, song) }; + return { ok: false, message: whyUnplayable(song, reason) }; } return { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }; } @@ -716,9 +705,10 @@ export function createPlayerRouter( queue.addNext({ ...song, requestedBy: requesterName(req) }); queue.playAt(insertedAt); bot.getPlayer().resetFailures(); - const ok = await bot.resolveAndPlay(queue.current()!); + let reason: string | undefined; + const ok = await bot.resolveAndPlay(queue.current()!, (failure: PlayFailure) => { reason = failure.message; }); if (!ok) { - return { ok: false, message: whyUnplayable(bot, song) }; + return { ok: false, message: whyUnplayable(song, reason) }; } return { ok: true, message: `正在播放:${song.name || "Unknown"} - ${song.artist || "Unknown"}` }; });