Files
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

552 lines
17 KiB
TypeScript

/**
* `DiscordTestSuite` — a `TestSuite` run by the elizaOS plugin test runner that
* exercises live message send, voice, and attachment paths against a real
* Discord channel (`DISCORD_TEST_CHANNEL_ID`). Requires real credentials.
*/
import { Readable } from "node:stream";
import type { VoiceConnection } from "@discordjs/voice";
import {
type IAgentRuntime,
logger,
ModelType,
type TestSuite,
} from "@elizaos/core";
import {
AttachmentBuilder,
ChannelType,
Events,
type Guild,
Message,
type TextChannel,
} from "discord.js";
import type { DiscordService } from "./service";
import { ServiceType } from "./types";
import { sendMessageInChunks } from "./utils";
import { loadDiscordVoiceModule } from "./voice";
const TEST_IMAGE_URL =
"https://github.com/elizaOS/awesome-eliza/blob/main/assets/eliza-logo.jpg?raw=true";
/**
* Represents a test suite for Discord functionality.
* @class DiscordTestSuite
* @implements TestSuite
* @property {string} name - The name of the test suite
* @property {DiscordService | null} discordClient - The Discord client instance
* @property {Array<{ name: string; fn: (runtime: IAgentRuntime) => Promise<void> }>} tests - Array of test functions
*/
export class DiscordTestSuite implements TestSuite {
name = "discord";
private discordClient!: DiscordService; // Use definite assignment assertion
tests: { name: string; fn: (runtime: IAgentRuntime) => Promise<void> }[];
/**
* Constructor for initializing the tests array with test cases to be executed.
*
* @constructor
* @this {TestSuite}
*/
constructor() {
this.tests = [
{
name: "Initialize Discord Client",
fn: this.testCreatingDiscordClient.bind(this),
},
{
name: "Slash Commands - Join Voice",
fn: this.testJoinVoiceSlashCommand.bind(this),
},
{
name: "Voice Playback & TTS",
fn: this.testTextToSpeechPlayback.bind(this),
},
{
name: "Send Message with Attachments",
fn: this.testSendingTextMessage.bind(this),
},
{
name: "Handle Incoming Messages",
fn: this.testHandlingMessage.bind(this),
},
{
name: "Slash Commands - Leave Voice",
fn: this.testLeaveVoiceSlashCommand.bind(this),
},
];
}
/**
* Asynchronously tests the creation of Discord client using the provided runtime.
*
* @param {IAgentRuntime} runtime - The agent runtime used to obtain the Discord service.
* @returns {Promise<void>} - A Promise that resolves once the Discord client is ready.
* @throws {Error} - If an error occurs while creating the Discord client.
*/
async testCreatingDiscordClient(runtime: IAgentRuntime) {
try {
this.discordClient = runtime.getService(
ServiceType.DISCORD,
) as DiscordService;
if (!this.discordClient) {
throw new Error("Failed to get DiscordService from runtime.");
}
// Wait for the bot to be ready before proceeding
const discordClient = this.discordClient.client;
if (discordClient?.isReady()) {
logger.success("DiscordService is already ready.");
} else {
logger.info("Waiting for DiscordService to be ready...");
if (!discordClient) {
throw new Error(
"Discord client instance is missing within the service.",
);
}
await new Promise((resolve, reject) => {
if (discordClient) {
discordClient.once(Events.ClientReady, resolve);
discordClient.once(Events.Error, reject);
}
});
}
} catch (error) {
throw new Error(`Error in test creating Discord client: ${error}`);
}
}
/**
* Asynchronously tests the join voice slash command functionality.
*
* @param {IAgentRuntime} runtime - The runtime environment for the agent.
* @returns {Promise<void>} - A promise that resolves once the test is complete.
* @throws {Error} - If there is an error in executing the slash command test.
*/
async testJoinVoiceSlashCommand(runtime: IAgentRuntime) {
if (!this.discordClient) {
throw new Error("Discord client not initialized.");
}
try {
await this.waitForVoiceManagerReady(this.discordClient);
const channel = await this.getTestChannel(runtime);
if (!channel?.isTextBased()) {
throw new Error("Invalid test channel for slash command test.");
}
// Simulate a join channel slash command interaction
interface MockJoinInteraction {
isCommand: () => boolean;
commandName: string;
options: {
get: (name: string) => { value: string } | null;
};
guild: Guild;
deferReply: () => Promise<void>;
editReply: (message: string) => Promise<void>;
}
const testJoinInteraction: MockJoinInteraction = {
isCommand: () => true,
commandName: "joinchannel",
options: {
get: (name: string) =>
name === "channel" ? { value: channel.id } : null,
},
guild: (channel as TextChannel).guild,
deferReply: async () => {},
editReply: async (message: string) => {
logger.info(`JoinChannel Slash Command Response: ${message}`);
},
};
if (!this.discordClient.voiceManager) {
throw new Error("VoiceManager is not available on the Discord client.");
}
await this.discordClient.voiceManager.handleJoinChannelCommand(
testJoinInteraction,
);
logger.success("Join voice slash command test completed successfully.");
} catch (error) {
throw new Error(`Error in join voice slash commands test: ${error}`);
}
}
/**
* Asynchronously tests the leave voice channel slash command.
*
* @param {IAgentRuntime} runtime - The Agent Runtime instance.
* @returns {Promise<void>} A promise that resolves when the test is complete.
*/
async testLeaveVoiceSlashCommand(runtime: IAgentRuntime) {
if (!this.discordClient) {
throw new Error("Discord client not initialized.");
}
try {
await this.waitForVoiceManagerReady(this.discordClient);
const channel = await this.getTestChannel(runtime);
if (!channel?.isTextBased()) {
throw new Error("Invalid test channel for slash command test.");
}
// Simulate a leave channel slash command interaction
interface LeaveChannelInteraction {
guildId: string | null;
reply: (message: string) => Promise<void>;
}
const testLeaveInteraction: LeaveChannelInteraction = {
guildId: (channel as TextChannel).guildId,
reply: async (message: string) => {
logger.info(`LeaveChannel Slash Command Response: ${message}`);
},
};
if (!this.discordClient.voiceManager) {
throw new Error("VoiceManager is not available on the Discord client.");
}
await this.discordClient.voiceManager.handleLeaveChannelCommand(
testLeaveInteraction,
);
logger.success("Leave voice slash command test completed successfully.");
} catch (error) {
throw new Error(`Error in leave voice slash commands test: ${error}`);
}
}
/**
* Test Text to Speech playback.
* @param {IAgentRuntime} runtime - The Agent Runtime instance.
* @throws {Error} - If voice channel is invalid, voice connection fails to become ready, or no text to speech service found.
*/
async testTextToSpeechPlayback(runtime: IAgentRuntime) {
if (!this.discordClient) {
throw new Error("Discord client not initialized.");
}
try {
await this.waitForVoiceManagerReady(this.discordClient);
const channel = await this.getTestChannel(runtime);
if (!channel || channel.type !== ChannelType.GuildVoice) {
throw new Error("Invalid voice channel.");
}
if (!this.discordClient.voiceManager) {
throw new Error("VoiceManager is not available on the Discord client.");
}
await this.discordClient.voiceManager.joinChannel(channel);
const guild = await this.getActiveGuild(this.discordClient);
const guildId = guild.id;
if (!this.discordClient.voiceManager) {
throw new Error("VoiceManager is not available on the Discord client.");
}
const connection =
this.discordClient.voiceManager.getVoiceConnection(guildId);
if (!connection) {
throw new Error(`No voice connection found for guild: ${guildId}`);
}
try {
const { entersState, VoiceConnectionStatus } =
await loadDiscordVoiceModule();
await entersState(connection, VoiceConnectionStatus.Ready, 10_000);
logger.success(`Voice connection is ready in guild: ${guildId}`);
} catch (error) {
throw new Error(`Voice connection failed to become ready: ${error}`);
}
let responseStream = null;
try {
responseStream = await runtime.useModel(
ModelType.TEXT_TO_SPEECH,
`Hi! I'm ${runtime.character.name}! How are you doing today?`,
);
} catch (_error) {
throw new Error("No text to speech service found");
}
if (!responseStream) {
throw new Error("TTS response stream is null or undefined.");
}
await this.playAudioStream(
Readable.from(Buffer.from(responseStream as ArrayBuffer)),
connection,
);
} catch (error) {
throw new Error(`Error in TTS playback test: ${error}`);
}
}
/**
* Asynchronously tests sending a text message to a specified channel.
*
* @param {IAgentRuntime} runtime - The runtime for the agent.
* @returns {Promise<void>} A Promise that resolves when the message is sent successfully.
* @throws {Error} If there is an error in sending the text message.
*/
async testSendingTextMessage(runtime: IAgentRuntime) {
if (!this.discordClient) {
throw new Error("Discord client not initialized.");
}
try {
const channel = await this.getTestChannel(runtime);
if (!channel?.isTextBased()) {
throw new Error("Cannot send message to a non-text channel.");
}
const attachment = new AttachmentBuilder(TEST_IMAGE_URL);
await this.sendMessageToChannel(
channel as TextChannel,
"Testing Message",
[attachment],
);
} catch (error) {
throw new Error(`Error in sending text message: ${error}`);
}
}
/**
* Asynchronously handles sending a test message using the given runtime and mock user data.
*
* @param {IAgentRuntime} runtime - The agent runtime object.
* @returns {Promise<void>} A Promise that resolves once the message is handled.
*/
async testHandlingMessage(runtime: IAgentRuntime) {
if (!this.discordClient) {
throw new Error("Discord client not initialized.");
}
try {
const channel = await this.getTestChannel(runtime);
// Minimal fixture for the fields MessageManager reads in this smoke test.
interface MockMessage {
_cacheType: boolean;
_patch: () => void;
content: string;
author: {
id: string;
username: string;
bot: boolean;
};
channel: typeof channel;
id: string;
createdTimestamp: number;
mentions: {
has: (id: string) => boolean;
};
reference: { messageId?: string } | null;
attachments: unknown[];
interaction?: unknown;
}
const testMessageFields = {
_cacheType: true,
_patch: () => undefined,
content: `Hello, ${runtime.character.name}! How are you?`,
author: {
id: "mock-user-id",
username: "MockUser",
bot: false,
},
channel,
id: "mock-message-id",
createdTimestamp: Date.now(),
mentions: {
has: () => false,
},
reference: null,
attachments: [],
} satisfies MockMessage;
const testMessage = Object.assign(
Object.create(Message.prototype),
testMessageFields,
) as Message<boolean>;
if (!this.discordClient.messageManager) {
throw new Error(
"MessageManager is not available on the Discord client.",
);
}
await this.discordClient.messageManager.handleMessage(testMessage);
} catch (error) {
throw new Error(`Error in handling message test: ${error}`);
}
}
// #############################
// Utility Functions
// #############################
/**
* Asynchronously retrieves the test channel associated with the provided runtime.
*
* @param {IAgentRuntime} runtime - The runtime object containing necessary information.
* @returns {Promise<Channel>} The test channel retrieved from the Discord client.
* @throws {Error} If no test channel is found.
*/
async getTestChannel(runtime: IAgentRuntime) {
if (!this.discordClient) {
throw new Error("Discord client not initialized.");
}
const channelId = this.validateChannelId(runtime);
const discordClient = this.discordClient.client;
const channel =
discordClient && (await discordClient.channels.fetch(channelId));
if (!channel) {
throw new Error("no test channel found!");
}
return channel;
}
/**
* Async function to send a message to a text-based channel.
*
* @param {TextChannel} channel - The text-based channel the message is being sent to.
* @param {string} messageContent - The content of the message being sent.
* @param {AttachmentBuilder[]} files - An array of files to include in the message.
* @throws {Error} If the channel is not a text-based channel or does not exist.
* @throws {Error} If there is an error sending the message.
*/
async sendMessageToChannel(
channel: TextChannel,
messageContent: string,
files: AttachmentBuilder[],
) {
try {
if (!channel?.isTextBased()) {
throw new Error(
"Channel is not a text-based channel or does not exist.",
);
}
// Pass empty string for _inReplyTo as it expects a string
await sendMessageInChunks(
channel as TextChannel,
messageContent,
"",
files,
);
} catch (error) {
throw new Error(`Error sending message: ${error}`);
}
}
/**
* Play an audio stream from a given response stream using the provided VoiceConnection.
*
* @param responseStream - The response stream to play as audio.
* @param connection - The VoiceConnection to use for playing the audio.
* @returns A Promise that resolves when the TTS playback is finished.
*/
async playAudioStream(
responseStream: ReadableStream | NodeJS.ReadableStream | Readable,
connection: VoiceConnection,
) {
const {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior,
} = await loadDiscordVoiceModule();
const audioPlayer = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
const audioResource = createAudioResource(responseStream as Readable);
audioPlayer.play(audioResource);
connection.subscribe(audioPlayer);
logger.success("TTS playback started successfully.");
await new Promise<void>((resolve, reject) => {
audioPlayer.once(AudioPlayerStatus.Idle, () => {
logger.info("TTS playback finished.");
resolve();
});
audioPlayer.once("error", (error) => {
reject(error);
throw new Error(`TTS playback error: ${error}`);
});
});
}
/**
* Retrieves the active guild where the bot is currently connected to a voice channel.
*
* @param {DiscordService} discordClient The DiscordService instance used to interact with the Discord API.
* @returns {Promise<Guild>} The active guild where the bot is currently connected to a voice channel.
* @throws {Error} If no active voice connection is found for the bot.
*/
async getActiveGuild(discordClient: DiscordService) {
if (!discordClient.client) {
throw new Error("Discord client instance is missing within the service.");
}
const guilds = await discordClient.client.guilds.fetch();
const fullGuilds = await Promise.all(guilds.map((guild) => guild.fetch())); // Fetch full guild data
const activeGuild = fullGuilds.find((g) => {
const membersMe = g.members.me;
return membersMe?.voice?.channelId;
});
if (!activeGuild) {
throw new Error("No active voice connection found for the bot.");
}
return activeGuild;
}
/**
* Waits for the VoiceManager in the Discord client to be ready.
*
* @param {DiscordService} discordClient - The Discord client to check for VoiceManager readiness.
* @throws {Error} If the Discord client is not initialized.
* @returns {Promise<void>} A promise that resolves when the VoiceManager is ready.
*/
private async waitForVoiceManagerReady(discordClient: DiscordService) {
if (!discordClient) {
// This check might be redundant if called after the initial test setup check, but safe to keep.
throw new Error("Discord client is not initialized.");
}
if (!discordClient.voiceManager) {
throw new Error("VoiceManager is not available on the Discord client.");
}
const voiceManager = discordClient.voiceManager;
if (!voiceManager?.isReady()) {
await new Promise<void>((resolve, reject) => {
if (voiceManager) {
voiceManager.once("ready", resolve);
voiceManager.once("error", reject);
}
});
}
}
/**
* Validates the Discord test channel ID by checking if it is set in the runtime or environment variables.
* If the test channel ID is not set, an error is thrown.
*
* @param {IAgentRuntime} runtime The runtime object containing the settings and environment variables.
* @returns {string} The validated Discord test channel ID.
*/
private validateChannelId(runtime: IAgentRuntime) {
const testChannelId =
runtime.getSetting("DISCORD_TEST_CHANNEL_ID") ||
process.env.DISCORD_TEST_CHANNEL_ID;
if (!testChannelId) {
throw new Error(
"DISCORD_TEST_CHANNEL_ID is not set. Please provide a valid channel ID in the environment variables.",
);
}
return testChannelId as string; // Assert as string since we check for falsy above
}
}