#archive-sharding
12465 messages · Page 5 of 13
How can I restart a websocket shard?
I destroyed it
Documentation suggestion for @next plaza:
ShardingManager#createShard()
Creates a single shard. (more...)
600 shards 
Want to restart a Websocket Shard
How to Add Shards?
totalShards must be a number not a string.
How's that?
Can I get you a code?
Replace "1" with 1 ?!
Yup
🤯
How can I get an emote from another shard?
Or how can I fetch all the emojis so I can use them on a different shard?
?softban @eternal cedar spamming question across multiple channels
Successfully softbanned Kartik#1234
How would you display your bot's whole server count in it's status?
~~use client.guilds.cache.size~~mb didn't realize this was sharding
whats the max amount of shards I could use?
i don't think there is any limit
hmms
hello, i wanted to get member count from across all the shard, this is how i did it in stable release:
client.shard.broadcastEval('this.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)')
.then(results => {
return message.channel.send(`Total member count: ${results.reduce((acc, memberCount) => acc + memberCount, 0)}`);
})
.catch(console.error);
```and it was working, but in v13 (master branch) it didnt work, i also tried this
```js
client.shard.broadcastEval(() => 'this.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)')
.then(results => {
return message.channel.send(`Total member count: ${results.reduce((acc, memberCount) => acc + memberCount, 0)}`);
})
.catch(console.error);
``` but it didnt work either ;-; can someone help me?
(i updated to master branch because i wanted to use threads. but it also had other changes so i had to fix them but idk how thats why i came here :))
anyone?
Iirc v13 takea a function
yeah i know thats what i did in second code block, i already got the fix in #djs-help-v14
Ah k
you have a login limit to the Gateway of 1000 per Day. Starting 1 Websocket Shard is logging 1 time, means you have a limit of 1000 Shards. Moreover, when your bot hits 100k Guilds, you can request Discord to make the limit higher to 1500 or more
This is not working and I'm using sharding
And it happends to me also with guildmemberAdd or some other ones
?shitty-buttons
We do not provide support with third party libraries like discord-buttons.
Discord.js supports buttons natively with version 13.
If you want to check it out now install npm i discord.js@dev (see #archive-buttons for docs and caveats)
Ping me if you know
know what
how do i restart bot on sharding? previously without sharding. I just do process.exit(1) but how i do 'restart bot' with sharding?
client.shard.broadcastEval('process.exit();')
pm2 doesn't restart since the sharding manager is still active
do you want to just respawn the shards?
nvm yeah found out
Would be nice if you posted the solution
Is there any way to restart a specific shard?
used the repawnAll method
anyone have a guide on sharding?
?sharding
const { ShardingManager } = require('discord.js');
const Manager = new ShardingManager('./bot.js', { token: 'your-token' });
Manager.spawn();
https://discord.js.org/#/docs/main/stable/class/ShardingManager
For an in-depth guide: https://discordjs.guide/sharding/
so by ('./bot.js') do they mean my main bot compiler file? I call it client.js
what ever is ur main bot file is put there (or path to id)
so i just implemented sharding, and my commands dont work.
const logger = require('./utils/logger.js');
(async function load() {
// This is to verify config file
const configCorrect = await require('./utils/verify-config.js').run(require('./configuration/config.json'));
if (!configCorrect) {
// This file is for sharding
const { ShardingManager } = require('discord.js');
// Create sharding manager
const manager = new ShardingManager('./bot.js', {
// Sharding options
totalShards: 'auto',
token: require('./configuration/config.json').token,
});
// Spawn your shards
manager.spawn().then(logger.log('=-=-=-=-=-=-=- Loading shard(s) -=-=-=-=-=-=-='));
// Emitted when a shard is created
manager.on('shardCreate', (shard) => {
logger.log(`Shard ${shard.id} launched`);
});
} else {
logger.error('Please fix your errors before loading the bot.');
process.exit();
}
})();
Thats My Shard Manager^^
and here is my bot.js
const Discord = require('discord.js')
const client = new Discord.Client()
const config = require('./configuration/config.json')
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
["command_handler", "event_handler"].forEach((handler) => {
require(`./handlers/${handler}`)(client, Discord);
})
client.on('guildMemberAdd', member => {
// Send the message to a designated channel on a server:
const channel = member.guild.channels.cache.find(ch => ch.name === 'mod-logs');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
});
client.on('roleCreate', member =>{
const channel = member.guild.channels.cache.find(ch => ch.name === 'mod-logs');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Attention! A New Role Was Created! `);
});
client.login(config.token)
im just wondering why my commands wont work?
?sharding
const { ShardingManager } = require('discord.js');
const Manager = new ShardingManager('./bot.js', { token: 'your-token' });
Manager.spawn();
https://discord.js.org/#/docs/main/stable/class/ShardingManager
For an in-depth guide: https://discordjs.guide/sharding/
Hey, how can I spawn 2 shards ?
What type of sharding are you using
I'm using the sharding manager
Put in totalShards: 2 in the ShardManager options
Or you can specify a list of ids in shardList
I tried, but the but the event that signals when a shard is launched no longer works (nothing is sent to the console)
Can you show the code you used?
?shitty-buttons
We do not provide support with third party libraries like discord-buttons.
Discord.js supports buttons natively with version 13.
If you want to check it out now install npm i discord.js@dev (see #archive-buttons for docs and caveats)
What...
Iirc u need to listen to the evnt before calling the <manager>.spawn function
Okay thx
${bot.users.cache.size}``` this works for me. But the member count will only update once the bot is restarted
that will not work for him, assuming he dont use broadcast eval and just place it, as bot will only be the current shard
is that on phone dont mind me asking
const promises = [
client.shard.fetchClientValues("guilds.cache.size"),
client.shard.broadcastEval(
"this.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)"
),
];
TypeError: SHARDING_INVALID_EVAL_BROADCAST
discord.js@dev
Why is this error Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready. stopping the rest of the shards from spawning?
Check you ready event
wdym
if you have a code that executes in the ready event it can stop the shard from becoming ready
The code doesnt stop the shard from becoming ready as it gets emitted the same time as the client ready event
You need to pass a function for broadcastEval on the master branch iirc
Tried that, didnt work
I am trying to execute
client.shard.broadcastEval('this.user.setStatus("invisible")')
So it will set the status as invisible.
But it does not work, it gives me the SHARDING_INVALID_EVAL_BROADCAST
Please ping me when you replied
when using master, the broadcastEval must be a function
SO how should I do it then?
to find a guild, would you use this.guild.cache.get('')?
ClientUser#setStatus()
Sets the status of the client user.
The normal Client.user.setStatus/setPresence should apply to all Shards by default if no shardID is specified
We can set different activity for diff shards?
client.shard.broadcastEval(function() {
this.client
})
I know do this, cause someone said I need to put this.client before it but that won't work either way, this is undefined. So how would I need to fix that?
After some testing, it worked. Thanks!
Yes
Wow learnt something new today
I want to get all emojis cache but client.shard.fetchClientValues needs all shards spawned, any event to know if all shards are spawned ?
client.on('shardReady', id => {
client.shard.fetchClientValues('emojis.cache')
.then(GuildEmojis => {
client.logger.debug(GuildEmojis)
})
.catch(client.logger.error)
})
No there isnt an event but you can impliment a function to check when a shard spawns to see if the shard collection size equals to the manager.total shards value
Hey,
I'm trying to spawn 2 shards for my bot, but when I'm doing that, I have an error that I never had before...
I have my guildDelete event (Screen #1)
And my shard.js file (Screen #2)
Error (Screen #3)
Who can help me solve this problem please?
And the error :

-
The property res is undefined
-
Res is undefined because you cannot perform an eval untill all shards have been spawned
Yes, but how can I change that ?
Change what
To make it work
Well you can add a check to see of res is undefined
Thx it works .But I have one last question. How can I get my site to start (with express) once. At the moment it tries to start once per shard.
You would need to have your express server run in your file with the shard manager
And I need to get my client to start the express server
Why
I need to get some informations about the bot on some pages
If its server count / user you can broadcasteval from the manager
If not you can create a websocket server to communicate with the shards and the server
how can I broadcasteval without the client ? 🤔
?docs ShardingManager#broadcastEval
Any docs to use emoji with v13 ?
It's probably the same as v12, and you should probably ask in #djs-help-v14 too
When's a good point to start clustering?
I'm already sharding
do I need multiple machines for sharding?
How do i respawn all shards
client.shard.respawnAll()
this seems to not work
No you dont, its uo to you if you want/you bot needs multiple machines
Any errors?
cannot read respawnAll of undefined
but i did a workaround already so i am fine
Okay
any guide to sharding with mutiple machines?"
uh no, but a simple way is by passing the shardList option to what shards you want spawned on x machine
you want it from the emoji cache or do you want to just send the emoji?
just send emojis in messages
then you can get the emoji id, by \ 
ok
I just tested \:emojiID: in embed description and that doesn't
!blobunamused
<:{name}:{id}>
ty !
[WS => Shard 6] [HeartbeatTimer] Didn't receive a heartbeat ack last time, assuming zombie connection. Destroying and reconnecting.
Sequence : 8105
[WS => Shard 6] [DESTROY]
Close Code : 4009
Three shards went zombie. Why does it not reconnect back?
Also I'm using Compression: zlib-stream
You have multiple things listening to the same port
hey, how do i get total amount of shards? and all sharding statistics?
client.shard.count
How do I do sharding
const { ShardingManager } = require('discord.js');
const Manager = new ShardingManager('./bot.js', { token: 'your-token' });
Manager.spawn();
https://discord.js.org/#/docs/main/stable/class/ShardingManager
For an in-depth guide: https://discordjs.guide/sharding/
@real spire
here
No
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
Could also be caused by not calling client.login
How do I start a dm message collector from different shard?
you cant, you have to broadcastEval it.
It is a little bit complicated
👍
[WS => Shard 6] [HeartbeatTimer] Didn't receive a heartbeat ack last time, assuming zombie connection. Destroying and reconnecting. Sequence : 8105 [WS => Shard 6] [DESTROY] Close Code : 4009Three shards went zombie. Why does it not reconnect back?
Bumping. Well the docs says you need to manually reconnect. But why is it happening frequently in random shards?
What djs version / sharding type (I'm assuming Sharding Manager?) / how many guilds roughly?
This are Websocket SHards
How are you spawning them?
they automatically gets spawn, when you do client.login | The provided Shardlist gets spawned
I was asking for code, really.
You're giving barely any information to diagnose with :p
They are using Internal Sharding, Guilds is approx 6k
Got it. That's relatively small, I wouldn't expect any issues
Its obvious, that they have a bad Connection. The Websocket didnt recieve any Heartbeat and it closed the Connection. There is nothing you can fix here
Perhaps, yeah. Odd that it'd be on one shard and not the others
eI used 30 Internal Shards, the amount is not a problem. It comes to your connection
Hi
Master branch. Sharding Manager. 6100 Guilds
And the issue is only happening in the public bot which is using the master branch. I have several other bots running in the same vps (premium version of the bot), which uses djs v12. There are no issues for em.
Also does zlib-sync has any role in this? Only the public bot has it tho. What does this module exactly do?
Also Setting a heartbeat interval for 41250ms this message might contribute to the connection status ig
zlib sync is used for data compressions, I personally do not use it at my bot, ...works fine
Why not just let it automatically handle the interval?
It is doing so automatically. Thats from the console
Ah 👍
You could try removing the compression, per meister's suggestion.
im getting this error
/root/bots/alphamanager/node_modules/discord.js/src/sharding/Shard.js:163
reject(new Error('SHARDING_READY_TIMEOUT', this.id));
^
Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
at Timeout.onTimeout (/root/bots/alphamanager/node_modules/discord.js/src/sharding/Shard.js:163:16)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
[Symbol(code)]: 'SHARDING_READY_TIMEOUT'
}
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
i've tried that, still happens
Did you actually logged in?
ill send the code of the shard.js file
const config = require('./config.json');
const logger = require('./utils/logger');
const Discord = require('discord.js');
const Statcord = require("statcord.js");
const { token } = require('./utils/variables.js');
const manager = new Discord.ShardingManager('./index.js', {
token: token,
//autoSpawn: true,
//totalShards: 'auto'
totalShards: 1,
});
manager.spawn(this.totalShards, 5500, -1);
manager.on('shardCreate', shard => logger.info(`Launching Shard ${shard.id + 1}`, { label: `Shard` }));
could you log out this.totalShards?
sure let me try
nvm i had an invalid token i think
what are shards
Shard (extends EventEmitter)
A self-contained shard created by the ShardingManager. Each one has a ChildProcess that contains an instance of the bot and its Client. When its child process/worker exits for any reason, the shard will spawn a new one to replace it as necessary.
^
wait so it basically just keeps the bot alive?
No
That is just saying when a shard dies(process exit) a new one will automatically be created
when would the process exit?
Errors, you calling the kill method note this will not create a new one and other things
Sharding is just splitting up the guilds ur bot is in into different processes
?sharding
const { ShardingManager } = require('discord.js');
const Manager = new ShardingManager('./bot.js', { token: 'your-token' });
Manager.spawn();
https://discord.js.org/#/docs/main/stable/class/ShardingManager
For an in-depth guide: https://discordjs.guide/sharding/
Shards will only receive events for its own guild
Hey does anyone know how to get the client from the shards? Im trying to set a winston child logger everytime a client gets instantiated.
also what is mode? like what does mode: process or worker do?
Please read the whole message underneath:
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
This can … successful launch.
const theShard = await manager.broadcastEval(async (client, id) => {
let server = client.guilds.cache.get('a_server_that_user_is_in');
if (server) return server.shardID
}, { context: "my_user_id_here" });
console.log(theShard)
/*
Result logged: [ undefined, 1, undefined, undefined ... undefined]
*/
await manager.broadcastEval(async (client, id) => {
let user = await client.users.fetch(id);
return user.send('Test');
}, { shard: theShard.filter(a=>a), context: "my_user_id" });
This code is repeatedly sending the "Test" into my DMs... despite my specifying the "shard" as the one that isn't falsey (hence the .filter(a=>a)). Any ideas on why its doing that?
I have changed the userID and serverID just to make this less specific, but I am of course specifying these correctly.
I was told to ask this question here
Is there a way I can instead message the user just once?
When I try to do broadcast a more simpler code as well:
manager.broadcastEval(async (client, id) => {
const user = client.users.cache.get(id);
if (user) user.send("Test");
}, { context: user_id });
This seems to message the user multiple times as well
does sharding minimize the lag of a bot?
my bot currently runs on 5,145 servers across 4 shards, and i'm not sure if that's too many or too little shards
You have to test it, Sharding seperates your Process accross your Cpus. When you see that your CPU-Usage is high, than you should
not sure what denotes as "high"; all of my bot's node.js processes currently take up 12% of my cpu (amd ryzen 9 3900x 12c)
yeah, thats totally fine
But just a tip, code like you can turn the next day on sharding
can you clarify that tip? i'm not sure what you mean in the last part
Your code should be shardable
oh ok, that i know already; all my code has been converted to be shard-compatible -- thanks :)
Will there be always be one shard where a user would be cached?
yea, if the user is in the same guild(altho this dosnt happen if uve disabled intents) or has sent a message, it should be cached in the shard refrenced to that guild
how to Check all shards are running or not.
shard status kinda.. maybe a comamnd.
I use discord sharding amanger
client.shard.broadcastEval('this.ws.status')
0 is ready
:O Rishab
missing access, then shard 2 died. why?
We don't know. A 403 indicates your bot no longer had permission to do what it was trying to. @umbral cradle
You could take a look at the channel it specifies and see what's up.
How i put status per shard like if guild is on shard 1 bot have status shard 1/3
How i can get all info about a shard? What i want is get shard ID, shard guild count, shard member count, shard status and more
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setActivity
You have to add in the options {shardID: 'theSHARDid'}
client.shard.broadcastEval('[
this.shard.id,
this.guilds.cache.size,
this.guilds.cache.reduce((acc, guild) => acc + (guild.memberCount||0), 0),
this.ws.status,
]
')```
You can do single requests too
Okey!
this.shard.id gives me undefined
And i cant do like: ID: this.shard.id to keep it better as a json
this.shard.ids[0]
Nice!
I'm just asking around because I want to future proof my bot, but what methods would I use to connect to MongoDB (using Mongoose) with shards? I'm not sure how to prevent conflicting processes with sharding
They arent any other methods to connect to mongo when using shards as you would have each shard process connect to the database
Alright, well does mongo allow multiple connections by the same user to the same database? Or do I need to create a seperate user for each shard?
Iirc it does
Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
at Timeout.onTimeout (/home/runner/LePatron/node_modules/discord.js/src/sharding/Shard.js:163:16)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
how do i solve this error in my code?
I have the same problem
@winter summit I used a alternative bot and it works fine with no errors
I think it’s the api error cause my api is 1000+
Some one pls help
Its not the api
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
Yh but why does it work with no errors on my alt bot
Same host same code just the token that is replaced
I’m new to these stuff I don’t really know much about it
That has nothing to do with this error
I guess it’s the amount of servers the bot is in
Cause currently it’s in 125
Could be your connection
Nope not the connection
Cause I used a different bot token which I use for testing and it worked perfectly fine
Try setting the spawnTimeout to -1 or Infinity
Ok
It’s just the client
Code:```js
let embed1 = new Discord.MessageEmbed().setColor(GREEN).setDescription(Novo comando utilizado\n\n**Comando utilizado por**:\n${message.author}\(${message.author.id})`\n\nComando utilizado:\n`${prefix}${command}`\nDps do comando:\n `${args.length ? args.join(' ') : "-/-"}`\n\nNo servidor: \n`${message.guild.name}(${message.guild.id})`\nCom:\n `${message.guild.memberCount} membros`).setAuthor(message.author.tag, message.author.displayAvatarURL()).setFooter(© Milo, Todos direitos reservados).setTimestamp() client.shard.broadcastEval((async () => {
const channel = await this.channels.cache.get('829794164392591461');
channel.send(embed1);
})();
`);
Error:```js
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at eval (eval at _eval (/home/runner/LePatron/node_modules/discord.js/src/client/Client.js:425:12), <anonymous>:4:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async ShardClientUtil._handleMessage (/home/runner/LePatron/node_modules/discord.js/src/sharding/ShardClientUtil.js:187:64)
this code is called when executing the bot prefix, but it gives me error, how can I solve it?
Could be the bot can’t find the channel
const channel = await this.client.channels.cache.get('829794164392591461');```
try this? coz this.channels will be undefined 
did not work
Add (after const channel)
if(!channel) return console.log("Returned")
So it will return when it did not find the channel.
I have ```javascript
manager.spawn();
manager.on("shardCreate", shard => {
log.info(Shard #${shard.id} is online.);
axios.get(`http://localhost:7000/api/shards?id=${shard.id}`, {
//shardID: shard.id
});
//getServerCount()
});
However no matter what I do, it gets to shard 9 and then it doesn't send a request for shard 10 or log its online even when it has spawned.
The shards' ids start at 0, so if you have 10 shards, the ids will be in a range from 0 to 9
So why doesn't it log shard 0 is online?
Is it possible to have different profile depending on different server?
or bot's status different in different servers
different shards, yes
the shard ID can be passed as an option:
https://discord.js.org/#/docs/main/stable/typedef/ActivityOptions
Got a code example?
one second
I want basically to have if a shards ID is 5 then it shows it in its status
await client.user.setPresence({ status: "online",
activity:{
name: `over shard 5`,
type: `WATCHING`
shardID: 5
}
})
its client.shard.ids[0] for the current shard ID right?
Isn't it just this.client.shard.id? (this only really needed in broadcasteval)
await client.user.setPresence({ status: "online",
activity:{
name: this.client.shard.id,
type: `WATCHING`,
shardID: client.shard.id
}
TypeError: Cannot read property 'shard' of undefined
@mellow grove ^^
is there a limit on how many sharding I could have
how do I check if a shard is online from its ID?
how do i find a channel from another shard?
It depends on how much login sessions you have, a regular bot under 250k guilds has 1k login sessions
broadcastEval this.ws.status on the shard by passing its id in the second param. <client>.shard.broadcastEval('this.guilds.cache.size', SHARDID)
broadcastEval
Pro 👏
scam
<@&839912195994812420> ^
thanks
Doesn't work
Thats because the shard process/worker is not ready
Hello, how can i get Guild Collection with broadcastEval method ?
manager.broadcastEval(`this.guilds.cache.get('${guildId}')`); // Is only javascription object, but i want the guild collection.
//
confused on the question; guilds.cache returns a collection no?
Do you want all guilds?
Right now I’m having issues with spawning shards, I’m running shards on a bot with a little over 3.2k servers and normally the bot spawns about 3 shards, but until recently, the bot only spawns 1 out of the needed 3 shards. Not long after, the client emits a SHARDING_READY_TIMEOUT saying that shard 0 took too long to become ready, and after that error, it just runs shard 0. Here’s my sharding code:
const { ShardingManager } = require('discord.js');
require('dotenv').config()
const manager = new ShardingManager('./asf.js', { token: process.env.Token, autoSpawn: true, respawn: true});
const chalk = require('chalk')
manager.on("shardCreate", (shard) => {
console.log(console.log(chalk.greenBright(`✅ - Launched shard #${shard.id}\n───────────────────────────────`)));
});
manager.spawn();
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
@terse cairn add in the spawn(undefined, undefined, -1)

Well, that solves the shard timeout issue, but only 1 out of 3 shards spawn.
I know, but it is trying to check shard one when you can see in the picture req.params.id is 0 so it should be checking shard 0
try manager.spawn('auto', undefined, -1)
@next plazaNo i want one guild
Can someone help me ?
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
I have javascript const SHARDID = req.params.id console.log(req.params.id) client.shard.broadcastEval("this.guilds.cache.size", 0).then(() => { console.log("online") })
However whenever I change the 0 to req.params.id which equals 0, it tries broadcasting it to shard 1 for some reason.
Same thing.
How can I force a shard to crash?
Shard#kill()
Immediately kills the shard's process/worker and does not restart it.
@versed temple you can kill it with this 
oh nice
i dont know how to stop it from crash and you crash it 
HAHAHAHAHAHAHHAHAHA
if my shard or index.js has the bot token. do i have to put client.login(token) in my bot.js as well?
mention me if u reply
Hello, was just curious: What do people recommend using for a database when sharding?
Just use one you're comfortable with
That's the thing though, I'm not sure which one, as I am not aware of many. So I was hoping for some ideas to look into.
I have my own if you want to use it, I coded it myself 
I'll definitely look into it! Just send me whatever you need to
dms
@coarse arch Can I have it too?
sure
@coarse arch can I also have?
s u r e
app.post('/dblwebhook', wh.listener(async (vote) => {
let user = client.shard.broadcastEval(`this.users.cache.get(${vote.user})`).then(console.log);
}))
does anyone know how to fix this code? it sends me [ null, null] when giving the request to run this code using shards
Make sure vote.user is an id
the user is not cached on the Shards
app.post('/dblwebhook', wh.listener(async (vote) => {
let user = client.shard.broadcastEval(`this.users.cache.get('${vote.user}')`).then(console.log);
})
``` Could you try this.
Can I also have it?
sure
Heyya everyone I've a small problem, there is only the first shardId in the this.client.shard.ids but everything else works fine.
Someone could help me ? 
I need it to make a command where all the shards with their guilds/users are displayed. But I can't get every shards data with the broadcastEval / fetchClientValues
Feel free to ping me

you have to broadcast for getting the guildCache....
This is not the problem as there is only the first shard linked to the client, I can't get the cache for the other shards :/
are the other shards hosted on a different machine?
No, it's a local test
are all shards is the same node/process?
The cache is separated correctly but there is juste one sharId in the this.client.shard.ids
Yes
Do you start all Shards from the Same Manager?
Show me your Shard.js file
const { ShardingManager } = require('discord.js')
const { discord: config } = require('./src/configuration')
const Logger = require('./src/logger')
/**
* Manages the DiscordClient shards to separate the bot on several instances
* @extends {ShardingManager}
*/
class Sharding extends ShardingManager {
constructor () {
super('./index.js', { token: config.token, respawn: true, autoSpawn: true })
this.logger = new Logger()
}
/**
* Instantiates the shard
* @return {Sharding}
*/
static bootstrap () {
return new Sharding()
}
/**
* Launch the sharding manager
* @return {Promise<Collection<number, Shard>>}
*/
async run () {
// Event emitted when a shard is created
this.on('shardCreate', (shard) => {
this.logger.log(`Launching ${shard.id}'s shard...`)
this.logger.log('──────────────────────')
})
// Spawn multiple shards -
return this.spawn({ amount: 2 })
}
}
const shard = Sharding.bootstrap()
shard.run()
.then((shards) => setTimeout(() => shard.logger.log(`Shards launched: ${shards.size}`), 1000))
.catch((err) => {
shard.logger.error(err)
process.exit(1)
})
you can do everything without creating your own class
But it's not the problem, it's better for us 
A question do all shards have to start before the bot starts? or can you start all shards at once?
All shards start one by one
how do the big bots do it? if you restart the bot? then at 200 shards it can take forever
I take the liberty of ping you @next plaza, but the part where I get the data for my command is here
const displayShards = []
const shards = this.client.shard.ids
for (const shardID of shards) {
const results = await this.client.shard.broadcastEval((client) => {
return {
guilds: client.guilds.cache.size,
guildsAvailable: client.guilds.cache.filter(({ available }) => available).size,
users: client.users.cache.size,
ms: client.ws.ping
}
}, { shard: shardID })
if (typeof results === 'object') {
results.id = shardID
} else {
results[0].id = shardID
}
displayShards.push(typeof results === 'object' ? results : results[0])
}
It does takes a bit of time, can take an hour or two lmao
Lmao
they generally don't restart for no reasons, they do maintenance downtimes etc to minimise it
_But, I would be surprised if many people are concerned about getting 200 shards 👀 _
I mean the big bots with 1 Millionen 2 Millionen servers
Discord enforces ratelimits on the gateway/bot path. You can connect Websockets every 5.5 Seconds. So you cant start your Shards at once.
More over Bots over 100k have a higher Shard Concurrency, the can start 16 Shards and then have the 5.5 Seconds cooldown
And most big Bots do rolling restarts, start shard 1, kill shard 1 on old Process....
Normally for it to be stable, about 1200 servers per shard is ideal
you are doing it weird lol, lemme show
client.shard.broadcastEval((client) => {
return {
id: client.shard.id,
guilds: client.guilds.cache.size,
guildsAvailable: client.guilds.cache.filter(({ available }) => available).size,
users: client.users.cache.size,
ms: client.ws.ping
}
Now you can pass the Data Here
Can you adjust that
Yes
Where ?
Personnaly client.shard.id return undefined
In your sharding manager file
use client.shard.ids[0]
I'm using djs 13 Meister
yeah, ik
Yes, when I can, I do, but here it's complicated because I want the informations from all my shards :/
I'm sorry if it's not clear :x
Ah yeah I see what you mean
It's better this way, thx x)
const displayShards = []
const shards = this.client.shard.ids // return only [0] or [1] but not [0, 1]
for (const shardID of shards) {
const results = await this.client.shard.broadcastEval((client) => {
return {
id: client.shard.ids[0],
guilds: client.guilds.cache.size,
guildsAvailable: client.guilds.cache.filter(({ available }) => available).size,
users: client.users.cache.size,
ms: client.ws.ping
}
}, { shard: shardID })
displayShards.push(results)
}
you do not have to provide a shardID
Lmao i'm tired thanks 

is client.ws.shards.size the number how many shards i have?
cool
but when i spawn 2 shards for testing it only has 1 shard
even tho i spawned 2
client.ws.totalShards
oh
but why did you say yes then ._.
anyways still shanks tho
Well I didn't know ws.shards.size wasnt accurate
btw that doesnt exist
its a private property
rip ts then
still nothing
same result both give 1 no matter now many shards i spawn
then idk
oof thanks tho
ill just do it via broadcasteval
O, You can use that and get the length of what it returns
yup
any way to allocate more ram to worker threads? currently getting OOM errors on workers, and letting node use more doesn't do anything as the bot runs on worker threads through sharding
TypeError: Cannot read property 'members' of undefined
at eval (eval at _eval (/home/runner/Kon-testing-1/node_modules/discord.js/src/client/Client.js:460:12), <anonymous> : 1:57)
at eval (eval at _eval (/home/runner/Kon-testing-1/node_modules/discord.js/src/client/Client.js:460:12), <anonymous> : 1:228)
at Client._eval (/home/runner/Kon-testing-1/node_modules/discord.js/src/client/Client.js:460:12)
at ShardClientUtil._handleMessage (/home/runner/Kon-testing-1/node_modules/discord.js/src/sharding/ShardClientUtil.js:188:82)
at MessagePort. [nodejs.internal.kHybridDispatch] (internal/event_target.js:399:24)
at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)```
this popped up when I tried spawning multiple shards in the worker mode :P
I feel stupid
It's from my index.js file
app.post('/dblwebhook', wh.listener(async (vote) => {
let user = await client.shard.broadcastEval(`this.users.cache.get('${vote.user}')`)
if(!user) return;
hook.send(`O usuário ${user.id} votou no **Milo** pela **top.gg**`);
}))
This code of mine gives me an undefined user id, how can I solve it?
does anyone know how to fix this
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
@sour merlin add manager.spawn(undefined, undefined, -1)
didnt work
const config = require('./config.json');
const logger = require('./utils/logger');
const Discord = require('discord.js');
const Statcord = require("statcord.js");
const { token } = require('./utils/variables.js');
const manager = new Discord.ShardingManager('./index.js', {
token: token,
//autoSpawn: true,
//totalShards: 'auto'
totalShards: 1
});
manager.spawn(undefined, undefined, -1)
manager.on('shardCreate', shard => logger.info(`Launching Shard ${shard.id + 1}`, { label: `Shard` }));
this is my code
This returns a array
Did you logged in your bot.js file?
check if there is a client.login
this is my main file
you index.js file , do you login there with the Client?
Bruh idk what happened I didn’t change anything and I kept it up for an hour and now it’s working yesterday even after 12 hours it was the same but today it’s working I’m so happy now
Is there any way to do a restart per shard and one after one? So I don't have to restart the process with pm2 and wait for 2 minutes to run the complete bot
What?
what is sharding?
Google it.
Sure, there's a method for it https://discord.js.org/#/docs/main/stable/class/ShardClientUtil?scrollTo=respawnAll
I did already
That's from a few hours ago
hello im new
hello new, I'm Feralheart
?off topic
Please use #archive-offtopic for all off-topic discussion.
How can I host specific shards but on different hosts?
specify shardLists option on each manager with the shards you want on that machine or use a package
Documentation suggestion for @winged bobcat:
ShardingManager#shardList
List of shards this sharding manager spawns
...
can you use hotswap commands eg reload, unload, load etc in a sharded bot? im assuming no because of the multiple processes but i wanted to check
@winged bobcat What package dogoy recommend
Dms
thanks
hey, its been like 2 days and my bot wont come online due to sharding errors, its currently in 5.5k servers. I tried everything but it wont work.
screenshot from debug logs, this all happens when I start the bot
the last time it happened was due to a discord problem so I was hoping it was the same thing time but nothing from discord yet..
how can i get total member count from all servers in one shard
Anyone why owner is not returned in broadcastEval of a shard. ownerID is but not owner. Its in the normal guild function but when you get that from the shard the variable is not there
May I ask, are you using discordjs v12? Also, can you send your current broadcastEval code setup?
Yes im using 12, and
```target = await shard.broadcastEval(this.guilds.cache.get("${targetID}")).then((total) =>
{
const temp = total.filter(Boolean);
shard.target = temp[0];
});```
might be a bit sloppy, but it gets some of the data, problem i have is lots of my code referes to data.messasge.clinet.guilds.cache.get (Or similar) and this only returnes data for the shard the command is run on, but i want to find a way to identify the shard a guild is on then get data from that shard
so like this (If it worked)
target.members = data.message.client.shard[SHARDIDHERE].guilds.members.cache.get(targetID);
Based on my understanding, you should be able to do something like this:
const guild = this.guilds.cache.get(`${guildid}`);
if (guild) {
doActionOnGuild()
};
This way, only the shard that has that guild will execute the code
so it does and it doesnt
the code run on all server, but if the server the command is run on is not on the same shard it does not work.
so this is the command file i have
It creates an invite for a server the bot is on, it work perfectly if the bot is not sharded, but as soon as i shard the bot it only work if the target server is on the same shard as the server i am running the command from
does that make sense or am i missing something. @jade onyx
So you want to create an invite for a guild with an ID targetID?
Yea, so the command is !tr invite server {id}
so i provide it with an ID and it creates an invite for that server, my bot is in 1600 servers, is a dev only function when the users has given permission and run the support command on their server, its not used to join random server ect ect, but if i ran this now, for a server that is not on the same shard as the shard i am in it wont work.
It says it can be run on a given shard, just dont know how to do that,
client.shard.broadcastEval(`
const guild = this.guilds.cache.get(`${targetID}`);
if (guild) {
guild.systemChannel.createInvite();
};
`).then(c=>console.log(c));
This code works for me and logs the invite in console.
(backticks may need escaping)
no luck, its not working for me
any idea @jade onyx, thank you for helping BTW
Is there an error? What is it logging?
Its not logging anything, just wont run.
now i'm getting undefined
Got it working.
thank you, It got me looking in a diffrent place and now i can figure it out
Yeah, .code will actually be undefined (oops!)
You'll need to filter the array to exclude the null values and then get the .code of that one
can someone ban this indog outta here for advertising
@light oar
@terse cairn literally advertised on the sharding channel
?ban 461468886920069130 ads
You sure you want me to ban this [no gender specified]?
Y
Successfully banned apaan lu#1111
Just ping mods
<@&839912195994812420>s
I have a kinda dum question so when I shard my bot what will I have to necessarily use broadcast eval for?
I guess contacting other shards. Such as find a guild from a shard
in a bot without shards, you can use client.guilds.cache.array() to get an array of all guild data
is there a way to do this in a bot with shards? if so, how?
(my bot is currently live on 7 shards)
How would I give required/imported modules access to a value, without needing to pass the value through to them? And without using globalThis (since I want other shards to not have access to said value).
For example, I don't want to have to pass my database connection object through the message handler, to the command each time a command is run that uses the database.
I already do that with discord.js's Client object, but would like to try eliminating the need for that too.
Yes, and yes - if you're using internal sharding.
Otherwise you need to figure out how to do that yourself, on traditional sharding.
Sounds like it's not very related to discord.js.
However, have you just considered requiring the database connection file/object directly, rather than passing it through method params?
With internal sharding. Is there a way to force the number of shard I want.
With a sharding manager I can set say 2 or 3 ect ect but when ever I set a number on internal sharding it gives me an error saying it has to be auto a number or an array of numbers
pass an array of required number. For example if you wanna spawn 5 shards, pass [0,1,2,3,4]
?shard
const { ShardingManager } = require('discord.js');
const Manager = new ShardingManager('./bot.js', { token: 'your-token' });
Manager.spawn();
https://discord.js.org/#/docs/main/stable/class/ShardingManager
For an in-depth guide: https://discordjs.guide/sharding/
?sharding ready timeout
?shardingreadytimeout
Thank you.
could someone help me with sharding ready timeout
even after adding JS manager.spawn(undefined, undefined, -1) it doesnt work 😦
any reason this wont work
const discord = require("discord.js");
const client = new discord.Client({
"shardCount": 3,
"shards": [0, 1, 2]
});```
i have tried it with just shards and just shardCount neither are loading more than one shard.
Should work with shards alone
perhaps omit shardCount?
Still only creates one shard
as you can see, it still says shard are null
why is my bots status not on the 2nd shard?
its only on the first shard
Ignore me, it is working, im just looking in the wrong place as im stupid
ive tried alot of methods on this issue but non of them worked 😦
manager.spawn(undefined, undefined, -1)
even with this it doesnt work
Edit one of the fields
What is sharding? :O
https://discordjs.guide/sharding/
Pins
TL:DR when your bot is in many guilds, split it up into smaller chunks
How can I execute a command on each shard using a .eval?
I mean something like client.emit('event') for events, but for commands
Use broadcastEval()
Hello, I don't understand this bug.
It causes a lot of troubles like fetching the invitations of users, the status of the bot is never available, etc...
show code
Hello, I have sharding on my bot (2 shard) and i got this error how to fix it?
TypeError: Cannot read property 'send' of undefined
message.channel.send(embed1)
I have exacute the command like this
Getting command and run it
bot.commands.get(command).run(bot, message, args)
Command Export
module.exports.run = async (bot, message, args) => {}
There is no problem before sharding but when i started sharding it shows that error.
(Sorry for my bad english :( i'm trying my best)
Hello, I need some help with discord.js sharding(I'm new for sharding).
Additional information : My bot already 1 shard i'm am reaching 2 shard
- What part of a code do i need to change/edit?
^^^^^ Ex. Send message, Fetch channel by id, Fetch channel across shard - How can i increate the shard like 600 server for 1 shard
- What happen if i login with multiple client like the one for general system one for music system but the both is sharding (Is it affect anything?)
If the bot needs to interact with different shards, then change that code
The sharder automatically splits the guilds in each shard
I am pretty sure that sharding does not effect it
hi it's not a bug when you are not hosting your bot with shard it return null
Try to verifiy that u are using shard & use message.guild.shard & wait for all shard to be spawned before execute the command
the problem is not that.
when you shard a bot will it always split guilds evenly between shards?
I want to test my code on a smaller bot that has like 5 guilds on it, to make sure my code doesnt break when the bot is sharded. But im unsure if sharding the smaller bot will even create shards.
I am pretty sure djs sharding does not even split the shards. Ex 100 servers shard 1 52 servers shard 2 48 servers
Discord decides, which Guilds belongs to which Shard(Nr.) based on the total Shardcount.
You can calculate it with the modulo
then describe your problem & give some code to debug though
what if the bot only has like 5 guilds? will the guilds still be splitted between shards??
the point is i want to test if my bot's code words when sharded, but obv can't just test it on the live bot.
They will be split
My test bot is in 3 servers and I spawn 2 shards and it gets split
the shards got split
can I use multiple bot tokens when sharding?
nope sharding is for one bot
do you manually spawn 2 shards? my test bot is in two servers but it only spawns 1 shard
Yea I manually spawn them
how do you do that?
you just provide the shard count instead of auto xd
Does anyone have a good sharding tutorial?
I dont like using the documentation because its so impractical and confusing xD
Whoops sorry!
Is there a point where the bot needs to start sharding? When does it become required
1.5k guilds iirc
2.5k
Code:```js
app.post('/dblwebhook', wh.listener(async (vote) => {
let user = await client.shard.broadcastEval(this.users.cache.get('${vote.user}'))
if(!user) return
hook.send(`O usuário **${user[0].tag}/${user[0].id}** votou no **Milo** pela **top.gg**`);
}))
`Cannot read property 'tag' of null`
can a gentle soul tell me how to solve?
Does sharding make error messages repeat for anyone else? seems like everytime the bot encounters a fatal errors the sharding manager tries restarting the bot.
my bot is taking ages to come online
Sends this twice
UnhandledPromiseRejectionWarning: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
Then comes online
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
how do i force the shardmanager to create 2 shards for example when the bot only has 2 guilds?
ShardingManager#totalShards
Amount of shards that all sharding managers spawn in total
@terse cairn ⏫ provide a Total Shard count
oh
i thought it was something i had to pass to the client constructor
Thanks, it worked
weird, shard 0 returns an error Reduce of empty array with no initial value when I don't pass "shards: 'auto' to my client constructor
is it because there are too few guilds to split between 2 shards (the bot is in 2 guilds)
bc, Discord decides which Guild belongs to which Websocket
On 2 guilds, its likely that the other shard has no guilds on the Websocket
how many guilds do i need to support 2 shards?
it's a small bot because i use it for testing if my other bot's code works when sharded
You don't need to shard and you shouldn't shard if you're bot is only in 2 guilds...
it's a small bot because i use it for testing if my other bot's code works when sharded
How to use message.guild.members.cache in Shards?
Use broadcastEval()
If it’s fetching a member
client.shard.broadcastEval(this.message.guild.members.fetch())?
If it’s within the guild you don’t need to
It’s only used when fetching from different shards
So I've got a large bot quickly closing in on 50 shards, running smoothly on a Raspberry Pi 4. Now that I've switched to slash commands and interactions, instead of messages, the RPi4 maxes out around 3% CPU. However, the memory usage is through the roof.
Each shard uses a MySQL connection pool. Each connection reserves, but doesn't necessarily use, ~5%+ memory. How do you's get around this? I was thinking, instead of having each shard create a connection pool, have the ShardingManager create the only pool, and have each shard send the MySQL queries to the ShardingManager.
Is this possible? Are there other options?
there is a easier way. Cluster your Bot:
Example:
10 Internal Shards in 1 Cluster
So you come to 5 "Processes" instead of 50.
On Npm there are some Packages
When your Cpu usage isnt so high, then Clustering is reasonable
hello i want to shard my bot but an express server is running in my bot and if i make shard number 2 each shard uses the port of my express server 3000 and this creates an error how can I solve it?
dont run more than 1 server boom problem solved

2 solutions:
Make an external file where you import it from the main file
Or:
let it run on the server shard count + 1
just create a server on your shard.js file
thx
so im having this problem with shards:
Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
theres my code:
const Discord = require('discord.js');
const manager = new Discord.ShardingManager('./index.js', {
token: 'my-token',
totalShards: 2
});
manager.on('shardCreate', shard => console.log(`Launching Shard ${shard.id + 1}`));
manager.spawn();
shard one is having problems, its not showing status in shard one but is showing in shard two
commands work on both but its just not showing status in one
When using a ShardingManager, we can use the shardCreate event. If using the shards: 'auto' ClientOption, where do we find that same event? The only Shard events emitted by Client are:
• shardError
• shardReady
• shardReconnecting
• shardResume
Thats because the client uses internal shards which are just multiple websocket connection rather than traditional which creates multiple process so the event shardCreate gets emitted when a new shard process is created
Right, but it would still seem useful if internal sharding would emit a shardCreate event when it spawns a new socket. Or am I just not seeing how to do it?
No there is no proper way and i highly doubt that it would be implemented
But you can use the debug event to see when a shard connects
for some reason i've begun getting this error, despite my "ready check" being displayed before the error
(node:350) UnhandledPromiseRejectionWarning: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
these are my sharding configs
index.js
const { ShardingManager } = require('discord.js');
const mySecret = process.env['token']
const manager = new ShardingManager('./bot.js', { token: mySecret });
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn();
bot.js
const client = new Discord.Client({ shards: 'auto' });
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
any way to allocate more ram to worker threads? currently getting OOM errors on workers, and letting node use more (--max-old-space-size=16384 doesn't do anything as the bot runs on worker threads through sharding
is there someone who could explain what sharding is or a link or something? not exactly sure what it is and what to use it for
?sharding
const { ShardingManager } = require('discord.js');
const Manager = new ShardingManager('./bot.js', { token: 'your-token' });
Manager.spawn();
https://discord.js.org/#/docs/main/stable/class/ShardingManager
For an in-depth guide: https://discordjs.guide/sharding/
sometime one guild is getting cached in multiple shards, how to stop it?
That shouldn't happen. How are you sharding?
ShardingManager
sometimes getting same guild id in this.client.guilds.cache.keyArray() in different shards
Can you share where you define your sharding manager.
sharder.js
const manager = new ShardingManager("./index.js", { token: require("./config").token, respawn: true, totalShards: totalShards, shardList: shardList, mode: 'process', shardArgs: [...process.argv, ...['--sharded']], execArgv: ['--trace-warnings', '--stack-size=1024', '--stack-trace-limit=1000', '--async-stack-traces'] });
What do totalShards and shardList log as?
totalShards = 12
shardList = [0,1,2,3,4,5,6,7,8,9,10,11]
so even one guild is cached in shard 7 or 5 or some other shard, it also sometime get cached in shard 0 also
Try removing both of those (or setting them both to "auto") and see if it makes any difference.
ok
to be on safe side can i do something like this before processing anything
if (guild.shardID != this.client.shard.ids[0]) return;
I mean it's your code you surely can?
Might be a bit unnecessary though if the issue was already fixed by the above
@ashen musk ?
sorry for the ping
You can always ping me. No problem.
Did the above not fix the issue?
@hoary stream ^
still testing as this happens only sometimes not always
maybe the Guild got fetched on your Code, accidently
how can I monitor sharders?\
does this issue related to sharding ?
help im getting this error
UnhandledPromiseRejectionWarning: Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
code:
const Discord = require('discord.js');
const manager = new Discord.ShardingManager('./index.js', {
token: 'my-token',
totalShards: 2
});
manager.on('shardCreate', shard =>
console.log(`Launching Shard ${shard.id + 1}`));
manager.spawn(undefined, undefined, Infinity);
Pretty sure heroku is blocked by discord.
Remove that spawn() line.
not working on local hosting too
why is it blocked?
Ask discord 
I think I saw someone earlier in #archive-djs-v12-deprecated use heroku for their bot.
But anyway this isn't really on-topic anymore
hey this code only reloaded the command in one shard
client.shard.broadcastEval(
delete require.cache[require.resolve(`../${folderName}/${command.name}.js`)]
)
try {
const newCommand = require(`../${folderName}/${command.name}.js`);
message.client.commands.set(newCommand.name, newCommand);
message.channel.send(`Command \`${newCommand.name}\` was reloaded!`);
} catch (error) {
console.error(error);
message.channel.send(`There was an error while reloading a command \`${command.name}\`:\n\`${error.message}\``);
}
i want it to reload the command in all shards
Probably need to reference the client on each shard instead of message.client
so like client.shard.broadcastEval.commands.set(newCommand.name, newCommand);?
(i cant try and see because it takes like 5 minutes for the bot to get to all shards and ppl are using it rn and i dont wanna make ppl mad)
No idea, I don't do sharding. That's just my guess based off using message.client
@ me if someone has a answer
Discord didnt block heroku (Pls inform yourself before providing such Information)
thats not how broadcastEval works
you broadcast a string (or function in v13)
It would be client.shard.broadcastEval("this.commands.set('${newCommand.name}', ${newCommand})")
let thing = await manager.broadcastEval(async (client, id) => {
let user = await client.users.fetch(id);
user.send("test")
}, { context: req.query.userId });
How do I pass multiple contexts? 
context is an object, not a string.
{
context: {
id: req.query.userId
}
}
However, isn't this #djs-help-v14 ?
@lusty smelt you're on v13, yes?^
Yea!
Best moved to #djs-help-v14, but that should be the fix you need
@lusty smelt (keep forgetting to reply)
tyty!
Code```js
client.users.cache.forEach(async (member) => {
let db = database.ref(Backpack/${member.id}/meat).remove().then(() => {
console.log(Success)
})
})
How can I do this method on shards?
that gives me this error
<rejected> { Error [SyntaxError]: Unexpected identifier
at Client._eval (D:\Discord Bot\nagito\node_modules\discord.js\src\client\Client.js:425:17)
at ShardClientUtil._handleMessage (D:\Discord Bot\nagito\node_modules\discord.js\src\sharding\ShardClientUtil.js:187:82)
at process.emit (events.js:198:15)
at emit (internal/child_process.js:848:12)
at processTicksAndRejections (internal/process/task_queues.js:81:17) name: 'SyntaxError' } } reason: { Error [SyntaxError]: Unexpected identifier
at Client._eval (D:\Discord Bot\nagito\node_modules\discord.js\src\client\Client.js:425:17)
at ShardClientUtil._handleMessage (D:\Discord Bot\nagito\node_modules\discord.js\src\sharding\ShardClientUtil.js:187:82)
at process.emit (events.js:198:15)
at emit (internal/child_process.js:848:12)
at processTicksAndRejections (internal/process/task_queues.js:81:17) name: 'SyntaxError' }
client.shard.broadcastEval(
delete require.cache[require.resolve(`../${folderName}/${command.name}.js`)]
)
const newCommand = require(`../${folderName}/${command.name}.js`)
client.shard.broadcastEval(`this.commands.set('${newCommand.name}', ${newCommand})`)
you didnt broadcast a String
i tried to broadcast a string but now it says that folderName is not defined when it is defined right before the broadcast
const folderName = commandFolders.find(folder => fs.readdirSync(`./cmds/${folder}`).includes(`${command.name}.js`));
client.shard.broadcastEval(
"delete require.cache[require.resolve(`../${folderName}/${command.name}.js`)]"
)
const newCommand = require(`../${folderName}/${command.name}.js`)
client.shard.broadcastEval("this.commands.set('${newCommand.name}', ${newCommand})")
Has anybody experienced this error before, when the shards spawn/bot comes online it triggers the guild leave event, but it isnt actually leaving any servers
https://link.michaelross.me/michael-s3/Discord_4h9kAudMNq.png
So i dug this backup from an older question relating to the same issue
https://github.com/discordjs/discord.js/pull/5367
Code:
if (client.shard.ids[0] == null || client.shard.ids[0] == 0) {
client.on('ready', () => reqEvent('ready-web')(client, database));
}
```**Error:**```js
Cannot read property 'ids' of null
at /home/runner/LePatron/index.js:27:18
How can I solve this?
how would i set the client status to be
Shard: shard id/total shards
thats probably, when guilds get unavailable
or uncached guilds
@lusty smelt after 1 week djs v13 and many internal shards. I can say that none of them crashed unexpectly. I didnt experienced any issues...
Its probably bc of zlib (compression)
I figured it out recently. It was because the bot was unable to resolve messages with select menus.
lol, good
um why?
hey why my bot shards always get disconnected it's really annoyed bc they don't respawn i need to restart my bot each time it's not my code fault i've fully optied
why do u want to delete from cache ?
How do I get the shard count of my bot?
Just have respawn: true
to reload the file
How do I get the shard count of my bot?
client.shard.count i think
Ok. So I am sharding my bot, but I am creating a server in bot.js. Since I have 2 shards, it creates 2 ports. How do I make it so it only creates 1 port. Note: I have to create my server in bot.js
you can check if the client shard id is 0 using <Client>.shard.ids
Do you need to have 2,000+ guilds to shard?
Nope, you can do it whenever you want
Okay thanks you
You would need to place the server in the Sharding Manager file
If your using traditional sharding: you can broadcastEval anything and use check the array length
Internal: check the array length of the property ids on client.shard
ok
hey how do you parse through object between shard bc i have backup system i put backup in cache put it's not availbale on other shard how do i do ?
why is my bots status not on every shard?
did you code it to change the status on every shard?
nvm there was an error
all fixed ty
lovely to hear that you have fixed it!
Do what it says and increase the max listeners ig
Anything else logs before those errors
Ahhhh you need to have your express server run in the file with the ShardingManager
?
Just require the dashboard file in the ShardingManager file like you do in the error event
We're not here to explain modules/express. Check out #resources for information on that.
how would i set the client status to be
Shard: shard id/total shards
?ban @analog flax shitpost in support
You sure you want me to ban this [no gender specified]?
y
Successfully banned cool boi abc#3709
everytime i use my shard stats command it shows cannot read property of broadcastEval
any solution for this?
client.shard is null
you are probably not sharding or using it wrong, could you show your code?
ok wait
const {ShardingManager} = require('discord.js');
const config = require('./config.json');
const shards = new ShardingManager("./index.js", {
token: process.env.token,
totalShards: "auto"
});
shards.on("shardCreate", async (shard) => {
console.log(`[${new Date().toString().split(" ", 5).join(" ")}] Launched Shard #${shard.id}`);
});
shards.spawn(shards.totalShards, 10000);```
is this okay for sharding??
yes, its okay
bruh after sharding the ping is like 10k + ms
hey why discord.js sharding is so fucking bad and when shard dies they no respawning with the options respawn true
So I’m trying log a guild when my bot gets added to a new server, but some guilds aren’t being logged after I started sharding. How do I make it so that I can log every new guild on both shards
You cant, the guild will only be logged on the shard its assigned to
Are there any errors
Shard Create```js
const { ShardingManager } = require("discord.js");
const manager = new ShardingManager("./index.js", {
token: process.env.TOKEN,
respawn: true,
autoSpawn: true
});
manager.spawn(2, 3000, -1);
manager.on('shardCreate', (shard) => console.log(Shard ${shard.id} Iniciada.));
**Code**```js
if(client.shard.ids[0] == 0 || client.shard.ids[0] == null) {
client.on('ready', () => reqEvent('ready-web')(client, database));
}```**Error**```js
Cannot read property "ids" for null // this in repl.it
anyone for help me?
I have question?
What do shards do?
splits the bots code
no lmao just some few missing perm how can i log error of shard
like wtf some shard respawn all the time it’s not stable and other just died and never respawn
Are you sure that the shards aren't throwing errors? There must be a cause of the shards randomly dying
Does dms use sharding?
What do you mean? DMs don't use sharding, clients use sharding. lol
I mean, if a user send a dm to a bot, will client.shard.ids have value
On a sharded bot, of course.
However, (don't quote me on this) I'm fairly certain that DMs always come in on shard 0
thank you
how he can see if he throwing errors
this is incorrect it uses multiple websockets instead of 1 each for separate guilds to provide higher performance across many guilds
how do logs that ?
TypeError: Cannot read property 'members' of undefined why i got this if on shard? i never got this when not sharding
Recently i implemented sharding
how to avoid that? that make my donators command broke
You might want to show relevant code.
Why this dont works?
client.on('guildDelete', guild => {
client.shard.broadcastEval(`this.channels.cache.has("851699234917974033") ? this.channels.cache.get("851699234917974033").send("**New guild** \nName: ${guild.name} \nId: ${guild.id} \nMembers: ${guild.members.size}") : null`)
})
It returns error:
(node:104496) UnhandledPromiseRejectionWarning: SyntaxError: Invalid or unexpected token
at Client._eval (C:\Users\ME\Desktop\kloce bot\node_modules\discord.js\src\client\Client.js:425:17)
at ShardClientUtil._handleMessage (C:\Users\\Desktop\kloce bot\node_modules\discord.js\src\sharding\ShardClientUtil.js:187:82)
at process.emit (events.js:327:22)
at emit (internal/child_process.js:903:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
(node:104496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:104496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
pls help
?syntax
If you get a SyntaxError, that means that you may have forgotten to match a brace, bracket, parenthesis, quote, or something else.
To get warned about syntax issues before you even run the code, install a linter (do ?linter in #app-commands)
shard 0 took too long to start and that's causing an error with an npm, it there any way for make shards starts faster?
Fixed it u cant use \n 🤣
i just updated to the latest version of discord.js and using the master branch, and i'm getting the error, Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready., how would i be able to fix it?
[WS => Shard 0] Shard did not receive any more guild packets in 15 seconds.
Unavailable guild count: 1
is this due to an api issue (outage) or did i break something on my end?
It could be a slow connection or a guild is unavailable/ is having an outage
?ban 801088898217410570 ads
You sure you want me to ban this [no gender specified]?
y
Successfully banned Shreyansh#6963
I have this error
why ?
?shardreadytimeout
Got this error: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.?
The spawnTimeout can be set to -1 or Infinity to prevent future errors:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn. This can also happen if you call ShardingManager#spawn before attaching a listener to the shardCreate event which could create a race condition possibly preventing the shard 0 to perform a successful launch.
^
ty
Hi, i recently implement sharding.
i have like this:
let serverku = client.guilds.cache.get("828543860127957025");
const allMembers = await serverku.members.fetch();
const membersWithRole = allMembers.filter(m => m.roles.cache.has('869070720787939338'));
// fetch ids of all members with role
const donator = membersWithRole.map(m => m.id);
console.log(donator)
its working properly in non sharding, but now i got TypeError: Cannot read property 'members' of undefined
how to fetch ids of all members with specific roles?
can't use map() in broadcastEval
Thats because the guild is not on the current shard, so you need to get it through broadcastEval
how i can add shard id to bot activity ?
client.shard.ids[0]
if your using internal status i suggest you use the shardReady event and set the status to display on that shard with the id provided from the event
ok
What is Shards and what do they do :?
const manager = new ShardingManager('./OFF/offlimits.js', { token: config.token });
Cannot create property 'shardCount' on string 'token'```
I am have const shards = [client.ws.shards.values()] and I want to see all the ways I can use shards like shards.length. Is there any docs for this because console.log(shards) gives me [ [Map Iterator] { } ]
I use this.client.options.shardCount not sure if this is what you're after
You forgot the spread operator
[…<Map>.values()]
I am trying to create a status page which shows the status and latency of each shard.
Oh
What do you mean?
Can’t you just broadcastEval then?
I have tried that but it has so far not been a success.
Show code
Use my code for an example: js const whatever = await client.shard.fetchClientValues('ws.ping') ${whatever[0]}ms ${await client.shard.broadcastEval(true, 0).catch(err => `${err}`) ? ' Online' : ' Offline'}
I don’t have it right now as I am on my phone however my issue was broadcasting it to a specific shard, if you maybe look at my message history using ctrl + f then you may be able to see
You have the shard id defined, but never used it
Always passing in 0 for the id
What does it output?
Again, can’t tell you as I am on my phone now
Read what the message says, when I change the 0 to req.params.id (which equals 0), it broadcasts it to shard 1 and not 0
hello there,
i need some help i ran into problem i have a bot which recently hits 1500+ servers, while i today checking the stats it's showing half of the servers in the stats and few days back i shard the bot, can anyone tell me how i can get the full amout of serves with sharding.
Prob need to convert the id to a number
I’ll try that later.
Broadcast to all shards, add up to the total
There is an example for this on the docs
oh ok
any example with command handler
1st line is getting the ping, 2nd line is getting the ping for shard 0, 3rd line is getting the status of shard 0 whether it's online or offline
bestie
?kick 756503000016486402 spamming threads in support
Successfully kicked ThatOneExplorer#9387
How would i get an argument "inside" of a broadcastEval?
Hey! How can I make regional shards?
are you talking about internal shards?
No, like for each VC region we have a shard for minimal latency
If you know what we mean
Yep ^^
No thats not possible, you either have all your shards in one region or have some shards in each region which is not recommended as a guild on x shard could be in a completely different reason and can effect the VC experience
How can I do some shards in each region then
Pass the shardList on the Shardingmanager options with an array of shard ids you want the ShardingManager to spawn
?docs ShardingManager#shardList
Alright thanks!
after im trying to spawn the bot, I think the bot is not really stable, shard keep reloading. I'm using v12, any advices ?
which error are you getting?
I'm aware you receive a regular object when doing this. How can I get the usual guild structure instead?
client.shard.broadcastEval(client => client.guilds.cache.get(guildId));
@steep otter check this
How do I change the number of shards and how many servers go on each?
when you are using internal Sharding: shardCount
When you are using the ShardingManager manager.spawn(shardcount)
You can decide, how much guilds will belong in 1 shard.
Discord decides how many servers will be a shard. But you can make a rough calculation
Oh cool ty
Does anyone have a shard friendly ping command?
Thanks. Tried extracting and/or utilising that, didn't succeed
client.shard.broadcastEval('this.ws.ping')
Thanks, I'll give it a go
Sorry, I probably have something wrong, but "This" isn't working, it returns null
const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./bot/bot.js', { token: process.env.token });
manager.on('shardCreate', shard => {
console.log(`Launched shard ${shard.id}`)
});
manager.spawn();
This is my setup
My folder paths: https://pixel.is-inside.me/Rm99r7Ya.png
your bot has to become ready
It should be ready, I have a ready event that gets triggered
So, the process is:
- Run index.js which spawns 1 shard of bot.js
- Bot.js loads commands from ./bot/commands
- When a command is run, the command file is run given the client and message parameters
Oh sorry, I got it working. Thank you so much!
Sorry again, what is the correct version of this.shard.shardID?
Hey, for me that returns null. I'm not sure why but this.guilds.cache.size returns fine
I'm having to use this.guilds.cache.first().shardID
And this.users.cache.size is returning the same as this.guilds.cache.size
const { ShardingManager } = require('discord.js');
const config = require('../../config.json');
const shard = new ShardingManager('./app/bot/bot.js', {
totalShards: 1,
token: config.bot.token
});
shard.on('shardCreate', shard => {
console.log(`Shard ${shard.id} is started.`);
});
shard.spawn();
Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready.
Can you please send bot.js
How would I go about leaving a guild and doing it nicely?
I've tested the below, which works, but it does .leave() for every shard, which spits out errors
client.shard.broadcastEval((client, { args }) => client.guilds.cache.get(args[0]).leave(), { context: { args: args } });
?.leave()
If you know the shard count, you can determine which shard to send it to
(static) ShardClientUtil.shardIDForGuildID()
Get the shard ID for a given guild ID.
uhh... can I just try sharding as testing right now ? I am not going to keep it for ever... Bot is in almost 60 guilds 😐
ping in reply
Sure, afaik there’s only a bug when sharding with 1 guild
well, thats obvius, I just wanna create like 1 shard where on shard 0 goes some servers and some on shard 1.
basicly 1. [0 & 1]
You can’t specify which guilds go to which shard
It’s determined by a formula
What's the formula
(static) ShardClientUtil.shardIdForGuildId()
Get the shard id for a given guild id.
module.exports = {
name: "shard-stats",
async run (client, message, args) {
let values = await client.shard.broadcastEval(`
[
this.shard.id,
this.guilds.size
]
`);
let finalString = "**SHARD STATISTICS**\n\n";
values.forEach((value) => {
finalString += "> SHARD #"+value[0]+" | Servers: "+value[1]+"\n";
});
message.channel.send(finalString);
}
}```
**AFTER I RUN THIS CODE, IT GIVES AN ERROR SAYING:**
```(node:11736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'broadcastEval' of null```
i'M UNABLE TO FIGURE OUT WHAT THE ERROR IS :/
client.shard is null, your bot is not sharded
what
impossible
wait imma show you
could you log out client.shard
const config = require('./config.json');
const shards = new ShardingManager("./index.js", {
token: process.env.token,
totalShards: "auto"
});
shards.on("shardCreate", async (shard) => {
console.log(`[${new Date().toString().split(" ", 5).join(" ")}] Launched Shard #${shard.id}`);
});
shards.spawn(shards.totalShards, 10000);```
ISN'T THIS THE CODE? FOR SHARDING?
yes it is
could you do this
where do i do it?
it's sharded,
i guess this wont work if it was not sharded
i see
on the ready event
ok
How do I get CPU usage on a shard?
hello, what does the replayed event parameter in the cliend.shardReconnect mean?
I'm curious why the error variable is undefined inside the broadcastEval. I believe I've "imported" it correctly into the context. The test variable works as expected.
...
catch (error) {
console.log(error); // This works
let test = "test_string"
client.shard.broadcastEval(async (c, { error, test }) => {
console.log(error); // This prints an empty object
console.log(test); // This prints "test_string"
}, { context: { error, test } })
}
Doing the following and then using errorNew instead does work, however. Apologies if this is more JS than related to sharding
const errorNew = {
name: error.name,
message: error.message,
code: error.code,
stack: error.stack,
};
Is there anyway to host a bot on many separated physic servers?
context gets stringified using JSON.stringify which only serializes enumerable properties and Error has none
Ahh, thanks
Yes, u need to pass the shard ids you want spawned in the shardList option on the manager for each machine
How do I get CPU usage on a specific shard?
I built a fully functional "Portable IDE Sandbox"
shard_id = (guild_id >> 22) % num_shards (https://discord.com/developers/docs/topics/gateway#sharding)
Please don’t revive dead/old convos
How do I get the number of shards?
i need help
I have done the fragmentation in my discord bot, 3 shards have been generated, but in the last shard (3) the commands do not work, only the log events
Shard Count:
client.shard.count [Number]
client.shard.ids [Array of ShardId's]
How much guilds does your Bot have? when the amount is small, not all shards serve a guild
Thank you. Do you happen to know how to get shard CPU and RAM usage?
On Worker_Threads (worker mode):
It is process.memoryUsage().rss/1024/1024
On Child_Processes (process mode):
It is client.shard.broadcastEval('process.memoryUsage().rss/1024/1024')
Get Cpu Usage:
async function cpuUsageCompact(time) {
const start = [process.hrtime(), process.cpuUsage()];
await new Promise(r => { setTimeout(r, time); });
const elap = [process.hrtime(start[0]), process.cpuUsage(start[1])];
return 100 * ((elap[1].user / 1000) + (elap[1].system / 1000)) / ((elap[0][0] * 1000) + (elap[0][1] / 1000000));
}
Oh wow! tysm!
I'm either reading the results wrong or I need to get a new VPS (Ignore the lack of shards, I'm only testing) https://pixel.is-inside.me/86rWzAgA.png
I multiplied the CPU usage by 100 because .2% didn't look right
what did you provided as time on teh function?
Oh 250
I didn't want it to take so long for response so I may add an edit to replace a blank field after its been measured
https://pixel.is-inside.me/FNLeuugv.png Increased to 1000 - this look better
Can confirm, I have done something wrong https://pixel.is-inside.me/BmnyciTE.png
I guess its just really efficient as @terse cairn says https://pixel.is-inside.me/X414041Z.png
It's on a 2vCPU server sooo I'll upgrade it to 4vCPU
I see. Thank you all so much!
Oh and is that RAM normal for an empty shard?
I have 2gb
Do shards only respond to broadcast eval if they have a server on the shard?
Broadcasteval runs it on all process
Yeah, my issue is that when I broadcast eval "console.log(1)" I only get 1 response but no errors
Example:
https://pixel.is-inside.me/qHv9P3O8.png
Here are 2 shards, in the code that is evaled, client.code is "console.log(1)". For some reason, only shard 0 returns anything
Weird, console.log should return undefined
Oh wait, client.code prob isn’t set for the other shard
Not sure why you don’t just pass in the code directly into the eval
I put the code under client.code then passed in client
I couldn't work out how to directly pass it in because the function has the first argument as client for some reason
As in, if I do this: https://pixel.is-inside.me/ZQF5KtkT.png
Then "code" actually is client
You can provide a context in the second param of broadcastEval, then it’ll show up in the second param of the callback function
ShardingManager#broadcastEval()
Evaluates a script on all shards, or a given shard, in the context of the Clients.
Sorry, I forgot to mention I am on V13 but afaik, the only difference is that you must provide a function
The context option was only added bc of that change
So like this? https://pixel.is-inside.me/i6og7KQ8.png
Still need to pass it in via options.context
can you give me this command?
Sorry, my emojis are custom designed so id rather keep them private
Ur code doesn’t come with emojis tho
I guess you could download it with the id
I was guessing they wanted it because of how good the emojis looked
you can give me without emojis but ok
Sorry, did we come to a conclusion on the issue?
I also linked the docs earlier
Oh ty
Sorry, I still can't understand how I pass in the variables with this https://pixel.is-inside.me/Jrv8t1os.png
shards = await client.shard.broadcastEval(function() {}, {context: ????})
context: code
@covert patio
oh ty
@dense cape you know what the problem is
in v13 WebhookClient Class has been changed. It is now:
- new WebhookClient(WEBHOOKID, WEBHOOKTOKEN)
+ new WebhookClient({id: WEBHOOKID, token: WEBHOOKTOKEN})
thanks you
and I wanted to ask something else why it is impossible to do
message.guilds.roles.cache.array()
In version v13 there is no array
what can I do then @next plaza
use the destruction method
[...message.guild.roles.cache.values()]
or
new Array(message.guild.roles.cache.values())
2900
What mode of sharding is 'better' for performance, process or worker?
how to add shard?
• Necessary at 2,500 guilds (discord will not let your bot connect)
• Internal sharding (recommended):
const client = new Discord.Client({ shards: 'auto' }); // auto shards
const client = new Discord.Client({ shards: [0, 1] }); // specific shards
• Sharding manager: learn more
Worker_Threads:
- uses shared ram
- Good for CPU intensive Processes
- canva rendering doesnt work mostly
- sql databases have some problems
- uses a special cloning algorithm, getting Objects on the Broadcasteval is just possible, when you stringify the result.
Child_Processes:
- takes a little bit longer to start
- used as default
If my bot is close to needing shards (500 servers off), is it Ok to use a single shard bot until 2k servers? If so, what one would be best as It'll only be 1 shard
1 Shard until 2k Guilds is fine
Does it matter if I use worker threads then or should I just stick to the default as I don't really need shard communications
than you can use worker_threads
k, tysm!
@next plaza
could try with 4 Shards and check?
3, total shards in "auto"
Could you check if it responds in a different guild with the same shard?
It does not respond, shard 3 is completely dead, only the audit log system responds (sends embeds to an established channel of the server), which I do not know why it happens since in shards 1 and 2 everything works correctly
and messages? try console.log(message.content)
messages either
https://discordjs.guide/additional-info/changes-in-v13.html#shardclientutil-broadcasteval
since this moved to a function, how do I send a string argument in my function.
I wanna do something like that (command is the command name defined above)
You probably want to take a look at this: https://discordjs.guide/sharding/additional-information.html#eval-arguments
i'll give a try thank you
I'm unable to make it work
tried this and this
try passing that into the broadcastEval instead (as well as keeping it in the context)
broadcastEval((client, { commandName }) => ...
alr one sec
yay, seems to be working
it's the way I made it, sharing purpose
@steep otter and thanks, appreciate your help
👍
@next plaza
I already read this lol. Could you try on a different host? with a higer/lower Shard Count?
I have the bot in a vps, I could test in replit
Can it be my version of node?
v13 requires now node 16
node v16.4
discord v12
what's sharding
https://discordjs.guide/sharding/
It shows how to get started and what it is
hi, may anyone help me with this little problem? let d = "XXX"; client.shard.broadcastEval((client,d) => { //console.log(client); console.log(d); })
logs that d is undefined, how can i pass the variable inside broadcastEval?
Eval(…, { context: d })
thanx, will try
Hello, when I try to turn on my bot, I keep getting this error.
TypeError: Cannot create property 'shardCount' on string
Anyone able to help?
WebhookClient or Client?
Client
I think you passed in a string to your client constructor, that's why that's showing up; it's trying to append default properties to a non-object data type. ClientOption's are supposed to be objects. But to better diagnose it, can you show what your client looks like?
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES]});
Then it's not coming from there, might as well wait for someone else who knows
Here's the entire error if you need it.
given[key] = def[key];
^
TypeError: Cannot create property 'shardCount' on string 'jheNstV9rQPhYysHdPACCeL4HScZWpYe4rmjTPb4TvBK71Z_AvdFbEzHVE2rctDpApXu'```
bro...
Honestly. Whenever I see that error, it means it's from a WebhookClient. Also, censor the token. As I see it, the token doesn't look like it comes from a bot client, hence the assumption
Already regenerated when I posted that
Could you show the full error trace?
given[key] = def[key];
^
TypeError: Cannot create property 'shardCount' on string 'jheNstV9rQPhYysHdPACCeL4HScZWpYe4rmjTPb4TvBK71Z_AvdFbEzHVE2rctDpApXu'
at Function.mergeDefault (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\util\Util.js:336:20)
at new BaseClient (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\BaseClient.js:20:25)
at new WebhookClient (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\WebhookClient.js:30:5)
at module.exports (C:\Users\eazop\Documents\GitHub\RankerPro2.0\events\ready.js:15:15)
at Client.emit (node:events:394:28)
at WebSocketManager.triggerClientReady ```
at WebSocketManager.checkShardsReady (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\websocket\WebSocketManager.js:361:10) at WebSocketShard.<anonymous> (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\websocket\WebSocketManager.js:183:14)
at WebSocketShard.emit (node:events:394:28)
at WebSocketShard.checkReady (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\websocket\WebSocketShard.js:474:12)
at WebSocketShard.onPacket (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\websocket\WebSocketShard.js:446:16)
at WebSocketShard.onMessage (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:394:28)
at Receiver.receiverOnMessage (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\ws\lib\websocket.js:970:20)
at Receiver.emit (node:events:394:28)
at Receiver.dataMessage (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\ws\lib\receiver.js:517:14)
at Receiver.getData (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\ws\lib\receiver.js:435:17)
at Receiver.startLoop (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\ws\lib\receiver.js:143:22)
at Receiver._write (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\ws\lib\receiver.js:78:10)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)```
Now I see it
Your error states "new WebhookClient ..." at "...". That simply means you've declared a new WebhookClient somewhere in your code and it's causing that error, not the bot itself. See:
at Function.mergeDefault (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\util\Util.js:336:20)
at new BaseClient (C:\Users\eazop\Documents\GitHub\RankerPro2.0\node_modules\discord.js\src\client\BaseClient.js:20:25)
at new WebhookClient (C:
Look, at the latest line. If you're using discord.js v13, then the WC constructor only accepts 1 object parameter,
new WebhookClient({ id: 'id', token: 'token' });
And I'm assuming you use the old way of doing it, which is adding two arguments inside the function? Please fix it to use the above (or you can just put a URL argument inside the object)
yes I have found the problem, its in a old script that I no longer use.
Hey there, I'm moving onto version 13 because my bot grew enough to require sharding, and now I have a question:
Is there a good way to reference outside functions inside the function that is passed to broadcastEval? So, for example, let's say I have a getChannelById function and I pass it when I need to get a channel. That's fine. But then I also have a getMessageByIdAndChannelId which would first need to get the channel by id, and then get the message on that channel. Can I somehow call the getChannelById function inside the getMessageByIdAndChannelId so I don't just copy-paste the same code there?
Or, in another example, let's say I have a helper function that I want to be accessible to multiple functions passed to broadcastEval. What's the best way to do it?
how can i send something from the bot's process to the manager's process
You can use process.send
in the bot file, right?
Yes
okay
so in bot.js i put process.send and in the manager file i put process.on("message")
You can attach the functions to the client object so when you call broadcasteval you simply broadcastEval((client) => client.<function>(...args))
No you listen for the Shard#message event
oh
works now, thanks
I know, but how can I call another function from inside that attached function?
You just call it inside the function 🤨
No, because the context is different somehow. It throws a failed reference error.
let's say i have the manager file forked, how do i send the message received from the shard to the parent process? process.send doesn't work
Could you show the error
I am currently not at home, so later.
Okie
Wdym by forked
child_process.fork
So the sharding manager is not the main process right
nope
main process => sharding manager => bot
im trying to send the message received from the shard to the main process
Ok
This is heading to not djs related but on thr main process are you listening for messages from the worker
yeah
wait
That's all I get:
{"name":"ReferenceError"}
This is how I call broadcastEval:
this.client.shard.broadcastEval(_getMessageByIdAndChannelId, { context: { messageId, channelId } })
And it fails on this line:
const channel = await _getChannelById(clientOrShard, { id: channelId })
//...
}```