I'm currently programming a discord bot in module type, and the problem with the reload command is that the import doesn't notice the file changes.
Folder structure (only what relevant)
application
├── src
│ ├── handlers
│ │ └── commands.js
│ └── commands
│ └── reload.js
commands.js
import { readdirSync } from 'fs';
async function reloadCommands(client) {
await client.commands.clear();
await client.aliases.clear();
const commandFiles = readdirSync('./src/commands').filter(file => file.endsWith('.js'));
for (let i = 0; i < commandFiles.length; i ) {
const cmd = await import(`../commands/${commandFiles[i]}`);
await client.commands.set(cmd.default.name, cmd.default);
console.log(`[COMMAND] Reloaded ${commandFiles[i]} with command ${cmd.default.name}${cmd.default.aliases}`);
if (cmd.default.aliases) {
cmd.default.aliases.forEach(async (alias) => {
await client.aliases.set(alias, cmd.default);
});
}
}
return commandFiles.length;
}
export default { loadCommands, reloadCommands };
reload.js
import commandHandler from '../handlers/commands.js';
export default {
name: 'reload',
description: 'Reloads all commands',
aliases: ['rl'],
async execute(message, args, client) {
try {
let cmd = await commandHandler.reloadCommands(client);
message.reply(`${cmd} commands have been reloaded!`);
} catch (error) {
console.log(error);
}
}
};
Node v18.9.0
I googled but found nothing that helps me
CodePudding user response:
I'm not sure where loadCommands
is defined, but I would personally reapproach the way I wrote the function for reloading commands.
import { readdirSync } from 'fs';
async function reloadCommands(client)
{
const commandFolders = readdirSync('./commands');
for (const folder of commandFolders)
{
const commandFiles = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles)
{
const command = require
(`../commands/${folder}/${file}`);
client.commands.set(command.name, command);
console.log(`Command ${command.name} loaded!`);
}
}
console.log('All commands loaded!');
}
export default { loadCommands, reloadCommands }
And the approach I would take for reload.js
import commandHandler from './handlers/commands.js';
export default {
name: 'reload',
description: 'Reloads all commands',
async execute(message, args)
{
if (message.author.id !== 'your id')
{
return message.channel.send('You don\'t have permission to use this command!');
}
await commandHandler.reloadCommands(message.client);
message.channel.send('All commands reloaded!');
}
}
Try seeing if there's a difference between this and the other.
CodePudding user response:
I found a solution for me, if I import the commands with searchParams the cache is not used.
No idea if this causes any memory leaks
const cmd = await import(`../commands/${commandFiles[i]}?${Date.now()}`);
await client.commands.set(cmd.default.name, cmd.default);