Files
JogyoGaori/src/handlers/commandHandler.js
2025-08-21 15:28:41 +09:00

76 lines
2.8 KiB
JavaScript

const { Collection } = require('discord.js');
const fs = require('fs');
const path = require('path');
const logger = require('../../modules/colorfulLogger');
const { commandPrefix } = require('../../config/constants');
const { getNameById } = require('../utils/discordUtils');
const cacheManager = require('../utils/cacheManager');
function loadCommands() {
const slashCommands = new Collection();
const legacyCommands = new Collection();
const commandFolders = fs.readdirSync(path.join(__dirname, '..', 'commands'));
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(path.join(__dirname, '..', 'commands', folder)).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
try {
const filePath = path.join(__dirname, '..', 'commands', folder, file);
const command = require(filePath);
// Load slash command part
if (command.data && command.execute) {
slashCommands.set(command.data.name, command);
}
// Load legacy command part
if (command.legacy) {
legacyCommands.set(command.legacy.name, command.legacy);
if (command.legacy.aliases) {
command.legacy.aliases.forEach(alias => {
legacyCommands.set(alias, command.legacy);
});
}
}
} catch (error) {
logger.error(`Error loading command from ${file}:`, error);
}
}
}
cacheManager.set('slashCommands', slashCommands);
cacheManager.set('legacyCommands', legacyCommands);
logger.info('All commands loaded and cached.');
}
async function handleCommand(message) {
if (!message.content.startsWith(commandPrefix) || message.author.bot) return;
const args = message.content.slice(commandPrefix.length).trim().split(/\s+/);
const commandName = args.shift().toLowerCase();
const legacyCommands = cacheManager.get('legacyCommands');
if (!legacyCommands) {
logger.error('Legacy commands not found in cache.');
return;
}
const command = legacyCommands.get(commandName);
if (!command) return;
const { author, guild } = message;
const userName = getNameById(message.client, author.id, guild);
logger.info(`Processing !${commandName} from ${userName} (${author.id}) in ${guild ? `guild ${guild.name} (${guild.id})` : 'DM'}`);
try {
await command.execute(message, args);
} catch (error) {
logger.error(`Error executing legacy command ${commandName}:`, error);
await message.reply('명령어 실행 중 오류가 발생했습니다.');
}
}
module.exports = { loadCommands, handleCommand };