import {
Client,
GatewayIntentBits,
Partials,
} from 'discord.js';
let client: Client | null = null;
let isReady = false;
/**
* Initialize and return the Discord client
*/
export async function getDiscordClient(): Promise<Client> {
if (client && isReady) {
return client;
}
const token = process.env.DISCORD_BOT_TOKEN;
if (!token) {
throw new Error('DISCORD_BOT_TOKEN environment variable is not set');
}
client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
Partials.GuildMember,
Partials.User,
],
});
return new Promise((resolve, reject) => {
client!.once('ready', () => {
isReady = true;
console.error(`Discord client ready as ${client!.user?.tag}`);
resolve(client!);
});
client!.once('error', (error) => {
reject(error);
});
client!.login(token).catch(reject);
});
}
/**
* Check if the Discord client is ready
*/
export function isClientReady(): boolean {
return isReady;
}
/**
* Get the current client instance (may not be ready)
*/
export function getClientInstance(): Client | null {
return client;
}
/**
* Destroy the Discord client connection
*/
export async function destroyClient(): Promise<void> {
if (client) {
client.destroy();
client = null;
isReady = false;
}
}