Dublicate shard. Many client instances for one shard.

Hello everyone, I'm using this code for a bot (https://github.com/iamnotacoder-djs/DiscordBotIda) and trying to run sharding (https://discordjs.guide/sharding/#when-to-shard). The problem is that due to the walk function in handlers/commands.js, as many client instances are created for one shard as there are commands in total. I assume that this is due to the recursive call to the walk function. If you remove
require(`./handlers/commands.js`).init(client);
require(`./handlers/commands.js`).init(client);
from index.js, then sharding works correctly, but commands do not work as logically. Maybe someone got stuck, tell me how to fix it? Thank you in advance Full code at the link to github: https://github.com/iamnotacoder-djs/DiscordBotIda This function with recursions:
async function walk(client, dir, slashes = []) {
if (Array.isArray(dir)) return slashes;
if ( !(await lstat(dir)).isDirectory() ) {
const cmdClass = require(`../${dir}`);
const cmd = new cmdClass();
if (cmd instanceof BaseCommand) {
client.commands.set(cmd.name, cmd);
if (cmd.type.includes(Config.CommandType.SLASH_APPLICATION))
slashes.push(cmd.slash);
}
return slashes;
}
for(let file of (await readdir(dir))) {
await walk(client, join(dir, file), slashes);
}
return slashes;
}
async function walk(client, dir, slashes = []) {
if (Array.isArray(dir)) return slashes;
if ( !(await lstat(dir)).isDirectory() ) {
const cmdClass = require(`../${dir}`);
const cmd = new cmdClass();
if (cmd instanceof BaseCommand) {
client.commands.set(cmd.name, cmd);
if (cmd.type.includes(Config.CommandType.SLASH_APPLICATION))
slashes.push(cmd.slash);
}
return slashes;
}
for(let file of (await readdir(dir))) {
await walk(client, join(dir, file), slashes);
}
return slashes;
}
[email protected] node.js v19.3.0 I would appreciate any help, thanks in advance!
GitHub
GitHub - iamnotacoder-djs/DiscordBotIda: Бот Ида не является финаль...
Бот Ида не является финальным продуктом. イド разрабатывается в рамках тестового полигона для обучающих видео по Discord.js. И не предназначен для использования на своих серверах. - GitHub - iamnotac...
discord.js Guide
Imagine a guide... that explores the many possibilities for your discord.js bot.
8 Replies
d.js toolkit
d.js toolkit2y ago
- What's your exact discord.js npm list discord.js and node node -v version? - Post the full error stack trace, not just the top part! - Show your code! - Explain what exactly your issue is. - Not a discord.js issue? Check out #useful-servers. - Issue solved? Press the button!
Kyanq
KyanqOP2y ago
index.js code:
const { ShardingManager } = require('discord.js');

const manager = new ShardingManager('./bot.js', {
token: process.env.TOKEN,
totalShards: 2,
mode: "worker"
});

manager.on('shardCreate', async (shard) => {
console.log(`Shard Launched ${shard.id}`)
shard.on('error', (error) => {
console.error(error)
})
});

manager.spawn().catch(e => console.log(e));
const { ShardingManager } = require('discord.js');

const manager = new ShardingManager('./bot.js', {
token: process.env.TOKEN,
totalShards: 2,
mode: "worker"
});

manager.on('shardCreate', async (shard) => {
console.log(`Shard Launched ${shard.id}`)
shard.on('error', (error) => {
console.error(error)
})
});

manager.spawn().catch(e => console.log(e));
bot.js code:
const {Client, Collection, IntentsBitField, GatewayIntentBits} = require("discord.js"),
client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates
]
})

require('dotenv').config()

global.Config = new ConfigUtil();
global.Log = new Logger();
client.commands = new Collection();

client.login(process.env.TOKEN)
.then(async () => {
await Log.init(client);
require(`./handlers/events.js`).init(client);

require(`./handlers/commands.js`).init(client);
});

client.on('error', Log.error)
client.on('warn', Log.error)
process.on('uncaughtException', Log.error);
process.on('unhandledRejection', Log.error);

module.exports = client;
const {Client, Collection, IntentsBitField, GatewayIntentBits} = require("discord.js"),
client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates
]
})

require('dotenv').config()

global.Config = new ConfigUtil();
global.Log = new Logger();
client.commands = new Collection();

client.login(process.env.TOKEN)
.then(async () => {
await Log.init(client);
require(`./handlers/events.js`).init(client);

require(`./handlers/commands.js`).init(client);
});

client.on('error', Log.error)
client.on('warn', Log.error)
process.on('uncaughtException', Log.error);
process.on('unhandledRejection', Log.error);

module.exports = client;
ok, sorry handlers/commands.js
const {lstat, readdir} = require('fs/promises'),
{join} = require('path'),
BaseCommand = require('../structures/BaseCommand');

module.exports.init = async (client) => {
Log.send(`[HANDLER/EVENTS] Хандлер Slash-комманд запущен.`);
const slashes = await walk(client, './commands/').catch(console.error);
client.application.commands.set(slashes)
.then(() => {
Log.send(`[HANDLER/COMMANDS] Установлено ${slashes.length} глобальных slash-комманд.`);
})
.catch((e) => {
Log.error(`[HANDLER/COMMANDS] Ошибка установки глобальных slash-комманд: ${e}`);
});
Log.send(`[HANDLER/COMMANDS] Загружено ${client.commands.size} комманд.`);
}

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('../structures/BaseCommand');

module.exports.init = async (client) => {
Log.send(`[HANDLER/EVENTS] Хандлер Slash-комманд запущен.`);
const slashes = await walk(client, './commands/').catch(console.error);
client.application.commands.set(slashes)
.then(() => {
Log.send(`[HANDLER/COMMANDS] Установлено ${slashes.length} глобальных slash-комманд.`);
})
.catch((e) => {
Log.error(`[HANDLER/COMMANDS] Ошибка установки глобальных slash-комманд: ${e}`);
});
Log.send(`[HANDLER/COMMANDS] Загружено ${client.commands.size} комманд.`);
}

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;
}
structures/BaseCommand.js: https://github.com/iamnotacoder-djs/DiscordBotIda/blob/master/structures/BaseCommand.js everything else is the same as on that github i changed only these 3 files: index.js, bot.js, handlers/commands.js yes, I just created bot.js, transferred the contents of index.js there, and wrote the code for creating shards in index.js. And I tried to fix the problem with creating multiple clients for one shard in commands.js do you mean this?
client.login(process.env.TOKEN)
.then(async () => {
await Log.init(client);
require(`./handlers/events.js`).init(client);
require(`./handlers/commands.js`).init(client);
});
client.login(process.env.TOKEN)
.then(async () => {
await Log.init(client);
require(`./handlers/events.js`).init(client);
require(`./handlers/commands.js`).init(client);
});
Syjalo
Syjalo2y ago
module.exports = client;
Kyanq
KyanqOP2y ago
I removed it, but it still launches repeatedly. Writes Shard Launched 0, Shard Launched 1 several times and restarts each time. Therefore, the bot responds to one command many times in the same shard
Syjalo
Syjalo2y ago
Don't use that template. It sucks
Kyanq
KyanqOP2y ago
thanks for the advice, and what template would you recommend, what should I strive for? I can see the structure close to the ideal somewhere?
Syjalo
Syjalo2y ago
If you want a framework use sapphire #useful-servers
Kyanq
KyanqOP2y ago
ok, thanks
Want results from more Discord servers?
Add your server