Compare commits

..

5 Commits

15 changed files with 379 additions and 227 deletions

View File

@@ -3,24 +3,22 @@ FROM node:23-alpine AS builder
WORKDIR /app
# Install pnpm and necessary build tools (if native modules are used)
# Install pnpm and necessary build tools
RUN apk add --no-cache python3 make g++ pnpm
# Copy package manifests
# First copy all config files
COPY tsconfig.json tsconfig.deploy.json ./
COPY package.json pnpm-lock.yaml ./
# Install ALL dependencies (including devDependencies needed for build)
# Now copy source code
COPY src/ ./src/
COPY deploy-commands.ts ./
# Install dependencies AFTER copying config files
RUN pnpm install --frozen-lockfile
# Copy the rest of the source code
COPY . .
# Compile TypeScript
RUN pnpm run build
# Prune devDependencies after build (optional but good practice)
RUN pnpm prune --prod
# Build the TypeScript code directly
RUN npx tsc -p tsconfig.json && npx tsc -p tsconfig.deploy.json
# ---- Production Stage ----
FROM node:23-alpine
@@ -29,17 +27,17 @@ WORKDIR /app
ENV NODE_ENV=production
# Copy necessary files from the builder stage
COPY --from=builder /app/node_modules ./node_modules
# Copy application files
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./package.json
# Copy other runtime necessities (adjust if needed)
# COPY .env.example ./
# COPY application.yml ./
# COPY plugins ./plugins
COPY --from=builder /app/pnpm-lock.yaml ./pnpm-lock.yaml
COPY application.yml ./application.yml
COPY plugins ./plugins
# Expose port if needed (though likely not for a Discord bot)
# EXPOSE 3000
# Install production dependencies only
# Temporarily disable the prepare script by setting npm_config_ignore_scripts
RUN apk add --no-cache pnpm && \
npm_config_ignore_scripts=true pnpm install --prod --frozen-lockfile
# Run the compiled JavaScript application
CMD ["node", "dist/index.js"]

View File

@@ -1,7 +1,7 @@
import { REST, Routes, APIApplicationCommand } from "discord.js";
import fs from "node:fs";
import path from "node:path";
import logger from "./src/utils/logger"; // Use default import now
import logger from "./src/utils/logger.js"; // Added .js extension for ES modules
import dotenv from "dotenv";
// --- Setup ---
@@ -33,8 +33,9 @@ const loadCommandsForDeployment = async () => {
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
try {
// Use dynamic import
const commandModule = await import(filePath);
// Use dynamic import with file:// protocol for ES modules
const fileUrl = new URL(`file://${filePath}`);
const commandModule = await import(fileUrl.href);
// Assuming commands export default or have a 'default' property
const command = commandModule.default || commandModule;

View File

@@ -1,16 +1,18 @@
{
"name": "discord-music-bot",
"name": "discord-music-bot",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "dist/index.js",
"type": "module",
"scripts": {
"build": "tsc",
"build": "tsc -p tsconfig.json",
"build:deploy": "tsc -p tsconfig.deploy.json",
"build:all": "npm run build && npm run build:deploy",
"start": "node dist/index.js",
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"lint": "eslint .",
"format": "prettier --write src/**/*.ts deploy-commands.ts",
"prepare": "npm run build"
"prepare": "npm run build:all"
},
"keywords": [],
"author": "",

60
scripts/fix-imports.cjs Executable file
View File

@@ -0,0 +1,60 @@
const fs = require('fs');
const path = require('path');
// Get all TypeScript files in a directory recursively
function getTypeScriptFiles(dir) {
const files = [];
function traverse(currentDir) {
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
traverse(fullPath);
} else if (entry.isFile() && entry.name.endsWith('.ts')) {
files.push(fullPath);
}
}
}
traverse(dir);
return files;
}
// Fix imports in a file
function fixImportsInFile(filePath) {
console.log(`Processing ${filePath}`);
let content = fs.readFileSync(filePath, 'utf8');
// Regular expression to match relative imports without file extensions
const importRegex = /(import\s+(?:[^'"]*\s+from\s+)?['"])(\.\.[^'"]*?)(['"])/g;
// Add .js extension to relative imports
content = content.replace(importRegex, (match, start, importPath, end) => {
// Don't add extension if it already has one or ends with a directory
if (importPath.endsWith('.js') || importPath.endsWith('/')) {
return match;
}
return `${start}${importPath}.js${end}`;
});
fs.writeFileSync(filePath, content);
}
// Main function
function main() {
const srcDir = path.join(__dirname, '..', 'src');
const files = getTypeScriptFiles(srcDir);
console.log(`Found ${files.length} TypeScript files`);
for (const file of files) {
fixImportsInFile(file);
}
console.log('Done');
}
main();

60
scripts/fix-imports.js Executable file
View File

@@ -0,0 +1,60 @@
const fs = require('fs');
const path = require('path');
// Get all TypeScript files in a directory recursively
function getTypeScriptFiles(dir) {
const files = [];
function traverse(currentDir) {
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
traverse(fullPath);
} else if (entry.isFile() && entry.name.endsWith('.ts')) {
files.push(fullPath);
}
}
}
traverse(dir);
return files;
}
// Fix imports in a file
function fixImportsInFile(filePath) {
console.log(`Processing ${filePath}`);
let content = fs.readFileSync(filePath, 'utf8');
// Regular expression to match relative imports without file extensions
const importRegex = /(import\s+(?:[^'"]*\s+from\s+)?['"])(\.\.[^'"]*?)(['"])/g;
// Add .js extension to relative imports
content = content.replace(importRegex, (match, start, importPath, end) => {
// Don't add extension if it already has one or ends with a directory
if (importPath.endsWith('.js') || importPath.endsWith('/')) {
return match;
}
return `${start}${importPath}.js${end}`;
});
fs.writeFileSync(filePath, content);
}
// Main function
function main() {
const srcDir = path.join(__dirname, '..', 'src');
const files = getTypeScriptFiles(srcDir);
console.log(`Found ${files.length} TypeScript files`);
for (const file of files) {
fixImportsInFile(file);
}
console.log('Done');
}
main();

View File

@@ -2,24 +2,21 @@ import {
SlashCommandBuilder,
PermissionFlagsBits,
ChannelType,
ChatInputCommandInteraction, // Import the specific _interaction type
GuildMember, // Import GuildMember type
VoiceBasedChannel, // Import VoiceBasedChannel type
ChatInputCommandInteraction,
GuildMember,
VoiceBasedChannel,
} from "discord.js";
import logger from "../utils/logger"; // Use default import
import { BotClient } from "../index"; // Import the BotClient interface
import { Player } from "shoukaku"; // Import the Player type explicitly
import logger from "../utils/logger.js";
import { BotClient } from "../index.js";
import { Player } from "shoukaku";
export default {
// Use export default for ES Modules
data: new SlashCommandBuilder()
.setName("join")
.setDescription("Joins your current voice channel"),
async execute(_interaction: ChatInputCommandInteraction, _client: BotClient) {
// Add types
// Ensure command is run in a guild
if (!_interaction.guildId || !_interaction.guild || !_interaction.channelId) {
// Reply might fail if _interaction is already replied/deferred, use editReply if needed
return _interaction
.reply({ content: "This command can only be used in a server.", ephemeral: true })
.catch(() => {});
@@ -46,9 +43,8 @@ export default {
const currentVoiceChannel = voiceChannel as VoiceBasedChannel;
// 2. Check bot permissions
const permissions = currentVoiceChannel.permissionsFor(_client.user!); // Use non-null assertion for _client.user
const permissions = currentVoiceChannel.permissionsFor(_client.user!);
if (!permissions?.has(PermissionFlagsBits.Connect)) {
// Optional chaining for permissions
return _interaction.editReply("I need permission to **connect** to your voice channel!");
}
if (!permissions?.has(PermissionFlagsBits.Speak)) {
@@ -67,77 +63,65 @@ export default {
}
// 3. Get or create the player and connect using Shoukaku
// Correctly get player from the players map and type it
let player: Player | undefined = shoukaku.players.get(_interaction.guildId);
if (!player) {
// First, ensure clean state by disconnecting if already connected
if (player) {
try {
// Create player using the Shoukaku manager
logger.info(`Destroying existing player for guild ${_interaction.guildId} before reconnecting`);
await player.destroy();
player = undefined;
} catch (error) {
logger.warn(`Error destroying existing player: ${error}`);
// Continue with connection attempt anyway
}
}
// Attempt to join voice channel with retry logic
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
attempts++;
try {
// Wait a short time between retries to allow Discord's voice state to update
if (attempts > 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
logger.info(`Attempt ${attempts} to join voice channel ${currentVoiceChannel.id}`);
}
player = await shoukaku.joinVoiceChannel({
guildId: _interaction.guildId,
channelId: currentVoiceChannel.id,
shardId: _interaction.guild.shardId, // Get shardId from guild
shardId: _interaction.guild.shardId,
deaf: true // Set to true to avoid listening to voice data, saves bandwidth
});
logger.info(
`Created player and connected to voice channel ${currentVoiceChannel.name} (${currentVoiceChannel.id}) in guild ${_interaction.guild.name} (${_interaction.guildId})`,
);
// Connection was successful
await _interaction.editReply(`Joined ${currentVoiceChannel.name}! Ready to play music.`);
return;
} catch (error: unknown) {
// Type error as unknown
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error(
`Failed to create/connect player for guild ${_interaction.guildId}: ${errorMessage}`,
`Attempt ${attempts}: Failed to connect to voice channel for guild ${_interaction.guildId}: ${errorMessage}`,
error,
);
// Attempt to leave voice channel if connection failed partially
shoukaku.leaveVoiceChannel(_interaction.guildId).catch((e: unknown) => {
// Type catch error
const leaveErrorMsg = e instanceof Error ? e.message : String(e);
logger.error(`Error leaving VC after failed join: ${leaveErrorMsg}`);
});
return _interaction.editReply("An error occurred while trying to join the voice channel.");
}
} else {
// If player exists, get the corresponding connection
const connection = shoukaku.connections.get(_interaction.guildId);
// Check if connection exists and if it's in a different channel
if (!connection || connection.channelId !== currentVoiceChannel.id) {
// Clean up any partial connections on failure
try {
// Rejoining should handle moving the bot
// Note: joinVoiceChannel might implicitly destroy the old player/connection if one exists for the guild.
// If issues arise, explicitly call leaveVoiceChannel first.
player = await shoukaku.joinVoiceChannel({
guildId: _interaction.guildId,
channelId: currentVoiceChannel.id,
shardId: _interaction.guild.shardId,
});
logger.info(
`Moved player to voice channel ${currentVoiceChannel.name} (${currentVoiceChannel.id}) in guild ${_interaction.guildId}`,
);
await _interaction.editReply(`Moved to ${currentVoiceChannel.name}!`);
} catch (error: unknown) {
// Type error as unknown
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error(
`Failed to move player for guild ${_interaction.guildId}: ${errorMessage}`,
error,
);
return _interaction.editReply(
"An error occurred while trying to move to the voice channel.",
);
await shoukaku.leaveVoiceChannel(_interaction.guildId);
} catch (leaveError) {
// Ignore leave errors
}
if (attempts === maxAttempts) {
return _interaction.editReply(`Failed to join voice channel after ${maxAttempts} attempts. Please try again later.`);
}
} else {
// Already in the correct channel
await _interaction.editReply(`I'm already in ${currentVoiceChannel.name}!`);
}
// Example of updating a manually managed text channel context (if needed)
// if (player.textChannelId !== _interaction.channelId) {
// player.textChannelId = _interaction.channelId;
// logger.debug(`Updated player text channel context to ${_interaction.channel?.name} (${_interaction.channelId}) in guild ${_interaction.guildId}`);
// }
}
},
};

View File

@@ -3,8 +3,8 @@ import {
ChatInputCommandInteraction, // Import the specific _interaction type
GuildMember, // Import GuildMember type
} from "discord.js";
import logger from "../utils/logger"; // Use default import
import { BotClient } from "../index"; // Import the BotClient interface
import logger from "../utils/logger.js"; // Use default import
import { BotClient } from "../index.js"; // Import the BotClient interface
// No need to import Player explicitly if we just check connection
export default {

View File

@@ -8,8 +8,8 @@ import {
GuildMember,
VoiceBasedChannel,
} from "discord.js";
import logger from "../utils/logger";
import { BotClient } from "../index";
import logger from "../utils/logger.js";
import { BotClient } from "../index.js";
// Import necessary Shoukaku types - LavalinkResponse might need a local definition if not exported
import { Player, Node, Track, SearchResult, Connection } from "shoukaku";
@@ -180,34 +180,75 @@ export default {
player = shoukaku.players.get(_interaction.guildId) as GuildPlayer | undefined;
const connection = shoukaku.connections.get(_interaction.guildId);
// Check if we need to join or move to a different channel
if (!player || !connection || connection.channelId !== currentVoiceChannel.id) {
// If player/connection doesn't exist or bot is in wrong channel, join/move
try {
player = (await shoukaku.joinVoiceChannel({
guildId: _interaction.guildId,
channelId: currentVoiceChannel.id,
shardId: _interaction.guild.shardId,
})) as GuildPlayer; // Cast to extended type
logger.info(
`Joined/Moved to voice channel ${currentVoiceChannel.name} (${currentVoiceChannel.id}) for play command.`,
);
// Initialize queue if it's a new player
if (!player.queue) {
player.queue = [];
// If existing player, destroy it for a clean slate
if (player) {
try {
logger.info(`Destroying existing player for guild ${_interaction.guildId} before reconnecting`);
await player.destroy();
player = undefined;
} catch (error) {
logger.warn(`Error destroying existing player: ${error}`);
// Continue with connection attempt anyway
}
}
// Attempt to join voice channel with retry logic
let attempts = 0;
const maxAttempts = 3;
let joinSuccess = false;
while (attempts < maxAttempts && !joinSuccess) {
attempts++;
try {
// Wait a short time between retries to allow Discord's voice state to update
if (attempts > 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
logger.info(`Attempt ${attempts} to join voice channel ${currentVoiceChannel.id}`);
}
player = (await shoukaku.joinVoiceChannel({
guildId: _interaction.guildId,
channelId: currentVoiceChannel.id,
shardId: _interaction.guild.shardId,
deaf: true // Set to true to avoid listening to voice data, saves bandwidth
})) as GuildPlayer;
// Initialize queue if it's a new player
if (!player.queue) {
player.queue = [];
}
player.textChannelId = _interaction.channelId; // Store text channel context
logger.info(
`Joined/Moved to voice channel ${currentVoiceChannel.name} (${currentVoiceChannel.id}) for play command.`,
);
joinSuccess = true;
} catch (joinError: unknown) {
const errorMsg = joinError instanceof Error ? joinError.message : String(joinError);
logger.error(
`Attempt ${attempts}: Failed to join voice channel for guild ${_interaction.guildId}: ${errorMsg}`,
joinError,
);
// Clean up any partial connections on failure
try {
await shoukaku.leaveVoiceChannel(_interaction.guildId);
} catch (leaveError) {
// Ignore leave errors
}
if (attempts === maxAttempts) {
return _interaction.editReply(
"Failed to join the voice channel after multiple attempts. Please try again later."
);
}
}
player.textChannelId = _interaction.channelId; // Store text channel context
} catch (joinError: unknown) {
const errorMsg = joinError instanceof Error ? joinError.message : String(joinError);
logger.error(
`Failed to join/move player for guild ${_interaction.guildId}: ${errorMsg}`,
joinError,
);
shoukaku.leaveVoiceChannel(_interaction.guildId).catch(() => {}); // Attempt cleanup
return _interaction.editReply(
"An error occurred while trying to join the voice channel.",
);
}
} else {
// We already have a player connected to the right channel
// Ensure queue exists if player was retrieved
if (!player.queue) {
player.queue = [];
@@ -271,10 +312,9 @@ export default {
responseEmbed
.setTitle("Track Added to Queue")
.setDescription(`[${track.info.title}](${track.info.uri})`)
// Ensure player exists before accessing queue
.addFields({
name: "Position in queue",
value: `${player.queue.length + 1}`,
value: `${player?.queue?.length ?? 0 + 1}`, // Add null checks
inline: true,
});
if (track.info.artworkUrl) responseEmbed.setThumbnail(track.info.artworkUrl); // Use artworkUrl
@@ -298,7 +338,7 @@ export default {
.setDescription(`[${track.info.title}](${track.info.uri})`)
.addFields({
name: "Position in queue",
value: `${player.queue.length + 1}`,
value: `${player?.queue?.length ?? 0 + 1}`, // Add null checks
inline: true,
});
if (track.info.artworkUrl) responseEmbed.setThumbnail(track.info.artworkUrl);

View File

@@ -1,6 +1,6 @@
import { Events, Interaction } from "discord.js";
import { BotClient } from "../types/botClient";
import logger from "../utils/logger";
import { BotClient } from "../types/botClient.js";
import logger from "../utils/logger.js";
export default {
name: Events.InteractionCreate,

View File

@@ -1,7 +1,7 @@
import { Events, ActivityType, Client } from "discord.js"; // Import base Client type
import logger from "../utils/logger"; // Use default import
import { initializeShoukaku } from "../structures/ShoukakuEvents"; // Import the correct setup function
import { BotClient } from "../index"; // Import BotClient type
import logger from "../utils/logger.js"; // Use default import
import { initializeShoukaku } from "../structures/ShoukakuEvents.js"; // Import the correct setup function
import { BotClient } from "../index.js"; // Import BotClient type
export default {
// Use export default

View File

@@ -1,6 +1,6 @@
import { Events, VoiceState, ChannelType } from "discord.js"; // Added ChannelType
import logger from "../utils/logger";
import { BotClient } from "../index"; // Assuming BotClient is exported from index
import logger from "../utils/logger.js";
import { BotClient } from "../index.js"; // Assuming BotClient is exported from index
export default {
// Use export default for ES modules

View File

@@ -4,38 +4,40 @@ import {
GatewayIntentBits,
Collection,
Events,
BaseInteraction, // Use a base type for now, refine later if needed
SlashCommandBuilder, // Assuming commands use this
BaseInteraction,
SlashCommandBuilder,
} from "discord.js";
import { Shoukaku, Connectors, NodeOption, ShoukakuOptions } from "shoukaku";
import logger from "./utils/logger"; // Assuming logger uses export default or similar
import logger from "./utils/logger.js"; // Add .js extension
import fs from "fs";
import path from "path";
// import { fileURLToPath } from 'url'; // Needed for __dirname in ES Modules if module is not CommonJS
import { fileURLToPath } from 'url'; // Needed for __dirname in ES Modules
// Get __dirname equivalent in ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Define Command structure
interface Command {
data: Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup">; // Or appropriate type for your command data
execute: (_interaction: BaseInteraction, _client: BotClient) => Promise<void>; // Adjust _interaction type if needed
data: Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup">;
execute: (_interaction: BaseInteraction, _client: BotClient) => Promise<void>;
}
// Define Event structure
interface BotEvent {
name: string; // Should match discord.js event names or custom names
name: string;
once?: boolean;
execute: (..._args: any[]) => void; // Use specific types later if possible
execute: (..._args: any[]) => void;
}
// Extend the discord.js Client class to include custom properties
export interface BotClient extends Client {
// Add export keyword
commands: Collection<string, Command>;
shoukaku: Shoukaku;
}
// --- Setup ---
dotenv.config();
// __dirname is available in CommonJS modules, which is set in tsconfig.json
// Validate essential environment variables
if (!process.env.DISCORD_TOKEN) {
@@ -46,8 +48,6 @@ if (!process.env.LAVALINK_HOST || !process.env.LAVALINK_PORT || !process.env.LAV
logger.warn(
"Lavalink connection details (HOST, PORT, PASSWORD) are missing or incomplete in .env. Music functionality will be limited.",
);
// Decide if the bot should exit or continue without music
// process.exit(1); // Uncomment to exit if Lavalink is mandatory
}
// Create a new Discord _client instance with necessary intents
@@ -55,28 +55,27 @@ const _client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages, // Add if needed for prefix commands or message content
GatewayIntentBits.MessageContent, // Add if needed for message content
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
}) as BotClient; // Assert the type here
}) as BotClient;
// Define Shoukaku nodes
const Nodes: NodeOption[] = [
{
name: process.env.LAVALINK_NAME || "lavalink-node-1", // Use an env var or default name
url: `${process.env.LAVALINK_HOST || "localhost"}:${process.env.LAVALINK_PORT || 2333}`, // Use || 2333 for default port number
auth: process.env.LAVALINK_PASSWORD || "youshallnotpass", // Password from your Lavalink server config
secure: process.env.LAVALINK_SECURE === "true", // Set to true if using HTTPS/WSS
name: process.env.LAVALINK_NAME || "lavalink-node-1",
url: `${process.env.LAVALINK_HOST || "localhost"}:${process.env.LAVALINK_PORT || 2333}`,
auth: process.env.LAVALINK_PASSWORD || "youshallnotpass",
secure: process.env.LAVALINK_SECURE === "true",
},
];
// Shoukaku _options
const shoukakuOptions: ShoukakuOptions = {
moveOnDisconnect: false, // Whether to move players to another node when a node disconnects
resume: true, // Whether to resume players session after Lavalink restarts
reconnectTries: 3, // Number of attempts to reconnect to Lavalink
reconnectInterval: 5000, // Interval between reconnect attempts in milliseconds
// Add other _options as needed
moveOnDisconnect: false,
resume: true,
reconnectTries: 3,
reconnectInterval: 5000,
};
// Initialize Shoukaku
@@ -84,7 +83,7 @@ _client.shoukaku = new Shoukaku(new Connectors.DiscordJS(_client), Nodes, shouka
// Show the actual Lavalink connection details (without exposing the actual password)
logger.info(
`Lavalink connection configured to: ${process.env.LAVALINK_HOST}:${process.env.LAVALINK_PORT} (Password: ${process.env.LAVALINK_PASSWORD ? "[SET]" : "[NOT SET]"})`,
`Lavalink connection configured to: ${process.env.LAVALINK_HOST || "localhost"}:${process.env.LAVALINK_PORT || 2333} (Password: ${process.env.LAVALINK_PASSWORD ? "[SET]" : "[NOT SET]"})`,
);
// Collections for commands
@@ -92,16 +91,17 @@ _client.commands = new Collection<string, Command>();
// --- Command Loading ---
const commandsPath = path.join(__dirname, "commands");
// Read .ts files now
const commandFiles = fs.readdirSync(commandsPath).filter((file: string) => file.endsWith(".ts"));
// Read .js files instead of .ts after compilation
const commandFiles = fs.readdirSync(commandsPath).filter((file: string) => file.endsWith(".js"));
const loadCommands = async () => {
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
try {
// Use dynamic import for ES Modules/CommonJS interop
const commandModule = await import(filePath);
const command: Command = commandModule.default || commandModule; // Handle default exports
// Use dynamic import with file:// protocol for ES Modules
const fileUrl = new URL(`file://${filePath}`).href;
const commandModule = await import(fileUrl);
const command: Command = commandModule.default || commandModule;
if (command && typeof command === "object" && "data" in command && "execute" in command) {
_client.commands.set(command.data.name, command);
@@ -112,7 +112,6 @@ const loadCommands = async () => {
);
}
} catch (error: unknown) {
// Type the error as unknown
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error(`Error loading command at ${filePath}: ${errorMessage}`, error);
}
@@ -121,22 +120,24 @@ const loadCommands = async () => {
// --- Event Handling ---
const eventsPath = path.join(__dirname, "events");
// Read .ts files now
const eventFiles = fs.readdirSync(eventsPath).filter((file: string) => file.endsWith(".ts"));
// Read .js files instead of .ts after compilation
const eventFiles = fs.readdirSync(eventsPath).filter((file: string) => file.endsWith(".js"));
const loadEvents = async () => {
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
try {
const eventModule = await import(filePath);
const event: BotEvent = eventModule.default || eventModule; // Handle default exports
// Use dynamic import with file:// protocol for ES Modules
const fileUrl = new URL(`file://${filePath}`).href;
const eventModule = await import(fileUrl);
const event: BotEvent = eventModule.default || eventModule;
if (event && typeof event === "object" && "name" in event && "execute" in event) {
if (event.once) {
_client.once(event.name, (..._args: any[]) => event.execute(..._args, _client)); // Pass _client
_client.once(event.name, (..._args: any[]) => event.execute(..._args, _client));
logger.info(`Loaded event ${event.name} (once)`);
} else {
_client.on(event.name, (..._args: any[]) => event.execute(..._args, _client)); // Pass _client
_client.on(event.name, (..._args: any[]) => event.execute(..._args, _client));
logger.info(`Loaded event ${event.name}`);
}
} else {
@@ -161,7 +162,6 @@ _client.shoukaku.on("error", (name: string, error: Error) =>
_client.shoukaku.on("close", (name: string, code: number, reason: string | undefined) =>
logger.warn(`Lavalink Node: ${name} closed with code ${code}. Reason: ${reason || "No reason"}`),
);
// Corrected disconnect event signature based on common usage and error TS148
_client.shoukaku.on("disconnect", (name: string, count: number) => {
logger.warn(
`Lavalink Node: ${name} disconnected. ${count} players were disconnected from this node.`,
@@ -180,7 +180,7 @@ async function main() {
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error(`Failed to log in: ${errorMessage}`);
process.exit(1); // Exit if login fails
process.exit(1);
}
}
@@ -197,6 +197,4 @@ process.on("unhandledRejection", (reason: unknown, promise: Promise<any>) => {
});
process.on("uncaughtException", (error: Error, origin: NodeJS.UncaughtExceptionOrigin) => {
logger.error(`Uncaught exception: ${error.message}`, { error, origin });
// Optional: exit process on critical uncaught exceptions
// process.exit(1);
});

View File

@@ -1,67 +1,66 @@
import { Shoukaku, NodeOption, ShoukakuOptions, Player, Connectors } from "shoukaku"; // Removed player event types, Added Connectors
// import { Connectors } from 'shoukaku-discord.js'; // Use the discord.js connector - Removed this line
import logger from "../utils/logger";
import { BotClient } from "../index";
import { Shoukaku, NodeOption, ShoukakuOptions, Player, Connectors } from 'shoukaku';
import logger from '../utils/logger.js';
import { BotClient } from '../index.js';
// Removed imports from play.ts for now as player listeners are removed
// Define Node _options (replace with your actual Lavalink details from .env)
// Define Node options (replace with your actual Lavalink details from .env)
const nodes: NodeOption[] = [
{
name: process.env.LAVALINK_NAME || "Lavalink-Node-1",
url: process.env.LAVALINK_URL || "lavalink:2333", // Use service name for Docker Compose if applicable
auth: process.env.LAVALINK_AUTH || "youshallnotpass",
secure: process.env.LAVALINK_SECURE === "true" || false,
},
{
name: process.env.LAVALINK_NAME || 'Lavalink-Node-1',
url: process.env.LAVALINK_URL || 'lavalink:2333', // Use service name for Docker Compose if applicable
auth: process.env.LAVALINK_AUTH || 'youshallnotpass',
secure: process.env.LAVALINK_SECURE === 'true' || false,
},
];
// Define Shoukaku _options
// Define Shoukaku options
const shoukakuOptions: ShoukakuOptions = {
moveOnDisconnect: false,
resume: false, // Resume doesn't work reliably across restarts/disconnects without session persistence
reconnectTries: 3,
reconnectInterval: 5, // In seconds
restTimeout: 15000, // In milliseconds
voiceConnectionTimeout: 15, // In seconds
moveOnDisconnect: false,
resume: false, // Resume doesn't work reliably across restarts/disconnects without session persistence
reconnectTries: 3,
reconnectInterval: 5, // In seconds
restTimeout: 15000, // In milliseconds
voiceConnectionTimeout: 15, // In seconds
};
// Function to initialize Shoukaku and attach listeners
export function initializeShoukaku(_client: BotClient): Shoukaku {
if (!_client) {
throw new Error("initializeShoukaku requires a _client instance.");
}
const shoukaku = new Shoukaku(new Connectors.DiscordJS(_client), nodes, shoukakuOptions);
// --- Shoukaku Node Event Listeners ---
shoukaku.on("ready", (name, resumed) =>
logger.info(`Lavalink Node '${name}' ready. Resumed: ${resumed}`),
);
shoukaku.on("error", (name, error) =>
logger.error(`Lavalink Node '${name}' error: ${error.message}`, error),
);
shoukaku.on("close", (name, code, reason) =>
logger.warn(`Lavalink Node '${name}' closed. Code: ${code}. Reason: ${reason || "No reason"}`),
);
// Fix: Correct disconnect listener signature
shoukaku.on("disconnect", (name, count) => {
// count = count of players disconnected from the node
logger.warn(`Lavalink Node '${name}' disconnected. ${count} players disconnected.`);
// If players were not moved, you might want to attempt to reconnect them or clean them up.
});
shoukaku.on("debug", (name, info) => {
// Only log debug messages if not in production or if explicitly enabled
if (process.env.NODE_ENV !== "production" || process.env.LAVALINK_DEBUG === "true") {
logger.debug(`Lavalink Node '${name}' debug: ${info}`);
export function initializeShoukaku(client: BotClient): Shoukaku {
if (!client) {
throw new Error("initializeShoukaku requires a client instance.");
}
});
// --- Shoukaku Player Event Listeners ---
// REMOVED - These need to be attached differently in Shoukaku v4 (e.g., when player is created)
const shoukaku = new Shoukaku(new Connectors.DiscordJS(client), nodes, shoukakuOptions);
logger.info("Shoukaku instance created and node event listeners attached.");
return shoukaku;
// --- Shoukaku Node Event Listeners ---
shoukaku.on('ready', (name, resumed) =>
logger.info(`Lavalink Node '${name}' ready. Resumed: ${resumed}`)
);
shoukaku.on('error', (name, error) =>
logger.error(`Lavalink Node '${name}' error: ${error.message}`, error)
);
shoukaku.on('close', (name, code, reason) =>
logger.warn(`Lavalink Node '${name}' closed. Code: ${code}. Reason: ${reason || 'No reason'}`)
);
// Fix: Correct disconnect listener signature
shoukaku.on('disconnect', (name, count) => {
// count = count of players disconnected from the node
logger.warn(`Lavalink Node '${name}' disconnected. ${count} players disconnected.`);
// If players were not moved, you might want to attempt to reconnect them or clean them up.
});
shoukaku.on('debug', (name, info) => {
// Only log debug messages if not in production or if explicitly enabled
if (process.env.NODE_ENV !== 'production' || process.env.LAVALINK_DEBUG === 'true') {
logger.debug(`Lavalink Node '${name}' debug: ${info}`);
}
});
// --- Shoukaku Player Event Listeners ---
// REMOVED - These need to be attached differently in Shoukaku v4 (e.g., when player is created)
logger.info("Shoukaku instance created and node event listeners attached.");
return shoukaku;
}

9
tsconfig.deploy.json Normal file
View File

@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"module": "NodeNext",
"moduleResolution": "NodeNext"
},
"include": ["deploy-commands.ts"]
}

View File

@@ -1,10 +1,11 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2020"],
"outDir": "dist",
"rootDir": ".",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
@@ -12,11 +13,11 @@
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"moduleResolution": "node"
"sourceMap": true,
"allowSyntheticDefaultImports": true
},
"include": [
"src/**/*",
"deploy-commands.ts"
"src/**/*"
],
"exclude": [
"node_modules",