Surface Stoat's voice errors and stop leaving orphan connections

Joining a channel failed silently: revoice's join() runs an async
executor inside `new Promise`, so a rejected join_call never reaches
reject() — the promise hangs forever and the real error escapes as an
unhandled rejection. The client wrapper now latches API failures and
settles the join itself, translating Stoat's error codes (AlreadyConnected,
LiveKitUnavailable, UnknownNode, ...) into messages the chat can show.

A failed join also used to leave the connection object alive, which kept
the bot registered in the channel and made the next attempt fail with
AlreadyConnected; it is now destroyed on any failure. The LiveKit node
name is configurable via VOICE_NODE for instances that renamed it, and
the README documents how to clear a stuck voice state from Redis.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Leonid Pershin
2026-09-08 23:40:21 +03:00
co-authored by Claude Opus 5
parent d4880e757e
commit 823a9f1565
6 changed files with 584 additions and 464 deletions
+4
View File
@@ -13,6 +13,10 @@ COMMAND_PREFIX=!
# Удалять сообщение с командой после её распознавания (нужно право ManageMessages).
DELETE_COMMAND_MESSAGES=true
# Имя LiveKit-ноды из Revolt.toml, секция [hosts.livekit].
# В стандартном self-hosted это "worldwide".
VOICE_NODE=worldwide
# ------------------------------------------------------------- Веб-панель ---
PORT=3005
HOST=0.0.0.0
+19 -1
View File
@@ -149,7 +149,25 @@ cd /opt/stoat-mbot && docker compose up -d --build && docker compose logs -f
резолвится в хост: `docker compose exec mbot node -e "fetch(process.env.STOAT_API_URL).then(r=>console.log(r.status))"`.
2. **`joining voice channel`, но нет `voice connection established`.** Значит `join_call` отдал
токен, а WebSocket до LiveKit не поднялся — смотрите, доступен ли `/livekit` через внешний домен.
3. **Бот в канале, но звука нет.** Это уже медиа-трафик: LiveKit анонсирует клиентам свой адрес
3. **`Stoat считает, что бот уже в этом голосовом канале` (`AlreadyConnected`).** Зависшее
состояние в Redis после падения бота: `join_call` регистрирует участника, а выйти он не успел.
Ботам API запрещает `force_disconnect`, поэтому чистим вручную — в каталоге инстанса:
```bash
docker compose exec redis valkey-cli --scan --pattern 'vc:*'
```
```bash
docker compose exec redis valkey-cli DEL 'vc:<ID_бота>'
```
```bash
docker compose exec redis valkey-cli SREM 'vc_members:<ID_голосового_канала>' '<ID_бота>'
```
В норме состояние снимает `voice-ingress` по вебхуку от LiveKit — если ситуация повторяется
после каждого перезапуска, смотрите `docker compose logs voice-ingress`.
4. **Бот в канале, но звука нет.** Это уже медиа-трафик: LiveKit анонсирует клиентам свой адрес
из `rtc.node_ip` / `use_external_ip` в `/opt/stoat/livekit.yml` и ждёт UDP на 50000-50100.
Если анонсируется внешний IP, а роутер не умеет NAT loopback, пакеты от контейнера до него не
дойдут. Тогда либо включите hairpin на роутере, либо запустите бота внутри compose-проекта
+2
View File
@@ -27,6 +27,8 @@ const schema = z.object({
STOAT_API_URL: z.string().url(),
STOAT_BOT_TOKEN: z.string().min(1),
COMMAND_PREFIX: z.string().min(1).default("!"),
/** LiveKit node name from Revolt.toml ([hosts.livekit]); self-hosted default is "worldwide". */
VOICE_NODE: z.string().min(1).default("worldwide"),
/** Remove the invoking message after a command is recognised. Needs ManageMessages. */
DELETE_COMMAND_MESSAGES: z
.enum(["true", "false"])
+2 -2
View File
@@ -11,7 +11,7 @@ import {
type Track,
} from "../types.js";
import { GuildPlayer, type Notice, type PositionUpdate } from "./player.js";
import { Revoice, type RevoiceLike } from "./revoice.js";
import { createRevoice, type RevoiceLike } from "./revoice.js";
const log = logger.child({ mod: "manager" });
@@ -64,7 +64,7 @@ export class MusicManager extends EventEmitter<ManagerEvents> {
constructor() {
super();
this.revoice = new Revoice(config.STOAT_BOT_TOKEN, { baseURL: config.STOAT_API_URL });
this.revoice = createRevoice(config.STOAT_BOT_TOKEN, config.STOAT_API_URL, config.VOICE_NODE);
}
attachStoat(context: StoatContext): void {
+23 -14
View File
@@ -146,20 +146,29 @@ export class GuildPlayer extends EventEmitter<GuildPlayerEvents> {
this.log.info({ channelId }, "joining voice channel");
const connection = await this.revoice.join(channelId);
// The room connects asynchronously inside revoice's constructor, so we wait
// for it to report readiness rather than polling a state getter.
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new UserFacingError("Не удалось подключиться к голосовому каналу")),
JOIN_TIMEOUT_MS,
);
const done = () => {
clearTimeout(timer);
resolve();
};
connection.once("join", done);
connection.once("roomfetched", done);
});
try {
// The room connects asynchronously inside revoice's constructor, so we wait
// for it to report readiness rather than polling a state getter.
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new UserFacingError("Не удалось подключиться к голосовому каналу")),
JOIN_TIMEOUT_MS,
);
const done = () => {
clearTimeout(timer);
resolve();
};
connection.once("join", done);
connection.once("roomfetched", done);
});
} catch (err) {
// Leave no orphan: an abandoned connection keeps the bot registered in the
// channel, and Stoat then refuses the next join with AlreadyConnected.
await connection.destroy().catch(() => {});
connection.removeAllListeners();
this.setStatus("idle");
throw err;
}
this.connection = connection;
this.voiceReady = true;
+87
View File
@@ -1,5 +1,6 @@
import { createRequire } from "node:module";
import type { Readable } from "node:stream";
import { UserFacingError } from "../types.js";
// revoice.js is CommonJS and its bundled typings lag behind the LiveKit rewrite,
// so we load it through require() and describe only the surface we rely on.
@@ -55,9 +56,95 @@ interface RevoiceModule {
const revoice = require("revoice.js") as RevoiceModule;
/** How long we wait for Stoat to answer POST /join_call before giving up. */
const JOIN_REQUEST_TIMEOUT_MS = 15_000;
export const Revoice = revoice.Revoice;
export const MediaPlayer = revoice.MediaPlayer;
interface RevoiceInternal extends RevoiceLike {
api: { post(path: string, body?: unknown, params?: unknown): Promise<unknown> };
}
/** Stoat error codes we can explain better than "internal error". */
const API_ERRORS: Record<string, string> = {
AlreadyConnected:
"Stoat считает, что бот уже в этом голосовом канале. Обычно это зависшее состояние после падения — см. README, раздел про AlreadyConnected.",
NotAVoiceChannel: "Это не голосовой канал",
LiveKitUnavailable: "Голосовой сервер (LiveKit) недоступен",
UnknownNode: "LiveKit-нода не найдена в конфигурации инстанса (Revolt.toml, [hosts.livekit])",
CannotJoinCall: "В канале достигнут лимит участников",
MissingPermission: "У бота нет права Connect в этом голосовом канале",
NotFound: "Канал не найден",
};
function describeApiError(err: unknown): Error {
const response = (err as { response?: { status?: number; data?: { type?: string } } }).response;
const type = response?.data?.type;
if (!type) return err as Error;
const message = API_ERRORS[type] ?? `Stoat отклонил запрос: ${type}`;
return new UserFacingError(message);
}
/**
* Wraps the revoice client so that join_call uses the configured LiveKit node
* and API failures surface Stoat's own error code instead of an axios dump.
*/
export function createRevoice(token: string, baseURL: string, node: string): RevoiceLike {
const instance = new Revoice(token, { baseURL }) as RevoiceInternal;
const post = instance.api.post.bind(instance.api);
const join = instance.join.bind(instance);
let pendingError: Error | null = null;
instance.api.post = async (path: string, body?: unknown, params?: unknown) => {
const payload =
path.endsWith("/join_call") && typeof body === "object" && body !== null
? { ...(body as Record<string, unknown>), node }
: body;
try {
return await post(path, payload, params);
} catch (err) {
pendingError = describeApiError(err);
throw pendingError;
}
};
// revoice's join() runs an async executor inside `new Promise`, so a failing
// join_call never reaches its reject() — the promise hangs forever and the
// real error escapes as an unhandled rejection. We latch that error above and
// settle the join ourselves.
instance.join = (channelId: string, leaveIfEmpty?: boolean | number) =>
new Promise<VoiceConnectionLike>((resolve, reject) => {
pendingError = null;
const startedAt = Date.now();
let settled = false;
const settle = (action: () => void) => {
if (settled) return;
settled = true;
clearInterval(watchdog);
action();
};
const watchdog = setInterval(() => {
if (pendingError) {
const error = pendingError;
settle(() => reject(error));
} else if (Date.now() - startedAt > JOIN_REQUEST_TIMEOUT_MS) {
settle(() => reject(new UserFacingError("Stoat не ответил на запрос подключения к каналу")));
}
}, 50);
watchdog.unref?.();
join(channelId, leaveIfEmpty).then(
(connection) => settle(() => resolve(connection)),
(err: unknown) => settle(() => reject(describeApiError(err))),
);
});
return instance;
}
/** Parses ffmpeg's `hh:mm:ss.xx` duration into seconds. */
export function parseFfmpegDuration(value: string | undefined | null): number {
if (!value) return 0;