Kyanq
Kyanq
DIAdiscord.js - Imagine an app
Created by Kyanq on 6/29/2023 in #djs-questions
duplicate client for shard
When connecting this file after authorization of the client with the line: require('commands.js').init(client); there is a problem with sharding. Duplicate client instances are created for the same shard. This way you get a lot of clients for one shard and the bot replies to one message many times. commands.js file code:
const {lstat, readdir} = require('fs/promises'),
{join} = require('path'),
BaseCommand = require('BaseCommand');

module.exports.init = async (client) => {
const slashes = await walk(client, './commands/').catch(console.error);
client.application.commands.set(slashes)
.then(() => {
Log.send(`${slashes.length} set to complex slash command.`);
})
.catch((e) => {
Log.error(`Error installing global slash commands: ${e}`);
});
}

async function walk(client, dir, slashes = []) {
const files = await readdir(dir);

for (const file of files) {
const filePath = join(dir, file);
const fileStat = await lstat(filePath);

if (fileStat.isDirectory()) {
await walk(client, filePath, slashes);
} else {
const cmdClass = require(`../${filePath}`);
const cmd = new cmdClass();

if (cmd instanceof BaseCommand && !client.commands.has(cmd.name)) {
client.commands.set(cmd.name, cmd);

if (cmd.type.includes(Config.CommandType.SLASH_APPLICATION)) {
slashes.push(cmd.slash.toJSON());
}
}
}
}

return slashes;
}
const {lstat, readdir} = require('fs/promises'),
{join} = require('path'),
BaseCommand = require('BaseCommand');

module.exports.init = async (client) => {
const slashes = await walk(client, './commands/').catch(console.error);
client.application.commands.set(slashes)
.then(() => {
Log.send(`${slashes.length} set to complex slash command.`);
})
.catch((e) => {
Log.error(`Error installing global slash commands: ${e}`);
});
}

async function walk(client, dir, slashes = []) {
const files = await readdir(dir);

for (const file of files) {
const filePath = join(dir, file);
const fileStat = await lstat(filePath);

if (fileStat.isDirectory()) {
await walk(client, filePath, slashes);
} else {
const cmdClass = require(`../${filePath}`);
const cmd = new cmdClass();

if (cmd instanceof BaseCommand && !client.commands.has(cmd.name)) {
client.commands.set(cmd.name, cmd);

if (cmd.type.includes(Config.CommandType.SLASH_APPLICATION)) {
slashes.push(cmd.slash.toJSON());
}
}
}
}

return slashes;
}
Without using sharding everything works correctly [email protected] node.js: v19.3.0
2 replies