Survive revoice's ffmpeg teardown and explain failed deletions

Switching tracks killed the process: revoice's #cleanUp() dereferences
this.fProc unconditionally, and its own ffmpeg error handler calls stop()
a second time after stop() has already nulled that field. Killing ffmpeg
is what triggers that error, so its handlers are detached first, the
instance's stop() is wrapped defensively (revoice calls it internally),
and an uncaughtException handler keeps the bot in the channel if the
dependency throws from another async callback.

Failed command-message deletions were logged at debug, i.e. invisible in
the default configuration; they now warn with Stoat's error type, and the
README says which permission the bot's role needs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Leonid Pershin
2026-09-08 23:50:31 +03:00
co-authored by Claude Opus 5
parent 315760e076
commit f22b08b350
5 changed files with 188 additions and 160 deletions
+3 -2
View File
@@ -178,8 +178,9 @@ cd /opt/stoat-mbot && docker compose up -d --build && docker compose logs -f
Все параметры — в [.env.example](.env.example). Что стоит знать: Все параметры — в [.env.example](.env.example). Что стоит знать:
- `DELETE_COMMAND_MESSAGES=true` (по умолчанию) — бот удаляет сообщение с командой, чтобы не - `DELETE_COMMAND_MESSAGES=true` (по умолчанию) — бот удаляет сообщение с командой, чтобы не
засорять канал. Нужно право `ManageMessages`; без него команда всё равно отработает, засорять канал. Для этого роли бота нужно право **Manage Messages** в настройках сервера
а неудачное удаление уйдёт в лог на уровне `debug`. (Settings → Roles → роль бота) или в правах самого канала. Без него команда всё равно
отработает, а в логе будет `could not delete command message` с причиной отказа.
- `REQUIRE_DJ_ROLE=true` — управлять смогут только владелец сервера, обладатели `ManageServer` - `REQUIRE_DJ_ROLE=true` — управлять смогут только владелец сервера, обладатели `ManageServer`
и роли из `DJ_ROLE_NAME`. По умолчанию `false`: играть может любой участник сервера. и роли из `DJ_ROLE_NAME`. По умолчанию `false`: играть может любой участник сервера.
- `IDLE_TIMEOUT_SECONDS` — через сколько секунд простоя (или пустого канала) бот выходит из войса. - `IDLE_TIMEOUT_SECONDS` — через сколько секунд простоя (или пустого канала) бот выходит из войса.
+6 -2
View File
@@ -68,8 +68,12 @@ async function handleMessage(manager: MusicManager, message: Message): Promise<v
if (config.DELETE_COMMAND_MESSAGES) { if (config.DELETE_COMMAND_MESSAGES) {
// Fire-and-forget: a missing ManageMessages permission must not block playback. // Fire-and-forget: a missing ManageMessages permission must not block playback.
void message.delete().catch((err) => { void message.delete().catch((err: unknown) => {
log.debug({ err, command: command.name }, "could not delete command message"); const type = (err as { response?: { data?: { type?: string } } })?.response?.data?.type;
log.warn(
{ type: type ?? String(err), command: command.name },
"could not delete command message (bot needs ManageMessages)",
);
}); });
} }
+20 -1
View File
@@ -185,6 +185,18 @@ export class GuildPlayer extends EventEmitter<GuildPlayerEvents> {
connection.on("userJoin", () => this.clearIdleTimer()); connection.on("userJoin", () => this.clearIdleTimer());
const media = new MediaPlayer(true); const media = new MediaPlayer(true);
// revoice's #cleanUp() dereferences this.fProc unconditionally, so a second
// stop() (which its own ffmpeg error handler triggers) throws and would take
// the whole process down. Everything it calls goes through this instance
// method, so guarding it here covers its internal paths too.
const stop = media.stop.bind(media);
media.stop = (init?: boolean) => {
try {
stop(init);
} catch (err) {
this.log.debug({ err }, "revoice cleanup threw, ignoring");
}
};
media.on("startplay", () => { media.on("startplay", () => {
this.setStatus(media.paused ? "paused" : "playing"); this.setStatus(media.paused ? "paused" : "playing");
this.startTicker(); this.startTicker();
@@ -298,7 +310,14 @@ export class GuildPlayer extends EventEmitter<GuildPlayerEvents> {
if (this.media) { if (this.media) {
this.expectingStop = true; this.expectingStop = true;
try { try {
this.media.fProc?.kill("SIGKILL"); // Detach revoice's own handlers first: killing ffmpeg makes it emit
// "error", and its handler would call stop() again on a half-reset player.
const proc = this.media.fProc;
if (proc) {
proc.removeAllListeners("error");
proc.removeAllListeners("end");
proc.kill("SIGKILL");
}
} catch { } catch {
// ffmpeg may already be gone. // ffmpeg may already be gone.
} }
+1 -1
View File
@@ -12,7 +12,7 @@ export interface MediaPlayerLike {
codecData?: { duration?: string } | null; codecData?: { duration?: string } | null;
paused: boolean; paused: boolean;
playing: boolean; playing: boolean;
fProc?: { kill(signal?: string): void } | null; fProc?: { kill(signal?: string): void; removeAllListeners(event?: string): void } | null;
originStream?: { destroy(): void } | null; originStream?: { destroy(): void } | null;
playStream(input: Readable | string, inputOptions?: string[]): Promise<void>; playStream(input: Readable | string, inputOptions?: string[]): Promise<void>;
pause(): void; pause(): void;
+4
View File
@@ -47,6 +47,10 @@ async function main(): Promise<void> {
process.on("SIGINT", () => void shutdown("SIGINT")); process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("SIGTERM", () => void shutdown("SIGTERM")); process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("unhandledRejection", (err) => logger.error({ err }, "unhandled rejection")); process.on("unhandledRejection", (err) => logger.error({ err }, "unhandled rejection"));
// revoice.js throws from async callbacks we cannot wrap (its ffmpeg teardown
// in particular). Dying there would drop the bot out of the voice channel
// mid-track, so we log loudly and keep serving instead.
process.on("uncaughtException", (err) => logger.error({ err }, "uncaught exception, continuing"));
} }
main().catch((err) => { main().catch((err) => {