Sharding Help

I want to increase my bot shard count to 2 but it is not working and there is no guide for that Only for auto guide is given
const { ShardingManager } = require('discord.js');
const { token } = require('./config.json');

const manager = new ShardingManager('./index.js', {
token,
totalShards: 'auto',
});

manager.on('shardCreate', shard => {
console.log(`πŸš€ Launched shard ${shard.id}`);

shard.on('death', process => {
console.warn(`πŸ’€ Shard ${shard.id} died (code: ${process.exitCode})`);
});

shard.on('exit', (code) => {
console.log(`πŸšͺ Shard ${shard.id} exited (code: ${code})`);
});
});

manager.spawn();
const { ShardingManager } = require('discord.js');
const { token } = require('./config.json');

const manager = new ShardingManager('./index.js', {
token,
totalShards: 'auto',
});

manager.on('shardCreate', shard => {
console.log(`πŸš€ Launched shard ${shard.id}`);

shard.on('death', process => {
console.warn(`πŸ’€ Shard ${shard.id} died (code: ${process.exitCode})`);
});

shard.on('exit', (code) => {
console.log(`πŸšͺ Shard ${shard.id} exited (code: ${code})`);
});
});

manager.spawn();
const client = new Client({ intents, shards: 'auto' });
const client = new Client({ intents, shards: 'auto' });
91 Replies
d.js toolkit
d.js toolkitβ€’4mo ago
Forever Gaming
Forever GamingOPβ€’4mo ago
@Inky I tried It is only spawning 1 Like I did from auto to 2
Inky
Inkyβ€’4mo ago
How many guilds is the bot in?
Forever Gaming
Forever GamingOPβ€’4mo ago
155 Its getting unknown interaction issues and all People said me to shard It worked properly for 1 months with 1 shard Then idk from past days the issue coming again
const { ShardingManager } = require('discord.js');
const { token } = require('./config.json');

const manager = new ShardingManager('./index.js', {
token,
totalShards: 2,
});

manager.on('shardCreate', shard => {
console.log(`πŸš€ Launched shard ${shard.id}`);

shard.on('death', process => {
console.warn(`πŸ’€ Shard ${shard.id} died (code: ${process.exitCode})`);
});

shard.on('exit', (code) => {
console.log(`πŸšͺ Shard ${shard.id} exited (code: ${code})`);
});
});

manager.spawn({ timeout: -1 });
const { ShardingManager } = require('discord.js');
const { token } = require('./config.json');

const manager = new ShardingManager('./index.js', {
token,
totalShards: 2,
});

manager.on('shardCreate', shard => {
console.log(`πŸš€ Launched shard ${shard.id}`);

shard.on('death', process => {
console.warn(`πŸ’€ Shard ${shard.id} died (code: ${process.exitCode})`);
});

shard.on('exit', (code) => {
console.log(`πŸšͺ Shard ${shard.id} exited (code: ${code})`);
});
});

manager.spawn({ timeout: -1 });
I tried this But then idk how to call in const Client On net it is coming to do process.env.shard_id But idh any process.env and how to get shard_id?
Inky
Inkyβ€’4mo ago
client.shard.ids[0]
Forever Gaming
Forever GamingOPβ€’4mo ago
I put this in const Client?
Inky
Inkyβ€’4mo ago
No It’s how you get the shard id Only useful for debugging tbh
Forever Gaming
Forever GamingOPβ€’4mo ago
Yeah so in const client I keep shards auto and in shard manager I do to 2?
Inky
Inkyβ€’4mo ago
You don’t specify anything in the client
Forever Gaming
Forever GamingOPβ€’4mo ago
Ohk Const client = new Client({intents}) Like this right?
Inky
Inkyβ€’4mo ago
Yea
Forever Gaming
Forever GamingOPβ€’4mo ago
But then it is like duplicating my prefix commands
Inky
Inkyβ€’4mo ago
Wdym? Commands appearing twice?
Forever Gaming
Forever GamingOPβ€’4mo ago
async function initializeBot() {
try {
console.log('Loading bot commands...');
await loadCommands(client);

console.log('Logging into Discord...');
await client.login(token).catch(err => {
console.error('Login failed:', err);
throw err;
});
console.log(`Logged in as ${client.user.tag}!`);

console.log('Setting bot status...');
setstatus(client);

// if (!client.shard || client.shard.ids[0] === 0) {
console.log('Deploying global slash commands...');
await deployGlobalSlashCommands(client);
// }

setTimeout(() => {
checkAndProcessExpiredChannels();
setInterval(checkAndProcessExpiredChannels, 30000);
}, 30000);

setTimeout(() => {
scanAndResumeGTNGames(client);
}, 30000);

await startItemWatcher();
await ItemHistoryWatcher();

} catch (error) {
console.error('Error initializing bot:', error);
process.exit(1);
}
}
async function initializeBot() {
try {
console.log('Loading bot commands...');
await loadCommands(client);

console.log('Logging into Discord...');
await client.login(token).catch(err => {
console.error('Login failed:', err);
throw err;
});
console.log(`Logged in as ${client.user.tag}!`);

console.log('Setting bot status...');
setstatus(client);

// if (!client.shard || client.shard.ids[0] === 0) {
console.log('Deploying global slash commands...');
await deployGlobalSlashCommands(client);
// }

setTimeout(() => {
checkAndProcessExpiredChannels();
setInterval(checkAndProcessExpiredChannels, 30000);
}, 30000);

setTimeout(() => {
scanAndResumeGTNGames(client);
}, 30000);

await startItemWatcher();
await ItemHistoryWatcher();

} catch (error) {
console.error('Error initializing bot:', error);
process.exit(1);
}
}
async function main() {
try {
console.log('Connecting to MongoDB...');
await connectToMongoDB(client);

console.log('Loading modules...');
require('./modules/auction.js')(client);
require('./modules/birthday.js')(client);
require('./modules/channelCreate.js')(client);
require('./modules/interactionCreate.js')(client);
require('./modules/intervals.js')(client);
require('./modules/messageCreate.js')(client);
require('./modules/messageDelete.js')(client);
require('./modules/messageUpdate.js')(client);
require('./modules/reaction.js')(client);
require('./modules/reminders.js')(client);
require('./modules/ticket.js')(client);
require('./modules/welcome.js')(client);
require('./modules/donation.js')(client);
await startExpress(client);

console.log('Initializing bot...');
await initializeBot();

console.log('Bot setup complete');
} catch (error) {
console.error('Error in main function:', error);
process.exit(1);
}
}

main();
async function main() {
try {
console.log('Connecting to MongoDB...');
await connectToMongoDB(client);

console.log('Loading modules...');
require('./modules/auction.js')(client);
require('./modules/birthday.js')(client);
require('./modules/channelCreate.js')(client);
require('./modules/interactionCreate.js')(client);
require('./modules/intervals.js')(client);
require('./modules/messageCreate.js')(client);
require('./modules/messageDelete.js')(client);
require('./modules/messageUpdate.js')(client);
require('./modules/reaction.js')(client);
require('./modules/reminders.js')(client);
require('./modules/ticket.js')(client);
require('./modules/welcome.js')(client);
require('./modules/donation.js')(client);
await startExpress(client);

console.log('Initializing bot...');
await initializeBot();

console.log('Bot setup complete');
} catch (error) {
console.error('Error in main function:', error);
process.exit(1);
}
}

main();
Yes
Inky
Inkyβ€’4mo ago
Logs are expected to appear twice You told it to run 2 clients
Forever Gaming
Forever GamingOPβ€’4mo ago
Like I have prefix commands as well So they give response 2 times
treble/luna
treble/lunaβ€’4mo ago
(and side note, but you should not deploy your commands every time your bot starts, only when you make changes)
Forever Gaming
Forever GamingOPβ€’4mo ago
And for like load commands and deploy I do on first shard right?
Inky
Inkyβ€’4mo ago
It’s also a bit concerning that you are running express in here
Forever Gaming
Forever GamingOPβ€’4mo ago
Express I will run on first shard Like the main things like command deploy and loading and express I run on the first shard?
Inky
Inkyβ€’4mo ago
In the future, you should just move it into the ShardingManager
Forever Gaming
Forever GamingOPβ€’4mo ago
I have separate file for express app Index.js and bot.js(sharding file)
Inky
Inkyβ€’4mo ago
That’s fine Issue is that ur initializing it in the client
Forever Gaming
Forever GamingOPβ€’4mo ago
You meant like putting shards: auto in client?
Inky
Inkyβ€’4mo ago
No
Forever Gaming
Forever GamingOPβ€’4mo ago
Then?
Inky
Inkyβ€’4mo ago
I’m talking abt other modules like express And deploying commands
treble/luna
treble/lunaβ€’4mo ago
as i mentioned, command deploy should not be ran at all alongside the client. You should have a separate script that deploys. Your commands wont magically undeploy every time your bot starts
Inky
Inkyβ€’4mo ago
Stuff that shouldn’t be running on every shard
Forever Gaming
Forever GamingOPβ€’4mo ago
Oh (client) parameters? Ohk I will try to do that what you guys are saying Then will update you what happened Alright
Inky
Inkyβ€’4mo ago
You can use an if statement to make the first shard to it and fix it later I’m more interested in ur commands replying twice
Forever Gaming
Forever GamingOPβ€’4mo ago
I have messageCreate for prefix commands in index.js Ig I was doing wrong sharding that's why it happened I will try again with how you guys said
Inky
Inkyβ€’4mo ago
Oh, you still had shards: auto in the Client?
Forever Gaming
Forever GamingOPβ€’4mo ago
See this error coming : ⚠️ Error in auction system:
DiscordAPIError[10062]: Unknown interaction
at handleErrors (/home/container/node_modules/discord.js/node_modules/@discordjs/rest/dist/index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async BurstHandler.runRequest (/home/container/node_modules/discord.js/node_modules/@discordjs/rest/dist/index.js:852:23)
at async _REST.request (/home/container/node_modules/discord.js/node_modules/@discordjs/rest/dist/index.js:1293:22)
at async ButtonInteraction.showModal (/home/container/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:406:22)
at async Client.<anonymous> (/home/container/modules/auction.js:97:13)
DiscordAPIError[10062]: Unknown interaction
at handleErrors (/home/container/node_modules/discord.js/node_modules/@discordjs/rest/dist/index.js:748:13)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async BurstHandler.runRequest (/home/container/node_modules/discord.js/node_modules/@discordjs/rest/dist/index.js:852:23)
at async _REST.request (/home/container/node_modules/discord.js/node_modules/@discordjs/rest/dist/index.js:1293:22)
at async ButtonInteraction.showModal (/home/container/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:406:22)
at async Client.<anonymous> (/home/container/modules/auction.js:97:13)
Like it works perfectly fine for first 10 mins Then this comes
Inky
Inkyβ€’4mo ago
Does the modal show?
Forever Gaming
Forever GamingOPβ€’4mo ago
No It says int fail After 10 mins of bot uptime If I go restart bot rn it will work perfectly fine
Inky
Inkyβ€’4mo ago
Either an internet issue or smth caused the bot to take too long to respond
Forever Gaming
Forever GamingOPβ€’4mo ago
Host issue?
Inky
Inkyβ€’4mo ago
It’s possible
Forever Gaming
Forever GamingOPβ€’4mo ago
That's what I also think ig
Inky
Inkyβ€’4mo ago
Are you able to see cpu and ram usage of the bot?
Forever Gaming
Forever GamingOPβ€’4mo ago
No description
Forever Gaming
Forever GamingOPβ€’4mo ago
I removed sharding and then it worked for now 25 mins With sharding it worked for 10 mins
Inky
Inkyβ€’4mo ago
When it errors, does it like keep failing if you keep trying again until you restart?
Forever Gaming
Forever GamingOPβ€’4mo ago
Yes
Inky
Inkyβ€’4mo ago
Can you show modules/auction.js? And mark line 97
Forever Gaming
Forever GamingOPβ€’4mo ago
No description
Forever Gaming
Forever GamingOPβ€’4mo ago
Ok Line 32 to line 99
if (interaction.isButton() && interaction.customId === 'auction_button') {
const userId = interaction.user.id;
const member = interaction.guild.members.cache.get(userId);

const auctionSettings = await settingsCollection.findOne({ guildId: interaction.guild.id });
if (!auctionSettings) {
return interaction.reply({
content: 'Auction system is not set up in this server. Please contact the server admin.',
ephemeral: true
});
}

const auctionRoleId = auctionSettings.auctionRole;
if (!member.roles.cache.has(auctionRoleId)) {
return interaction.reply({
content: `You need the <@&${auctionRoleId}> role to create auctions.`,
ephemeral: true
});
}

const existingAuction = await auctionsCollection.findOne({
userId: userId,
status: { $in: ['pending', 'active'] }
});


if (interaction.isButton() && interaction.customId === 'auction_button') {
const userId = interaction.user.id;
const member = interaction.guild.members.cache.get(userId);

const auctionSettings = await settingsCollection.findOne({ guildId: interaction.guild.id });
if (!auctionSettings) {
return interaction.reply({
content: 'Auction system is not set up in this server. Please contact the server admin.',
ephemeral: true
});
}

const auctionRoleId = auctionSettings.auctionRole;
if (!member.roles.cache.has(auctionRoleId)) {
return interaction.reply({
content: `You need the <@&${auctionRoleId}> role to create auctions.`,
ephemeral: true
});
}

const existingAuction = await auctionsCollection.findOne({
userId: userId,
status: { $in: ['pending', 'active'] }
});


const modal = new ModalBuilder()
.setCustomId('auction_modal')
.setTitle('Create Auction')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('auction_item')
.setLabel('Name of Item')
.setStyle(TextInputStyle.Short)
.setPlaceholder('Ant, Blob, Pepe Trophy, etc.')
.setRequired(true)
),
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('auction_quantity')
.setLabel('Quantity')
.setStyle(TextInputStyle.Short)
.setPlaceholder('1, 10, 100, etc.')
.setRequired(true)
),
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('starting_bid')
.setLabel('Starting Bid')
.setStyle(TextInputStyle.Short)
.setPlaceholder('100,000,000')
.setRequired(true)
)
);

await interaction.showModal(modal);
return;
}
const modal = new ModalBuilder()
.setCustomId('auction_modal')
.setTitle('Create Auction')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('auction_item')
.setLabel('Name of Item')
.setStyle(TextInputStyle.Short)
.setPlaceholder('Ant, Blob, Pepe Trophy, etc.')
.setRequired(true)
),
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('auction_quantity')
.setLabel('Quantity')
.setStyle(TextInputStyle.Short)
.setPlaceholder('1, 10, 100, etc.')
.setRequired(true)
),
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('starting_bid')
.setLabel('Starting Bid')
.setStyle(TextInputStyle.Short)
.setPlaceholder('100,000,000')
.setRequired(true)
)
);

await interaction.showModal(modal);
return;
}
Line 97 is await interaction.showModal
Inky
Inkyβ€’4mo ago
Why fetch existing auction? I don’t see it being used
treble/luna
treble/lunaβ€’4mo ago
also, just to inform, if your bot is in 155 guilds and getting unknown interaction a lot, increasing shards wont really help, you'll have to look into your network or host sharding isnt really beneficial until around 2000 guilds
Forever Gaming
Forever GamingOPβ€’4mo ago
Oh that was for before like I was limiting if user has exisiting auction they can't request again I removed the if statement
Inky
Inkyβ€’4mo ago
It could be the db call not finishing fast enough You only get 3 seconds to reply/respond/etc or defer an interaction upon receiving it
Forever Gaming
Forever GamingOPβ€’4mo ago
Oh I have like 5k documents πŸ’€ In that collection It is because of that?
treble/luna
treble/lunaβ€’4mo ago
most likely yes, you are doing a lot of db calls thats slowing down the modal showing also, interaction.member exists, you dont need to get it from cache
Forever Gaming
Forever GamingOPβ€’4mo ago
Ohh But slash commands also give application not respond const member = interaction.guild.members.cache.get(userId); Instead of this I do const member = interaction.member(userId)
treble/luna
treble/lunaβ€’4mo ago
no, just interaction.member
d.js docs
d.js docsβ€’4mo ago
:property: ButtonInteraction#member discord.js@14.21.0 If this interaction was sent in a guild, the member which sent it
treble/luna
treble/lunaβ€’4mo ago
dont just guess
Forever Gaming
Forever GamingOPβ€’4mo ago
Also in slash commands it gives application not respond On slash command @Inky It comes application not respond I have like deferreply as well
treble/luna
treble/lunaβ€’4mo ago
Then your code is not reaching that defer Figure out where code execution stops
d.js docs
d.js docsβ€’4mo ago
If you aren't getting any errors, try to place console.log checkpoints throughout your code to find out where execution stops. - Once you do, log relevant values and if-conditions - More sophisticated debugging methods are breakpoints and runtime inspections: learn more
Forever Gaming
Forever GamingOPβ€’4mo ago
@Inky can you help me sort out my bot if i give you access?
treble/luna
treble/lunaβ€’4mo ago
No. We are here to help you. Not fix stuff for you Start by the beginning Your unknown interaction issues wont be solved by sharding
Forever Gaming
Forever GamingOPβ€’4mo ago
Then what should I do now Fully built bot from scratch again?
treble/luna
treble/lunaβ€’4mo ago
No Look at whats causing the unknown interaction errors You're taking longer than 3s to respond
Forever Gaming
Forever GamingOPβ€’4mo ago
im using defer reply immedietly and it is coming in all commands
treble/luna
treble/lunaβ€’4mo ago
Whether thats your code or your host, thats up to you And what happens in discord Does it show application did not respond, or application is thinking
Forever Gaming
Forever GamingOPβ€’4mo ago
application didnt respond even though i have deferreply
treble/luna
treble/lunaβ€’4mo ago
Sounds like a host/ network issue then Your code is not even reaching that defer in time Thats your issue And your stack points to a .reply Not a deferReply
Forever Gaming
Forever GamingOPβ€’4mo ago
async function donoCheck(interaction) { try { await interaction.deferReply(); it have immedietly defer
treble/luna
treble/lunaβ€’4mo ago
yet your stack is still showing .reply
Forever Gaming
Forever GamingOPβ€’4mo ago
how 😭
Forever Gaming
Forever GamingOPβ€’4mo ago
issue happening cuz of this?
d.js docs
d.js docsβ€’4mo ago
To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.
treble/luna
treble/lunaβ€’4mo ago
There isnt a single deferReply in that code
Forever Gaming
Forever GamingOPβ€’4mo ago
thats the main one which executes command if i like put deferreply in this and then in all commands i use editReply instead of reply will that fix this?
treble/luna
treble/lunaβ€’4mo ago
thats step one yes . You need to figure out why Either you are doing too much async stuff or its a host issue Start by deferring the moment you receive the interaction If it still happens, its a host issue
Forever Gaming
Forever GamingOPβ€’4mo ago
ok
WhoAboutYT :3
WhoAboutYT :3β€’4mo ago
consider making cleaner code and adding comments to explain things such as what the fallback handler does etc and yeah
treble/luna
treble/lunaβ€’4mo ago
thats not the current focus though
Forever Gaming
Forever GamingOPβ€’4mo ago
@treble/luna I found the main issues I deferred all commands the bot slows down after sometime of starting which leads to slowness how to prevent that now? Due to slowness buttons give unknown interaction to optimize buttons we use deferUpdate?
Amgelo
Amgeloβ€’4mo ago
buttons aren't "optimized" you should just find what's making your bot slow down
Forever Gaming
Forever GamingOPβ€’4mo ago
Too many messageCreates? And interaction creates Prefix commands are main cause
Amgelo
Amgeloβ€’4mo ago
how do you know that? and why do you think that
treble/luna
treble/lunaβ€’4mo ago
you'd also ideally only have 1 listener per event and pass your logic down using handlers I'm suprised you even got approved for the content intent but that still shouldn't slow down your code
Forever Gaming
Forever GamingOPβ€’4mo ago
Yeah that's what I thought to make async function for all and then load them And use in a single interactionCreate/messageCreate I learnt from them
treble/luna
treble/lunaβ€’4mo ago
smart to publicly announce that
Amgelo
Amgeloβ€’4mo ago
what's the "trick" supposed to be, if they allowed it then it doesn't sound like a trick at all
Forever Gaming
Forever GamingOPβ€’4mo ago
Trick like using separate messagecreates and all Btw it got fixed By changing host It washost issue Thanks for the help

Did you find this page helpful?