mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
feat(open-protocol): add OpenProtocol v1 discovery and slash-command support
This commit is contained in:
1 parent
17008ae52e
commit
263c1ba6da
16 files changed
+1359
-183
No files matched your search
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseCommand, canRunCommand, isAdminCommand } from "./commands.js";
|
||||
import {
|
||||
parseCommand,
|
||||
parseCommandWithFallback,
|
||||
canRunCommand,
|
||||
isAdminCommand,
|
||||
} from "./commands.js";
|
||||
|
||||
describe("Command Parser", () => {
|
||||
it("parses simple command", () => {
|
||||
@@ -93,3 +98,31 @@ describe("canRunCommand", () => {
|
||||
expect(canRunCommand("clear", [], [6])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCommandWithFallback", () => {
|
||||
it("accepts both the configured primary prefix and slash fallback", () => {
|
||||
expect(parseCommandWithFallback("!play 晴天", "!")).toEqual({
|
||||
name: "play",
|
||||
args: "晴天",
|
||||
rawArgs: ["晴天"],
|
||||
flags: new Set(),
|
||||
});
|
||||
expect(parseCommandWithFallback("/play 晴天", "!")).toEqual({
|
||||
name: "play",
|
||||
args: "晴天",
|
||||
rawArgs: ["晴天"],
|
||||
flags: new Set(),
|
||||
});
|
||||
});
|
||||
|
||||
it("applies aliases on slash fallback and ignores bare slash", () => {
|
||||
expect(parseCommandWithFallback("/p 稻香", "!", { p: "play" })).toEqual({
|
||||
name: "play",
|
||||
args: "稻香",
|
||||
rawArgs: ["稻香"],
|
||||
flags: new Set(),
|
||||
});
|
||||
expect(parseCommandWithFallback("/", "!")).toBeNull();
|
||||
expect(parseCommandWithFallback("plain chat", "!")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,23 @@ export function parseCommand(
|
||||
};
|
||||
}
|
||||
|
||||
export function parseCommandWithFallback(
|
||||
message: string,
|
||||
primaryPrefix: string,
|
||||
aliases: Record<string, string> = {},
|
||||
fallbackPrefixes: readonly string[] = ["/"],
|
||||
): ParsedCommand | null {
|
||||
const direct = parseCommand(message, primaryPrefix, aliases);
|
||||
if (direct) return direct;
|
||||
|
||||
for (const fallback of fallbackPrefixes) {
|
||||
if (!fallback || fallback === primaryPrefix) continue;
|
||||
const parsed = parseCommand(message, fallback, aliases);
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isAdminCommand(commandName: string): boolean {
|
||||
return ADMIN_COMMANDS.has(commandName);
|
||||
}
|
||||
|
||||
@@ -1948,3 +1948,115 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance — OpenProtocol & slash command routing", () => {
|
||||
it("accepts / commands when commandPrefix is '!' and routes private replies to invokerId", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [] });
|
||||
ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) =>
|
||||
`ok:${parsed.name}:${parsed.args}`,
|
||||
);
|
||||
|
||||
const dm: TS3TextMessage = {
|
||||
invokerName: "FlSpeakUser",
|
||||
invokerId: "12",
|
||||
invokerUid: "uid-fl",
|
||||
message: "/play 晴天",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dm);
|
||||
|
||||
expect(ctx.executeCommand).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
await handleTextMessage.call(ctx, makeMsg("/now"));
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:");
|
||||
});
|
||||
|
||||
it("routes permission denied and execution errors privately when triggered via DM", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] });
|
||||
const dmStop: TS3TextMessage = {
|
||||
invokerName: "Guest",
|
||||
invokerId: "22",
|
||||
invokerUid: "uid-guest",
|
||||
message: "/stop",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dmStop);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith(COMMAND_DENIED_MESSAGE, 1, 22);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
const okCtx = makeGateCtx({ adminGroups: [] });
|
||||
okCtx.executeCommand = vi.fn(async () => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
await handleTextMessage.call(okCtx, { ...dmStop, message: "/play x" });
|
||||
expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22);
|
||||
});
|
||||
|
||||
it("wires connected, clientMoved, pluginCommand, and disconnected to openProtocol", () => {
|
||||
const tsClient = new EventEmitter() as EventEmitter & {
|
||||
getClientId(): number;
|
||||
};
|
||||
tsClient.getClientId = () => 99;
|
||||
const openProtocol = {
|
||||
scheduleAnnounce: vi.fn(),
|
||||
handlePluginCommand: vi.fn(async () => {}),
|
||||
reset: vi.fn(),
|
||||
};
|
||||
const ctx = {
|
||||
tsClient,
|
||||
openProtocol,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
autoPaused: false,
|
||||
idleTimer: null,
|
||||
idlePollTimer: null,
|
||||
jellyfinPollTimer: null,
|
||||
snapshotTimer: null,
|
||||
currentSourceIsSpotify: false,
|
||||
disconnectEmitted: false,
|
||||
_cancelIdleTimer: vi.fn(),
|
||||
_startIdlePoller: vi.fn(),
|
||||
_startJellyfinReportPoller: vi.fn(),
|
||||
unregisterManagedVoiceClient: vi.fn(),
|
||||
voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn(), handleVoiceActivity: vi.fn() },
|
||||
spotifyController: { stop: vi.fn() },
|
||||
player: { stop: vi.fn() },
|
||||
jellyfinReporter: undefined,
|
||||
queue: { clear: vi.fn() },
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
refreshOccupancy: vi.fn(async () => {}),
|
||||
profileManager: { onChannelMoved: vi.fn(async () => {}) },
|
||||
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
} as Record<string, any>;
|
||||
|
||||
(BotInstance.prototype as any).setupTsEvents.call(ctx);
|
||||
|
||||
tsClient.emit("connected");
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
|
||||
|
||||
tsClient.emit("clientMoved", { id: 5, targetChannelID: 10n });
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
|
||||
|
||||
tsClient.emit("clientMoved", { id: 99, targetChannelID: 10n });
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(2);
|
||||
|
||||
const pluginCmd = {
|
||||
name: "tsclient:commands",
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 5,
|
||||
invokerName: "User",
|
||||
invokerUid: "uid-user",
|
||||
};
|
||||
tsClient.emit("pluginCommand", pluginCmd);
|
||||
expect(openProtocol.handlePluginCommand).toHaveBeenCalledWith(pluginCmd);
|
||||
|
||||
tsClient.emit("disconnected");
|
||||
expect(openProtocol.reset).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+42
-8
@@ -2,15 +2,17 @@ import { EventEmitter } from "node:events";
|
||||
import {
|
||||
TS3Client,
|
||||
type TS3ClientOptions,
|
||||
type TS3PluginCommand,
|
||||
type TS3TextMessage,
|
||||
type TS3VoiceActivity,
|
||||
type TS3VoiceSendFailure,
|
||||
} from "../ts-protocol/client.js";
|
||||
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import type { MusicProvider, Platform, Song } from "../music/provider.js";
|
||||
import {
|
||||
parseCommand,
|
||||
parseCommandWithFallback,
|
||||
canRunCommand,
|
||||
type ParsedCommand,
|
||||
} from "./commands.js";
|
||||
@@ -154,11 +156,27 @@ export interface BotStatus {
|
||||
effectiveDuration?: number;
|
||||
}
|
||||
|
||||
async function sendTextReply(
|
||||
tsClient: Pick<TS3Client, "sendTextMessage">,
|
||||
msg: TS3TextMessage,
|
||||
text: string,
|
||||
): Promise<void> {
|
||||
if (msg.targetMode === 1) {
|
||||
const targetClientId = Number(msg.invokerId);
|
||||
if (Number.isInteger(targetClientId) && targetClientId > 0) {
|
||||
await tsClient.sendTextMessage(text, 1, targetClientId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await tsClient.sendTextMessage(text);
|
||||
}
|
||||
|
||||
export class BotInstance extends EventEmitter {
|
||||
readonly id: string;
|
||||
name: string;
|
||||
|
||||
private tsClient: TS3Client;
|
||||
private openProtocol: OpenProtocolManager;
|
||||
private player: AudioPlayer;
|
||||
private voiceDucking: VoiceDuckingController;
|
||||
private managedVoiceClients: ManagedVoiceClientRegistry;
|
||||
@@ -230,6 +248,14 @@ export class BotInstance extends EventEmitter {
|
||||
this.avatarStore = options.avatarStore;
|
||||
|
||||
this.tsClient = new TS3Client(options.tsOptions, this.logger);
|
||||
this.openProtocol = new OpenProtocolManager({
|
||||
transport: this.tsClient,
|
||||
getConfig: () => ({
|
||||
locale: this.config.locale,
|
||||
commandPrefix: this.config.commandPrefix,
|
||||
}),
|
||||
logger: this.logger,
|
||||
});
|
||||
this.player = new AudioPlayer(this.logger);
|
||||
this.voiceDucking = new VoiceDuckingController(
|
||||
this.player,
|
||||
@@ -446,6 +472,12 @@ export class BotInstance extends EventEmitter {
|
||||
});
|
||||
});
|
||||
|
||||
this.tsClient.on("pluginCommand", (cmd: TS3PluginCommand) => {
|
||||
this.openProtocol?.handlePluginCommand(cmd).catch((err) => {
|
||||
this.logger.debug({ err }, "OpenProtocol plugin command handler failed");
|
||||
});
|
||||
});
|
||||
|
||||
this.tsClient.on("disconnected", () => {
|
||||
// Always reset local state — covers the case where connect() never
|
||||
// completed (hanging handshake → 60s library idle timeout) and
|
||||
@@ -453,6 +485,7 @@ export class BotInstance extends EventEmitter {
|
||||
// short-circuited on !this.connected, leaving player stuck as "playing".
|
||||
this.lifecycleGeneration++;
|
||||
this.connected = false;
|
||||
this.openProtocol?.reset();
|
||||
this._cancelIdleTimer();
|
||||
this.unregisterManagedVoiceClient(MANAGED_VOICE_CLIENT_RELEASE_GRACE_MS);
|
||||
this.voiceDucking.reset(true);
|
||||
@@ -487,6 +520,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.autoPaused = false;
|
||||
this._startIdlePoller();
|
||||
this._startJellyfinReportPoller();
|
||||
this.openProtocol?.scheduleAnnounce();
|
||||
});
|
||||
|
||||
this.tsClient.on("voiceActivity", (activity: TS3VoiceActivity) => {
|
||||
@@ -525,6 +559,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.profileManager.onChannelMoved(event.targetChannelID).catch((err) => {
|
||||
this.logger.warn({ err }, "Channel description move update failed");
|
||||
});
|
||||
this.openProtocol?.scheduleAnnounce();
|
||||
} else {
|
||||
this.voiceDucking.removeSpeaker(event.id);
|
||||
}
|
||||
@@ -667,6 +702,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.disconnectEmitted = true;
|
||||
this.emit("disconnected");
|
||||
}
|
||||
this.openProtocol?.reset();
|
||||
this.tsClient.disconnect();
|
||||
// Stop outbound PCM and initiate the TeamSpeak disconnect before removing
|
||||
// our id from the shared registry, minimizing the window in which another
|
||||
@@ -787,10 +823,10 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private async handleTextMessage(msg: TS3TextMessage): Promise<void> {
|
||||
const parsed = parseCommand(
|
||||
const parsed = parseCommandWithFallback(
|
||||
msg.message,
|
||||
this.config.commandPrefix,
|
||||
this.config.commandAliases
|
||||
this.config.commandAliases,
|
||||
);
|
||||
if (!parsed) return;
|
||||
|
||||
@@ -800,7 +836,7 @@ export class BotInstance extends EventEmitter {
|
||||
"Command denied: invoker not in adminGroups"
|
||||
);
|
||||
try {
|
||||
await this.tsClient.sendTextMessage(COMMAND_DENIED_MESSAGE);
|
||||
await sendTextReply(this.tsClient, msg, COMMAND_DENIED_MESSAGE);
|
||||
} catch (sendErr) {
|
||||
this.logger.error({ err: sendErr }, "Failed to send permission-denied message to chat");
|
||||
}
|
||||
@@ -818,15 +854,13 @@ export class BotInstance extends EventEmitter {
|
||||
// A single long reply (e.g. full lyrics) would exceed TeamSpeak's
|
||||
// per-message byte cap, so split it and send the chunks in order.
|
||||
for (const chunk of splitTextIntoChunks(response)) {
|
||||
await this.tsClient.sendTextMessage(chunk);
|
||||
await sendTextReply(this.tsClient, msg, chunk);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error({ err, command: parsed.name }, "Command execution error");
|
||||
try {
|
||||
await this.tsClient.sendTextMessage(
|
||||
`Error: ${(err as Error).message}`
|
||||
);
|
||||
await sendTextReply(this.tsClient, msg, `Error: ${(err as Error).message}`);
|
||||
} catch (sendErr) {
|
||||
this.logger.error({ err: sendErr }, "Failed to send error message to chat");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { Client, generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { BotProfileManager } from "./profile.js";
|
||||
import { TS6HttpQuery } from "../ts-protocol/http-query.js";
|
||||
import type { TS3Client } from "../ts-protocol/client.js";
|
||||
@@ -419,20 +418,15 @@ describe("BotProfileManager checked TS6 profile lifecycle", () => {
|
||||
|
||||
it("checks self clientupdate permission responses and retries only after reconnect", async () => {
|
||||
const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true });
|
||||
const client: any = new Client(generateIdentity(0), "127.0.0.1:9987", "Bot");
|
||||
const commands: string[] = [];
|
||||
client.handler.sendPacket = vi.fn((_type, data: Buffer) => {
|
||||
const command = data.toString();
|
||||
ts.execCommand.mockImplementation(async (command: string) => {
|
||||
commands.push(command);
|
||||
const returnCode = command.match(/return_code=(\d+)/)?.[1];
|
||||
client.handler.onPacket({ typeFlagged: 2, data: Buffer.from(`error id=2568 msg=insufficient\\sclient\\spermissions${returnCode ? ` return_code=${returnCode}` : ""}`) });
|
||||
throw new Error("insufficient client permissions (error id=2568)");
|
||||
});
|
||||
ts.sendCommandNoWait.mockImplementation((command: string) => client.sendCommandNoWait(command));
|
||||
ts.execCommand.mockImplementation((command: string) => client.execCommand(command));
|
||||
await pm.onSongChange(null);
|
||||
await pm.onSongChange(null);
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatch(/^clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放 return_code=\d+$/);
|
||||
expect(commands[0]).toBe("clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放");
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(logger.info.mock.calls.some((call: any[]) => call[1] === "Client properties updated (nickname + away)")).toBe(false);
|
||||
pm.onConnect();
|
||||
|
||||
Reference in new issue
Block a user