#archive-sharding
12465 messages · Page 6 of 13
I didn't use any sharding manager or else why I'm getting this then?
I guess I could send a message to the sharding manager with the arguments, the sharding manager could pass them to a function, and then return the results back in another message to the shard...
Uhhh im unsure about your problem
It's coming from the webhook
given[key] = def[key];
^
const hook = new Discord.WebhookClient({
id: 'xxx',
token: 'yyy',
});
WebhookClient (extends BaseClient) (implements Webhook)
The webhook client.
As in, you don't know the answer, or you don't understand the problem?
I dont have an answer
Ah, okay.
Thanks for trying to find one anyway. There probably is some way... At worst, I can just copy the code. Not pretty, but functional.
man i thank you from buttom of my heart
after i did it , my bot with sharding?
or i need more stuff?
Ye thats basically it
ok ty
Just being a bit slow today, with the way broadcastEval works now is there a way I can pass additional arguments to the function? i.e
let func = (client, string) => { console.log(string); }
client.shard.broadcastEval(func(something here?, "Hello, world!"));
Oh I actually see broadcastEval takes a second parameter
though this doesn't seem to be explained in the docs. How do I use the context option?
The second parameter has to be a JSON object. It should have a property called context, which is yet another JSON object, where you can pass all the arguments.
For example:
client.shard.broadcastEval(functionName, { context: { argument1: '1', argument2: '2' } })
And then in functionName you need to have two arguments: the first being the shard, and the second being the context object, so something like this:
//stuff goes here
})```
You can read more about it here: https://discordjs.guide/sharding/extended.html
it doesn't have to be a json object. just has to be json-serializable
hello there, is infinite promise here is correct behavior?
if I use string, eval works as expected
i'm on node 16.6.0 & typescript 4.2.2 & djs 13.0.1
anyone? 
Does it still happen if you use <Manager>.broadcastEval(…, { shard: shardId })?
with this it works fine
Prob just a bug with Shard.eval then
okay, thanks for your help
Hi, how does one restart a shard in v13? I used to do ts const shardid = args[1]; if (shardid === undefined) { await message.channel.send({ embeds: { color: colors.red, description: ':x: You must give a shard id!', }, }); return; } await message.channel .send(`Shard ${shardid} restarted!`) await client.shard?.send(`restart ${shardid}`); in v12 and in my manager code, I did: ```ts
shard.on('message', (message) => {
const regex = /restart (\d+)/im;
logger.log(Shard ${regex.exec(message)![1]} Restarting Regex Sent)
if (regex.test(message)) {
manager.shards.get(parseInt(regex.exec(message)![1], 10))?.respawn();
}
});
if your bot is over 1k servers, sharding is recommend but not required, when it gets to 2k+ sharding is a must
you could try upgrading your hardware or if sharding fixes the preformance issues
Hi, when I try to start my bot with sharding, I keep getting this error: https://cdn.discordapp.com/attachments/792786264751472680/873871991071981568/Screenshot_from_2021-08-08_13-15-03.png

My index.ts code: ```ts
const token = beta === true ? config.token.beta : config.token.prod;
const manager = new ShardingManager('dist/src/bot.js', { token });
manager.on('shardCreate', (shard) => {
logger.log(chalk.yellow.bold('[PizzaTown]') + Launched shard ${shard.id});
shard.on('death', () => {
logger.log(chalk.yellow.bold('[PizzaTown]') + Shard ${shard.id} killed. Restarting....);
});
manager.spawn();
lgtm
Then why is it giving the error...
what are all the possible manager.spawn errors?
Well, I reinstalled discord.js but I'm still getting the error: ```js
(node:31606) UnhandledPromiseRejectionWarning: TypeError: process.send is not a function
at Client.<anonymous> (/root/PizzaTownBeta/node_modules/discord.js/src/sharding/ShardClientUtil.js:37:17)
at Client.emit (events.js:376:20)
And it's not allowing me to start my bot, and after this error pops up, it shows: ```js
node:events:371
throw er; // Unhandled 'error' event
^
Error [ERR_IPC_CHANNEL_CLOSED]: Channel closed
at new NodeError (node:internal/errors:371:5)
at process.target.send (node:internal/child_process:724:16)
at Client.<anonymous> (/home/achakra/PizzaTown/node_modules/discord.js/src/sharding/ShardClientUtil.js:38:17)
at Client.emit (node:events:406:35)
at WebSocketManager.triggerClientReady (/home/achakra/PizzaTown/node_modules/discord.js/src/client/websocket/WebSocketManager.js:378:17)
at WebSocketManager.checkShardsReady (/home/achakra/PizzaTown/node_modules/discord.js/src/client/websocket/WebSocketManager.js:361:10)
at WebSocketShard.<anonymous> (/home/achakra/PizzaTown/node_modules/discord.js/src/client/websocket/WebSocketManager.js:183:14)
at WebSocketShard.emit (node:events:394:28)
at WebSocketShard.checkReady (/home/achakra/PizzaTown/node_modules/discord.js/src/client/websocket/WebSocketShard.js:474:12)
at WebSocketShard.onPacket (/home/achakra/PizzaTown/node_modules/discord.js/src/client/websocket/WebSocketShard.js:446:16)
at WebSocketShard.onMessage (/home/achakra/PizzaTown/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/achakra/PizzaTown/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (node:events:394:28)
at Receiver.receiverOnMessage (/home/achakra/PizzaTown/node_modules/ws/lib/websocket.js:970:20)
at Receiver.emit (node:events:394:28)
at Receiver.dataMessage (/home/achakra/PizzaTown/node_modules/ws/lib/receiver.js:517:14)
Emitted 'error' event on process instance at:
at node:internal/child_process:728:35
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ERR_IPC_CHANNEL_CLOSED'
}
client.shard.fetchClientValues(...).reduce is not a function
( client.shard.fetchClientValues("guilds.cache.size")).reduce((a,b)=> a + b)
the code worked fine on djs 12v
fetchClientValues returns a Promise, resolve it
oh alr thanks
How do you get shard id?
no 👍 !
please don't ping me for something like this, thanks.
That’s impressive how did u get it in that many
1k servers is a lot
How do I respawn all my shards?
client.shard.id
ShardingManager#respawn
Whether shards should automatically respawn upon exiting
wrong link:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=respawnAll
@covert patio
k, ty
discordjs.guide results:
• Sharding: How does sharding work?
• Sharding: Sharding file
• Sharding: ShardingManager#shardArgs and ShardingManager#execArgv
How do I see if a shard is online?
Sorry for coming back to this, is this in MB by chance? Thanks
Yes, bc we format it to mb by dividing it
k, tysm. I put % for some reason lmao
Does it have nodejs v16?
That's an error that occurs before you login
client#shard#respawn is not a function. How do I respawn correctly?
you have to broadcast it on the manager
at how many servers should i start sharding?
2500 required by discord
1500, after 2500 sharding is required by the discord gateway
No
It also depends on you bot needs if it uses alot of resources although having non active activity they can shard at 1.5k or earlier
Its more to be prepared for maybe a sudden increase in guild members
I thought I read somewhere that after 2,5k guilds discord will prevent you from connecting to the api if your bot isn’t sharded
Might be more though
Yh thats it
But also not everyone has the intent
but then we wouldn’t be in #archive-sharding now would we
Is there any way to forcibly disconnect a shard without a resume? I have the need to do a rolling restart when I push an update. When each shard of a new instance connects, the same shard of the old instance is killed immediately.
Im migrating blargbot from eris to djs due to eris updates slowing down lately, and this is the last major feature im missing as far as I can tell. In eris it was just
shard.disconnect({ reconnect: false });
shards.remove(shard);
Anyone having shard login issues or just me?
Yes, before 2k but recommended past 1k servers
Hey, i have a problem : (node:25) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetchClientValues' of undefined at callback (/home/container/commands/Info/shards.js:10:22)
const Discord = require("discord.js");
module.exports = {
commands: 'shards',
permissions: 'ADMINISTRATOR',
permissionError: "**Vous n'avez pas la permission !**",
callback: async (shards, config, message, args) => {
shards.shard.fetchClientValues("guilds.cache.size")
.then(res => {
let nbr_serveur = 0
let nbr_shard = 0
for(serveur in res) {
nbr_shard++
nbr_serveur += res[serveur]
}
const embed = new MessageEmbed()
.setAuthor(`Statistiques Shards`, member.user.displayAvatarURL({ dynamic: true }))
.addField('Serveurs :', `${nbr_serveur}`)
.addField('Shards :', `${nbr_shard}`)
.setColor('#00FFF0')
.setImage(member.user.avatarURL())
message.channel.send(embed)
})
}
} ```
Who can help me ?
there is shard.destroy function, but It automatically respawns the shard. So no, there isnt a way.
could you console.log(shard)
I believe that is also a private or undocumented method, will be a pain to do in typescript. Ill try to figure a way to bodge it then 🙂 Thanks!
lol
Have you tried the <Shard>.kill() method?
Thats not documented in the typescript definitions as far as I can see, so no. Ill see if I can add a shim for it
Ah, #kill() is on the shard structure, im working with the WebSocketShard structure as im using my own sharding management system. Blargbot clusters multiple shards onto 1 process rather than a separate process per shard to share caches
what you could do, is overwrite the ratelimit property, so it never respawns
Kill WebsocketShard
Hi, i have a little problem with shards.
Using fetchClientValues, when i calculate all servers, the count depends on the number of shards, for some reason..
When i start the bot with 6 shards, my bot its in 40 servers.
When i start it with 1 they're 35 and when i start it with 20 they become 36?
Any idea on this?
it displays the servers in the console
you need to compile it
🤦♂️
How to get channel by id and send embed to the channel by broadcastEval in djs v13?
Im got this error so but i'm using var for defind embed
Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready.
at Shard.onDeath (/home/ubuntu/bot/node_modules/discord.js/src/sharding/Shard.js:158:16)
at Object.onceWrapper (node:events:514:26)
at Shard.emit (node:events:394:28)
at Shard._handleExit (/home/ubuntu/bot/node_modules/discord.js/src/sharding/Shard.js:384:10)
at ChildProcess.emit (node:events:394:28)
at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12) {
[Symbol(code)]: 'SHARDING_READY_DIED'
}
im getting this error
discordjs.guide results:
• Sharding: When to shard
• Sharding: Sending messages across shards
• Sharding: How does sharding work?
@old cave
discordjs.guide results:
• Popular Topics: Setting up Canvas
• Miscellaneous: Implementation
• OAuth2: A quick example - Implicit grant flow
guys that sharding is built-in discord or discordjs?
yes its built in in discord.js
still same erro
is it possible to spread shards into multiple cluster(instance)?
?shardreadytimeout
🥺
help ME
Call Me NASA already tried to help, they sent this: #archive-sharding message
That would fix the error
tried this
i think i got the problem
thanks for not helping me
Else, your shard is hitting an error before the ready event runs. Try debugging the code best on a non-sharded bot
Anyways, my issue: What is the best way to have a stats command on a sharded bot? I have everything set up, but is it worth caching the results from broadcast eval so it doesn't happen too often?
is it possible to use variables declared outside broadcastEval inside the method?
for example
let targetShard = 0;
client.shard.broadcastEval(client => {
if (client.shard.ids[0] === targetShard) .....
})
Just do broadcastEval(() => {…}, {shard: shardId})
alr thanks!
could i also ask what does the repeated events in client.shardResume refer to?
than how can I do that?
You need to set the same shardamount on each cluster
then assign different ids to each cluster
So for example on cluster 1 you assign shards [0,1,2,3] cluster 2 you assign [4,5,6,7] etc.
But features like broadcasteval only work on the cluster it’s casted on, so not the other clusters
im not sure what you are trying to say here
Oh you probably mean unofficial, not unsupported
I will try that,thks
Hello! This is bug?
I have an error Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
but i set the spawnTimeout is -1:
manager.spawn({amount: 20, delay: 5500, spawnTimeout: -1});```
Hello, I am using discord.js sharding manager and am recently having shards duplicate. E.g. if you type a command then it repeats. This has randomly started happening and I haven't changed any code. Any ideas?
manager.on('shardCreate', shard => console.log(Launched shard ${shard.id}));
manager.spawn();
I am using pm2 to run my main process using pm2 start index.js
Then there are likely more instances of the sharder
you need start the file with sharding manager, not main
yeah, my index.js is the shard manager
Is there a way to disable the SHARDING_IN_PROCESS error? (using broadcasteval while shards are still spawning?)
I was told this would be removed in v13 but it seems like it wasn't. Every time I update d.js I have to manually comment out the line causing this and it's kind of infuriating
Why do you need to broadcastEval while shards are spawning?
I just have a lot of shards and I don't want a lot of functionality to be lost while waiting for them to spawn
Mainly for things like the web dashboard, etc
The fact that it can be fixed by commenting a single line just makes me feel like one of the devs thought "sure it works perfectly but i don't want people to do this". Such an unnecessary limitation tbh
I’d host the dashboard stuff from the manager
So you can await Manager.spawn before binding the webserver to the port
@tame iris
Again I understand that it's better to wait for all the shards but in reality I'd rather just be able to have the shard be fully functional from the moment it becomes ready. It's a bit irritating when I start up the bot and am immediately spammed with constant sharding errors
Are you using shard id to send to a specific shard in broadcastEval?
Or do you absolutely need all online shards to respond?
why i cannot spawn shard with ts file?
its manager's spawnTimeout, not Shard one
Bc node can’t run ts files
You should be transpiling ur code to js
spawnTimeout is renamed to timeout, in d.js v12 it's worked 
sorry for stupid questions, i read the changelog yesterday and found answer :d
oh
@vestal chasm well Ive been using -1 too and I had shards timeouts error
but nothing causing issues tho, the shard was getting ready after that
other shards is not starting after error
ah
I don't remember what I did to avoid that
How can I force all shards (or specific shards) to respawn from within a shard, such as having shard 1 communicate to shard 2 to respawn
?
Shard 1’s process exited before it’s client became ready
When do i need to use broadcastEval?
For example if i want to clone a channel from a specific guild, do i need to do that with client.shard.broadcastEval
<@&839912195994812420>, edit: the scam got deleted
@vestal chasm maybe try Infinity?
infinity also doens't work
Broadcasteval are mostly used for checking or getting the cache on a specific shard
Do you have an example of use case?
I used process.exit on broadcastEval with a shardid check
client.shard.broadcastEval(`client.channels.cache.get('${channelID}')`)
i get this error while spawning shards
Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
i already set the delay to 10 sec but i still get this error
And do i need to use that if i want to send a message to a channel?
i found out that it is because i use setInterval() in shard process, if i remove setInterval() in bot file, it works fine, if i use it, i get the error
I would recommend shard 1 to communicate with sharding manager to tell it to reboot shard 2
I keep getting ```
/Root/COOL-BOI-BOT/node_modules/discord. J's/src/util/Util. J's: 336
Given [key] = def [key];
^
TypeError: Cannot create property 'shardCount' on a string 'Q7oY7kdvoHJKpwwGYtYmP7frNrrMKp9sXeBsVEAEoVLtWRnAWcgg0FTd1soxZBCi-vr1'
At Function. mergeDefault (/root/COOL-BOI-BOT/node_modules/discord.js/src/util/Util.js:336:20)
At new BaseClient (/root/COOL-BOI-BOT/node_modules/discord. j's/src/client/BaseClient. j's: 20:25)
At new WebhookClient (/root/COOL-BOI-BOT/node_modules/discord. j's/src/client/WebhookClient. j's: 26:5)
At Object.<anonymous> (/Root/COOL-BOI-BOT/index. j'shttps://cdn.discordapp.com/emojis/817012751054274581.png?size=3214)
At Module. _compile (node: internal/modules/cjs/loader: 1101:14)
At Object. Module. _extensions.. j's (node: internal/modules/cjs/loader: 1153:10)
At Module. Load (node: internal/modules/cjs/loader: 981:32)
At Function. Module. _load (node: internal/modules/cjs/loader: 822:12)
At Function. ExecuteUserEntryPoint [as renaming] (node: internal/modules/run_main: 79:12)
At node: internal/main/run_main_module: 17:47
It’s a issue with the options you passed into new WebhookClient
Not sure which line bc ur error looks weird
Thx for responding.
can I ask why .jss are . J's?
Anyone know how to fix shards loading too slowly?
The way I found to fix this is increase the timeout or set it to -1 to yield them indefinitely until they're loaded (probably not the best solution though)

does sharding effect the way the events fire or commands work?
no
then is there a down side of sharding?
Hey, How can i make internal sharding in djs v13? Same as v12? My bot it 2000 guild
it remained the same, any errors you are getting?
I have seen the document already it just run on 1 process so i need to edit my code back to normal i think i just wanna try hybrid-sharding
How can I check if all shards are launched before making a fetchClientValues in my ready event ?
Ping me
Is sharding hard to do ?
Here
Hey, i have this problem when i execute my shards stats command, in console when i launch the bot i see : Shard on : 0
So it's good, but the command shards doesn't work 😦
Code?
const Discord = require("discord.js");
const { MessageEmbed } = require('discord.js')
module.exports = class ShardsCommand extends Command {
constructor(client) {
super(client, {
name: 'shards',
memberName: 'shards',
group: 'music',
guildOnly: true,
description:
"Shards"
});
}
async run(message, args, onsenfou, client) {
if(message.author.id !== '870370835066654753') return;
client.shard.fetchClientValues("guilds.cache.size")
.then(res => {
let nbr_serveur = 0
let nbr_shard = 0
for(serveur in res) {
nbr_shard++
nbr_serveur += res[serveur]
}
const embed = new MessageEmbed()
.setAuthor(`Sanction`, client.user.displayAvatarURL({ dynamic: true }))
.setTitle(`Statistiques Shards`)
.addField('Serveurs :', `${nbr_serveur}`)
.addField('Shards :', `${nbr_shard}`)
.setColor('#00FFF0')
.setImage(client.user.avatarURL())
message.channel.send(embed)
})
}
}```
"client" is null
in my handler i const client in args 4
and here i put client on args 4
Can I see?
my handler ?
This part
Oh no i'm a noob 😭
It's not the same bot so i don't put client on args 4 in my music bot i just have this
commandPrefix: prefix,
owner: discord_owner_id
});
client.registry
.registerDefaultTypes()
.registerGroups([
['music', ':notes: Commandes Musiques :'],
])
.registerCommandsIn(path.join(__dirname, 'commands'));```
But I confess that I have no idea how to solve my problem
I do not see the arguments anywhere
Yes I thought there was the same handler on this bot but in fact not at all
So does it work now?
No same error
Can you send your code in a bin?
stats shards code ?
what is sharding
The handler, command handler or the file that fires the command
I am not familiar with Commando, maybe someone else can help.
That's okay, thanks anyway!
A specific shards heartbeat can be found on the WebSocketShard instance, accessible at <client>.ws.shards > .ping.
Can anyone show me an example of this?
<client>.ws.shards is a Collection so you need to get the shard from it to get the property ping
nobody know how to solve my problem?
Is there a way to get the amount of errors of a specific shard? With client.shards.broadcastEval()?
I have this code:
const { ShardingManager } = require("discord.js")
import { token } from "./environment_variables/variables.json"
import * as functions from "./functions"
const manager = new ShardingManager("./bot.js", {token : token})
manager.on("shardCreate", async shard => {
await functions.processShardCreate(shard)
})
manager.spawn()```
Error:
```This session would have handled too many guilds - Sharding is required.
whats this files name?
just make sure you run the right file okay
hmm try to force spawn the exact amount of shard? instead of auto
My bot is in 3,800 guilds, how many should I do?
4?
yea 3-4
Ok
Same thing
no idea then
Could the token somehow be the wrong one?
Let me console.log it and check
it should be the different error...
and its alr login the first shard so it cant be
Thats very weird
It creates a shard, yet thinks I'm not sharding?
Anyone else have any clue?
Too many guilds
[WS => Manager] Fetched Gateway Information
URL: wss://gateway.discord.gg
Recommended Shards: 4
[WS => Manager] Session Limit Information
Total: 1000
Remaining: 200
[WS => Manager] Spawning shards: 3
[WS => Shard 3] [CONNECT]
Gateway : wss://gateway.discord.gg/
Version : 9
Encoding : json
Compression: none
[WS => Shard 3] Setting a HELLO timeout for 20s.
[WS => Shard 3] [CONNECTED] Took 204ms
[WS => Shard 3] Clearing the HELLO timeout.
[WS => Shard 3] Setting a heartbeat interval for 41250ms.
[WS => Shard 3] [IDENTIFY] Shard 3/4 with intents: 515
[WS => Shard 2] An open connection was found, attempting an immediate identify.
[WS => Shard 2] [IDENTIFY] Shard 2/4 with intents: 515
[WS => Shard 3] [READY] Session 10764c132218cada0845a77a5653e4ab.
[WS => Shard 3] [ReadyHeartbeat] Sending a heartbeat.
[WS => Shard 2] [INVALID SESSION] Resumable: false.
[WS => Shard 2] Failed to connect to the gateway, requeueing...
[WS => Manager] Shard Queue Size: 1; continuing in 5 seconds...
[WS => Shard 3] Heartbeat acknowledged, latency of 2567ms.
[WS => Shard 0] Shard did not receive any more guild packets in 15 seconds.
Unavailable guild count: 1
Logged in!
Hit a 429 while executing a request.
Global : false
Method : put
Path : /applications/657776310491545620/commands
Route : /applications/:id/commands
Limit : 2
Timeout : 17772ms
Sublimit: None
[WS => Shard 2] An open connection was found, attempting an immediate identify.
[WS => Shard 2] [IDENTIFY] Shard 2/4 with intents: 515
The bot goes online, but its in a loop of the bot disconnecting and reconnecting with shard errors?
You hit the rate limit for setting global commands
Also doesn’t seem like you enabled the guilds intent
Trust me, they are on
Hard to believe that when the logs says it’s not receiving guild create/unavailable events
You mean Guild members, right?
No
The GUILDS intent
Oh
That’s better
Thats how it was lol
Shard 0 has an unavailable guild
I guess there’s more that are available that that if there’s 4 shards
You're saying it should be 5?
No
Ok
I’m not sure why Discord is sending invalid sessions upon first connect tho
Maybe Discord hates my bot
So yeah it just goes on and on until I stop node
Also, I'm using the library's set method to add the commands, so I don't know why its rate limiting
Are you calling it on ready?
Yes
That’s prob why
Oh, ready is being called multiple times?
Per shard
You only need to do it when you actually update a slash command
The guide has a script that does this and it doesn’t require the bot to login
I want to actually get the bot working before I mess with slash commands though
I don’t think ur the only one having issues with reconnections bc of invalid session tho
Not sure if it’s a Discord issue or d.js
Hmm is there any "workaround"?
Not rn
Can you link me to the issue? (If its on GitHub or something)
I don’t see any issues for it on GitHub
You’ll prob be asked to provide a short reproducible code sample
I'll just go back to shards : auto until its fixed
(node:866) UnhandledPromiseRejectionWarning: Error [SHARDING_READY_DIED]: Shard 1's process exited before its Client became ready.
I am Getting this error once i run my sharding code
Welcome to the club
?shard ready timeout
Nvm
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 many ram is suggested for 10 shard which has 1000 guilds for each?
2-4gb
Is it possible to make a "shard" that I use
quick.db ?
can we respawn shards individually using internal sharding?
I see no respawn function on websocketshard
You have to destroy the shards with client.ws.shards.get(shardid).destroy()
ah, it doesn't show as a method on the docs
All event codes with 4xxx mostly doesnt emit a respawn of the WS Shards. Destroying with 1000 should recreate the ws shard again.
nvm its just a private one
Enable private methods
ok thankies
Documentation suggestion from @winged egret:
ShardingManager#totalShards
Amount of shards that all sharding managers spawn in total
please i want to know what's sharding do
• 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
@terse cairn here you go^
is anyway to setup a redundancy client for discord.js??
What conditions require me to create a new shard?
Could More Than 70% CPU Usage Be The Reason I Did That? Or Recommended When The Bot Has 1000 Servers Each Shard?, I'm Confused Now
definitely cpu, bc sharding spreads the load on available cores
Oh, Ok, Thank You
Suddenly I can't get my shards to boot. Didn't change anything and now it doesn't work anymore
rip dbot then 😄
I've once again returned for help with sharding.
[WS => Manager] Fetched Gateway Information
URL: wss://gateway.discord.gg
Recommended Shards: 4
[WS => Manager] Session Limit Information
Total: 1000
Remaining: 990
[WS => Manager] Spawning shards: 3
[WS => Shard 3] [CONNECT]
Gateway : wss://gateway.discord.gg/
Version : 9
Encoding : json
Compression: none
[WS => Shard 3] Setting a HELLO timeout for 20s.
[WS => Shard 3] [CONNECTED] Took 225ms
[WS => Shard 3] Clearing the HELLO timeout.
[WS => Shard 3] Setting a heartbeat interval for 41250ms.
[WS => Shard 3] [IDENTIFY] Shard 3/4 with intents: 515
[WS => Shard 2] An open connection was found, attempting an immediate identify.
[WS => Shard 2] [IDENTIFY] Shard 2/4 with intents: 515
[WS => Shard 3] [READY] Session 3f25ba1c382ed2b1563de799229f9f9f.
[WS => Shard 3] [ReadyHeartbeat] Sending a heartbeat.
[WS => Shard 2] [INVALID SESSION] Resumable: false.
[WS => Shard 2] Failed to connect to the gateway, requeueing...
[WS => Manager] Shard Queue Size: 1; continuing in 5 seconds...
[WS => Shard 3] Heartbeat acknowledged, latency of 2334ms.
The session keeps getting invalidated and the bot reconnects over and over again
Also this:
Unavailable guild count: 1
Any help would be appreciated, please
@coarse lagoon what intents do you have
export const client = new Discord.Client({intents : ["GUILD_MEMBERS", "GUILDS", "GUILD_MESSAGES"]})
Hey i have a problem with my shard stats command
https://cdn.discordapp.com/attachments/877663820804395008/877684190722801664/Screenshot_53.png
code : https://pastebin.com/qjQQG8VR
It’s client.shard.ids[0]
And .cache.size
@hasty ledge
So what should I do then ?
Change the eval code accordingly
Now when i execute cmd i have this error in console : ```
(node:14255) UnhandledPromiseRejectionWarning: ReferenceError: empty is not defined
at AboutCommand.onError (/home/akamusic/node_modules/discord.js-commando/src/commands/base.js:361:47)
That’s an issue with commando
Or maybe you in ur about command?
yes
Tried to use empty, but it isn’t declared nor defined
same error
Idk what you changed
Basically in all my orders I use empty after commando
When I check my commands there is no argument that could be related to "empty".
Everything works except my status command
does discord.js take in account of the sharding max concurrency?
There is a property for max concurrency on the ws manager. But I dont use big bot sharding, so idk if it uses the Discord given limit.
ah gotcha, i was asking because i've implemented this in my discord.js clustering library, making sure there's no conflicts
Btw, I would suggest to add the discord.js licensce to the repo, bc the Code is literally the same, you renamed Shard to Cluster and added the Shardlist on workerdata/proccess.env
workerdata?
my library doesn't use worker threads
it only uses cluster/child_process
*Check Util.mergeDefault on ClusterMananger
Doesn't change the fact, that you have to add the License
there's no workerdata there
Regarding my problem, when I run the bot on my main computer, the problem is still there. I guess there is something wrong with my code?
Event Code: 1000
Clean : true
Reason :
[WS => Shard 3] Clearing the heartbeat interval.
[WS => Shard 3] WS State: CLOSED
[WS => Shard 3] [CONNECT]
Gateway : wss://gateway.discord.gg/
Version : 9
Encoding : json
Compression: none
[WS => Shard 3] Setting a HELLO timeout for 20s.
[WS => Shard 3] [CONNECTED] Took 195ms
[WS => Shard 3] Clearing the HELLO timeout.
[WS => Shard 3] Setting a heartbeat interval for 41250ms.
[WS => Shard 3] [IDENTIFY] Shard 3/4 with intents: 515
[WS => Shard 3] [READY] Session 15a7152286a1cf86ef225925dc7b29ca.
[WS => Shard 3] [ReadyHeartbeat] Sending a heartbeat.
Or an internet problem?
https://media.discordapp.net/attachments/730840356450730056/877813450049458187/unknown.png
This Error follows to a hard Crash, I thought it got fixed. I am using the latest discord.js version.
- you seem to be using discord.js-light, a mod and outdated library of discord.js, use the actual one. 2. What's your code? 3. Basing on the error, I don't think thats a WebhookClient. It's a Client, I assume, and since the -light library modifies the internal structures, then I assume it doesn't know what "data.url" is
The latest discord.js-light doesnt modify the internal structure, since cacheControl comes from Discord.js side.
Its a Client
And this error appeared earlier too, several had this issue.
It still modifies structures https://github.com/timotejroiko/discord.js-light/blob/master/extensions.js
there we go ^
I dont want to argue and unterstand fully that there is no support. But the latest version of discord.js-light doesnt modify the WS part. As I said other djs users had this same problem. Lemme refer to the issue.
I am know running the latest djs version. To see if the error appears there too. I will report tomorrow.
It does modify how packets are handled tho https://github.com/timotejroiko/discord.js-light/blob/d037519e93dfaad8aad212e546a8811b01a07b41/client.js#L45
Ur error actually reminds me of an old issue pre v13 used to have tho
#5590 in discordjs/discord.js by Pliexe closed <t:1625334288:R>
Cannot read property 'url' of null. discord.js/src/client/websocket/WebSocketShard.js:268
The latest v13 no longer references connection.url in that method tho
i get this when using the example from the guide where you replace index with bot and require it
Is there any benefits to sharding a small bot?
is there a way to know what crashed a shard?
is there a benefit in using worker threads
Node supports two types of Process Splitting.
Both have in comparisons some differences:
Worker_Threads:
- uses shared ram
- Good for CPU intensive Processes
- canva rendering doesnt work mostly
- faster ipc
- sql databases have some problems
- uses a special cloning algorithm, getting Objects on the Broadcasteval is just possible, when you stringify the result.
Process:
- takes a little bit longer to start
- uses a little more process ram
- used as default
the reason, why it crashed?
you can listen on shard.on('death', console.log)
so mongodb database will work fine on worker thread?
yes, works fine for me
alr
what does Shard#error emit? client errors or like api errors?
hello, I am getting an error "Shard's client took too long to become ready", even though the spawnTimeout is -1 here. Any ideas how I fix this? I am currently unable to spawn all my shards because of this
The spawn Timeout should be added on the spawnfunction
You don't want to pass it in the ShardingManager class, you want to pass it in where you spawn them:
https://discord.js.org/#/docs/main/stable/class/ShardingManager?scrollTo=spawn
manager.spawn(this.totalShards, 5500, -1).catch(e => console.log(e));
@next plaza@lost saddle so something like this?
Look at the link I sent and Click on the options
It is an Object, look:
https://discord.js.org/#/docs/main/stable/typedef/MultipleShardSpawnOptions
oh, so it's an object. my bad
I hope this helps you out!
thank you very much!
When using v12 yes, when using v13 check the link
oh yeah I am still using v12, so that should be fine?
Yes, manager.totalShards
what does Shard#error event emit?
Node v16.7 introduced Pointer Compression from the v8 engine.
We could hope on 30% less heap ram usage on 64bits system.
Someone???!!!
People who asked after got their answers and im still waiting from 17 hours
Nvm ill find a fix for it
stackoverflow and other sites exists 😑
The message is deleted, so I cant help
i did
Shard's Client Took Too Long To Become Ready
same code from discordjs.guide
how can i restart specific shard / all shards in shardingManager?
Documentation suggestion for @echo fulcrum:
Shard#respawn()
Kills and restarts the shard's process/worker.
I'm randomly receiving a 1000 close code on websocket which makes the bot shard just die silently without emitting any errors or trying to reconnect to the gateway.
Did anyone else experience this issue and is there a way to handle it?
I think it's an issue on Discord's side because it probably missed a heartbeat after having a sudden API latency spike on some of their servers. (The latency was logged and my other shards on the same machine didn't face any issues so it's not my internet connection)
My question is how do I resume without having to restart the shard process?
It actually should recreate the ws shard automatically
You could listen to the shardDisconnect event
Nope it doesn't, the process remains running but the bot is fully disconnected from Discord.
It didn't catch anything, but WebSocketShard.close did, (code: 1000)
But the problem is not listening to the disconnect event, it's how do I reconnect and resume the session?
I have a unsupported solution, its a private method, so I wont suggest it.
Are you on the latest pkg version?
Yes I'm on the latest djs version if that's what u mean.
But I think I found where my real issue is, I tried to simulate a missed heartbeat and it reconnected automatically after being closed. But any active voice connection on my Lavalink node gets terminated after few seconds because the gateway session associated with it was closed..
ok
Every shards as an attached even listener on the shard. shard.on('message', ...) and process.on('message'` for your bot.js file
When you use Childprocesss, yes
On WorkerThreads, you have to listen on the parentPort
when i use Sharding Manager, the bot very slow and won't respond to messages. But when I use Internal Sharding, the bot working fine. Any problem?
Did the Shards started?
yes
all of it started but unstable and will restart itself about 5-10 mins later
but the response time slow too 
How to send a message to another shard
I'm sorry. I have a question.
I want to use require('express'); with new ShardingManager().
No matter how many times I searched on Google, I could not find the answer.
There are many examples of using Discord.Client(), but I couldn't find any example using new ShardingManager().
Can you give me some advice?
Does sharing support import/export syntax?
Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready.
You could try this link.
https://maah.gitbooks.io/discord-bots/content/sharding.html
Or just try to look through the discord.js documentation:
How would I avoid this error Error [SHARDING_IN_PROCESS]: Shards are still being spawned. when I use client.shard.fetchClientValues when a client is ready?
how can I know when internal sharding spawning complete
u use sharding Manager right ?
Sorry for the late response, yes.
i'm using like this
manager.spawn().then(... ur code here)
the spawn() function will resolve when all shard spawning done 
Ok, much appreciated.
how to use shards?
hey guys any help
idk 🤷♀️ everything is right
see a first error say response mean
Shard 0's Client took too long to become ready.
There are some weird things occurred to me while I'm trying to shard my bot today. When I terminate my process with ^C in the console and everything looks stop, it can still receive and response the command, even log things in console. This usually follow with error ERR_IPC_CHANNEL_CLOSED and I didn't find out what's that.
I quit the terminal but it's still there. Everything become fine after I restart my computer.
My code is the same with the guide.
const { ShardingManager } = require('discord.js');
const { bot: {token} } = require('./config.json');
const manager = new ShardingManager('./app.js', { token: token });
manager.on('shardCreate', shard => console.log(`Shard ${shard.id} is start working...`));
manager.spawn();
So basically I'm confused how can I kill all shards properly.
how much RAM (very rough estimate) should each spawned shard use? I feel like my bot is using more RAM than it should be.
hi does anyone has clues of this
Look throgh the shards collection on the manager and call Shard#kill on each
ShardingManager#shards
A collection of shards that this manager has spawned
Shard#kill()
Immediately kills the shard's process/worker and does not restart it.
So basically I can just teminate the main process in the console but need some command things to kill them?
Or I have to listen to some event
You can listen to the Process#SIGINT event which is emittrd b4 the process is fully exited
Okay I'll try. Thx a lot!
Np
How can I sharding across hosts? Any ideas/advices/guides? I can self-taught but I need a starting point
https://discord.js.org/#/docs/main/stable/typedef/ShardingManagerOptions
totalShards is the TOTAL amount of shards from ALL hosts
shardList accepts an array of numbers (the shards that it will be responsible for)
found this post on reddit last year that might help you out a bit
https://www.reddit.com/r/Discord_Bots/comments/ism4r7/sharding_across_multiple_hosts_discordjs/g6k9ch8?utm_source=share&utm_medium=web2x&context=3
Thanks
can someone help me with sharding , im getting confused as there are 2 types of sharding in there , my bot is in 2.2 servers
Hi, I'm someone who's in shard to know
Hello, I currently run a VPS to host my Discord.js bot. I've noticed that due to the nature of JS, not all CPU cores are used when I'm sharding on a single process. If I were to use Clusters to shard my bot, will this effectively make use of all my virtual cores?
Hey! Pls, can someone help me, i'm trying to restart my bot but says Shard 0's Client took too long to become ready., i'm waiting for 6hours and nothing
I have 66 shards
mee to
How would I go with my database with sharding?
Should I make a separate process using a database in the backend and queue-ing each request it recieves from each shard?
Execute order 66...
what do you mean with that
66 shards... Execute order 66... Star wars?
well
Yep, that's probably the best way I can think of
well, rip my time lmao
Like, i can do it in a day - i just lack motivation often
Good luck I guess
sql allows 32,767 connections at once, no?
other databases are more/less but the majority do more than one
could either make a private api to communicate with it or just have them all connected lol
Well, I use SQLite
which is a file...
sqlite is good for non-sharded bots, you'd be best migrating to a proper database if you're needing sharding
well, anything as performant as SQLite?
sqlite is lightweight but with large amounts of data it's very inefficient
any database will work just as well
Hmm
you hosting on a vps or using one of the panels that sell you database access?
Vps of course
how much data are you storing, just guild configs, etc? also whats your guild/shard count
guild count is 600 ish
i use 6 different SQLite files to keep filesize low, each for each category - economy, guildconfigs, prefixes, specific cooldowns etc
😳
you don't need to shard until like 2000 servers but i'd start moving things over now whilst it's still small
i'll dm you, since this isn't the place for this talk anyways
sure
How can I check if a specific shard is online?
@fickle mural any chance you know?
@tough idol are you able to help me out on this as you gave me this first, it doesn't actually say Shard X is offline when it is?
deprecated since v13, use (await client.shard.broadcastEval('true', { shard: 0 }).catch(err => false)) ? 'Online' : 'Offline'
I'm still currently using v12 until i get the chance to move to v13, Shard 14 (the shard which is offline), the ping shows null = nothing but it says it's online, that's what i'm trying to explain
oh sorry, true should be a string, edited
Still saying it's online when it is not
works for me
Promises are always truthy
?
broadcastEval returns a Promise
Since Promises are objects, it’ll always return true
I see.
oh yeah, you gotta await the promise
didn't catch that, thanks kinect
I already await it
The second param of broadcastEval is an object, not a number
doing {shard: 14} doesn't respond at all, bare in mind i'm still using v12 currently
Oh, then it is a number
Non-empty strings are truthy btw
So returning the error message will always be true
Remove .catch(...)?
No, it’ll become an unhandled rejection
Make the catch return a falsy value
still returns it's online
@dense cape
Do you have 15 shards?
I have 20
when i restart bot with ctrl c and yarn start
the old shards are still on even if i dont start
how do i turn off bot properly
Listen for the Process#SIGINT event and loop throgh the shards collection on the manager and call Shard#kill on each
like this?
like this?
edit : manager.shards
Yes
yea worked
ty
Why ?
I have to stop the bot for 45 minutes to avoid the error and this is a minimum of 5 times a day.
do you have setTimeout: -1 or setTimeout: 0
@covert vortex
the emojis from my server if they are in shard 0 will they work in shard 1
where ? I don't think so
in your shardingmanager
i dont have this
An example of this would be:js const manager = new ShardingManager('./index.js', { totalShards: 'auto', spawnTimeout: -1, token: yourtoken})
okay
hello guys i hope you doing well i have question what Sharding do?
discordjs.guide results:
• Sharding: How does sharding work?
• Sharding: Sharding file
@strange echo
@valid gale
the user has been banned
no idea why the message is still there
(delete it?)
That'd be helpful ^
@pearl cove I don't suppose you know anything about shard broadcasteval?
What about broadcast eval exactly?
I've been trying to get it to show the status of a shard, but when Shard X is offline it automatically returns 'true'
@pearl cove ^
can anyone explain to me what is sharding
Read #archive-sharding message or checkout https://discordjs.guide/sharding/ i guess
Hi! I've been trying to make a shard restart command for my bot. How can I make the bot wait until the shard is actually dead before restarting? Here's the code: ```ts
shard.on('message', async (message) => {
const regex = /restart_shard:(\d+)/
if (regex.test(message)) {
const shardid = regex.exec(message)![1];
if (manager.shards.get(Number(shardid)) === undefined) {
logger.log(chalk.yellow.bold('[PizzaTown]') + ` Message ignored as Shard ${shardid} does not exist....`);
return;
}
logger.log(chalk.yellow.bold('[PizzaTown]') + ` Shard ${shardid} will be restarting soon....`);
manager.shards.get(Number(shardid))?.kill();
logger.log(chalk.yellow.bold('[PizzaTown]') + ` Shard ${shardid} has been killed....`)
return;
}
})
shard.on('death', () => {
logger.log(chalk.yellow.bold('[PizzaTown]') + Shard ${shard.id} killed. Restarting....);
shard.respawn();
});
kill the shard then respawn from sharding manager or something like that?
Does each shard need to register slash commands or do I need to move them into the main file?
commands are per app so registering them should be unrelated to sharding
Does anyone know what could be causing this? The stack trace isn't really helpful so it could be anywhere. I'm guessing something related to sharding bc ShardClientUtil but I have no idea besides that
(this is the full stack trace. the code being thrown is from https://github.com/discordjs/discord.js/blob/main/src/sharding/ShardClientUtil.js#L184)
Interesting. Completely random question: are you instantiating the never mind, it's not this (duh) (XWebhookClient class anywhere in your code? This probably isn't the issue, but I remember a very similar error
Is it possibly a bug with d.js? If so I’ll create an issue for it.
I don't know the relevant code or reproducible code for this nor am I familiar that much with sharding, so I'm not a good person to ask for this >:
👍 I’ll wait to see if anyone else might know more then, ty
So after further investigation I think it might be due to a shard going down. I did a rolling restart (restart each shard one at a time) and it happened at some point during that. Not positive about that, just a theory
How to fix this?
Issue is with another library, not d.js
thats a discord.js error
the discord.js error is caused by the other library's error crashing the process and therefore the shard failed to start
My bot is in 2258 servers. Should I start the sharding process?
yes
K. Thx
When I do my bot's stats command the console output showed like this.
[2260, 2260]
And the bot started to run on 2 instances. Like when I do a command it sends 2 messages instead on 1.
Sharding code
const { ShardingManager } = require('discord.js');
const config = require('./botconfig/config.json')
const manager = new ShardingManager('./bot.js', { token: config.token });
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn()
.then(shards => {
shards.forEach(shard => {
shard.on('message', message => {
console.log(`Shard[${shard.id}] : ${message._eval} : ${message._result}`);
});
});
}).catch(console.error);
When y try to eval this code, it says channelId is not defined
why ?
The channelId must be inside the broadcast eval function because of how js scoping works

but i can use the args ? ex: channelId = args[0] in the broadcast
yep they should work
All your function variables need to be inside the broadcast eval afaik
ahh ok i see, ty
so i can't use externals functions in boadcast like that ?
I'm unsure of that probably wait for an expert sharder to come 😁
If you pass in the function as a parameter, it'll work I guess
when we shard the bot, when we print client.users.cache in a channel, will that contain the users in that shard only?
Yes, the one, which are cached
^^^^^^
const config = require('./config.json')
const manager = new ShardingManager('./index.js', { token: config.settings.token, totalShards: 5});
manager.on("shardCreate", (_) => { 0 })
manager.spawn().catch((_) => 0)```
`Error [SHARDING_REQUIRED]: This session would have handled too many guilds - Sharding is required.`
Anyone able to help with this?
How to stop that the bot disconnects if a heartbeatping fails ( I want to raise the limit to like 5)
That's server-side, you can't control it.
But my bots crashes due to it every 1 -5 minutes
that over 8 differejnt os, tested on windows, windows xp, rasperian, debian, ubuntu, fudora, etc.
i made a issue request if u want to see my images: https://github.com/discordjs/discord.js/issues/6552
Do you have this in a seperate file instead of your main bot file?
how to fix this
Ram: 1gb/24gb
CPU: 5%/100% (8 CORES)
50gb SSD
DEBIAN 9
Download: 800mb/s
Upload: 400mb/s
https://cdn.discordapp.com/attachments/824411059443204127/881610918612570212/unknown.png
So should I just go ahead and make an issue for this? Doesn't seem like anyone knows and I'm suspecting that it's a bug
@dense cape?
Then the process is up
It doesn’t check if the ws is actually connected
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.
Hello, I have added sharding to my bot and literally nothing works now
I am trying to make a simple eval command but I don't get the message logged in console
here are my intents, what am I doing wrong? please help
const { ShardingManager } = require("discord.js");
const manager = new ShardingManager('./bot.js', {token: config.token});
const Discord = require("discord.js");
const client = new Discord.Client({
intents: Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES
})
manager.on('shardCreate', shard => {
shard.on("death", () => {
const channel = client.channels.cache.get("channel-id")
channel.send({content: `The shard: ${shard.id} death`})
})
})
I have a question I would like to send a message to a channel if the shard death what can I do there I tried client.channels.cache.get () but that doesn't work :/
the error?
channel.send({content: `The shard: ${shard.id} ready`})
^
TypeError: Cannot read property 'send' of undefined
the channel id is invalid
no its right
before send, console.log(channel)
undefined why
so the channel id is undefined
But I entered the channel id correctly
verify its a text channel
is :D
try: js manager.on('shardCreate', shard => { shard.on("death", async () => { const channel = await client.channels.cache.get("channel-id") channel.send({content: `The shard: ${shard.id} death`}) }) })
nop
same error?
yes
bruh, you cant access the client on the manager
@last creek your sharding code is wrong
You need 2 files
You could use a webhook for it
2 files ?
Shard.js -> ShardingManager
Bot.js -> Sharded Client
• 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
Check the last link
what is better
shareding manager or internal sharding
Apart from ShardingManager, discord.js also supports a sharding mode known as Internal sharding. Internal sharding creates multiple websocket connections from the same process, and does not require major code changes. To enable it, simply pass shards: 'auto' as ClientOptions to the Client constructor. However, internal sharding is not ideal for bigger bots due to high memory usage of the single main process and will not be further discussed in this guide.
I have,
But I would like to send a message with the shard.id to a channel do I do that in the Bot.js?
ah so if i use sharding manager, i can save resources
Not necessarily
no, you will even use more. But this will help you to balance the load over cpu cores
Oh hmm
Well i am using a custom worker which does that for me
So i dont need the sharding Manager at all
you are talking about worker_threads?
No
you could combine Internal Sharding and the Sharding Manager with your custom solution
Yes i am using internal sharding
Is it normal that if an error occurs in the bot that automatically restarts the bot?
let values = await client.shard.broadcastEval(`
[this.shard.ids[0],
this.guilds.cache.size
this.uptime,
this.ws.ping]`);
It's give me this error:
reject(new TypeError('SHARDING_INVALID_EVAL_BROADCAST'));
^
TypeError: SHARDING_INVALID_EVAL_BROADCAST
Anyone?
which line i mean

In your code what you send
which line of what
the error is create
It doesn’t say. All the info I know is there
And my update a bit further down
oh okay i look
Have you tried a try catch?
Hello, I have added sharding to my bot and literally nothing works now
I am trying to make a simple eval command but I don't get the message logged in console
here are my intents, what am I doing wrong? please help
In v13, you have to broadcast a function
Oh okay thanks
how can i ignore unavaible guilds
just ignore them?
no, the bot doesnt start because of this problem
and it says no websocket avaible
just check <guild>.available before doing anything with them
allright i will try thx
Hey, how can I get a shard's ping? client.ws.shards.ping is undefined.
how can i put number in broadcastEval function ?
// this one v12 still works
// defined laysodep function above
const guildCount = await getGuildCount(manager);
const membersCount = await getMembersCount(manager);
console.log(`${guildCount} guilds and ${membersCount} members!`);
console.log(`Set presence: ${guildCount} guilds and ${membersCount} members!`);
manager.broadcastEval(client => client.user.setPresence({ status: "online", activities: [{ name: `${laysodep(guildCount)} servers | ${laysodep(membersCount)} members` }] }));
in v13 it will said laysodep is undef error (already defined above)
Sorry, just saw this.
I have no idea where the error could be coming from or even what method could be causing it. I don't even know if it is a method, maybe it's caused by some internal task?
Any code that deals with broadcastEval or fetchClientValues throughout all of my code has catching, both with the block (try { ... } catch (e) { ... }) and with promises (.catch((e) => ...)) for good measure.
Unfortunately I have no idea either :/
Possibly a bug then? Seems like nobody knows what could cause it.
I would guess yes
Can the bot shut down the sharding manager? E.G. if I want to completely shut down a test version of my bot
I tried to process.exit() but that only kills the shard
You probably triggered it from the shard, not the manager
Yeah I know, it's responding to an admin command
I want to bubble it up to the manager from the shard
Yeah so it's firing on the shard
Yeah that's my problem
how can I get list of shards in internal sharding
edit: client.ws.shards
At about what server count is it recommended that I start working on the code to shard my bot?
2500
I thought that was when you literally have to shard. I want to know when a good time is to start sharding my bot.
Or can you not shard your bot if your server count is below 2500, I'm not really sure 
typically its 1000 guilds per shard
Ah, I see
you can totally shard before 2000 guilds if you want
I mean, my bot is at 380 servers right now but I'm just looking into the future since it's growing crazily fast.
gonna be real, im a d.py refugee.. our bot has 11 shards each with 1000.. weve been using autosharding since about 2500-3000 guilds
so im not totally sure if d.js shard recommendations are the same, but i assume they are 
Alrighty, I'll look into it some more. But thank you 
👍
you can always implement autosharding and have it grow with your server use for future proofing

Hmm, alright
bump
Alr so my bot is in 2466 servers and should I shard it now or should I wait for the bot to hit 2500 servers?
Because I tried to shard the bot at 2225 servers and it caused a lot of problems like server count for each shard showed as [2225, 2225]
There's def smth wrong if the count is equal on both shards
idk what's wrong. I've done everything correctly
const { ShardingManager } = require('discord.js');
const config = require('./botconfig/config.json')
const manager = new ShardingManager('./bot.js', {
token: config.token
});
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn()
Can you show the eval?
const {
MessageEmbed,
splitMessage
} = require(`discord.js`);
const config = require(`../../botconfig/config.json`);
const ee = require(`../../botconfig/embed.json`);
const emoji = require(`../../botconfig/emojis.json`);
const {
inspect
} = require(`util`);
module.exports = {
name: `eval`,
category: `Owner`,
aliases: [`evaluate`],
description: `eval Command`,
usage: `eval <CODE>`,
run: async (client, message, args, guildData, player, prefix) => {
if (!config.ownerIDS.includes(message.author.id)) {
const nope = new MessageEmbed()
.setColor(ee.wrongcolor)
.setDescription(`${emoji.msg.ERROR} You are not allowed to run this command! Only the Owner is allowed to run this command`)
return message.channel.send({embeds: [nope]})
}
if (!args[0]) {
let idk = new MessageEmbed()
.setColor(ee.wrongcolor)
.setDescription(`${emoji.msg.ERROR} You have to at least include one evaluation arguments`);
return message.channel.send({embeds: [idk]})
}
let evaled;
try {
if (args.join(` `).includes(`token`)) return message.reply("Abbe sale!");
evaled = await eval(args.join(` `));
let string = inspect(evaled);
if (string.includes(client.token)) return message.reply("Abbe sale!");
} catch (e) {
console.log(String(e.stack).bgRed)
const emesdf = new MessageEmbed()
.setColor(ee.wrongcolor)
.setAuthor(`An Error Occurred`)
.setDescription(`\`\`\`${e.message}\`\`\``);
return message.channel.send({embeds: [emesdf]});
}
},
};
And also when I shard my bot it ran on 2 instances
I mean the broadcast eval
Huh?
Like it was responding twice to stuff?
yes
Do I have to add broadcast eval?
It only runs on 2 instances when I shard
How did you get [2225, 2225]?
I used this client.shard.fetchClientValues('guilds.cache.size').then(console.log);
Ur on v12?
Or does v13 still do string for that method?
I still didn't updated to v13, I'm now using a beta version before v13
Why not use the latest?
I have to update a lot of stuff. Do you think this issue will go away if I update the version?
Which commit are you on?
^13.0.0-dev.e37ef3af2151e556527ccd8e98ec531bdcc0ed70
Oh, that commit is like 2 months old
yes
So updating the version will fix this issue?
I would say so
alr, I'll try
Thx 🙂
Yea, the ShardingManager got a cleanup and improvements done since then
Mind the breaking changes like ...ID to ...Id
Is it possible to get the child_process's stderr and stdout? They're shown as null when I output the child_process of the shard.
Bot is replying twice after sharding in some servers
same bro
I am getting an error SHARDING_INVALID_EVAL_BROADCAST how can I fix this
Apoglises for the late reply, on the ping (via ws) I get null so it must mean the process is dead?
It's reconnecting but it's not getting disconnected??
I got this error when sharding.
Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready.
I sharded my bot using internal sharding and it's working fine. But I don't want to keep internal sharding system. I get above error every time I start my bot
Sometimes discord asks to reconnect
iv fixed this for us :p
You can check client.ws.status
WebSocketManager#status
The current status of this WebSocketManager
I see. And doing it for each shard...how?
client.shard.fetchClientValues('ws.ping')```
i do js eval client.shard.fetchClientValues('ws.ping')
I'm not after the ping, it's the status of each shard i'm after, where it's online or not.
ah
.fetchClientValues(ws.status)
You can determine the status of the shard by the number
So it could be similar to broadcastEval with .broadcastEval(true, 8)
I’m pretty sure fetchClientValues also allows you to pass in a specific shard id
Could there be an example? I'm quite unsure.
Documentation suggestion for @abstract elm from @dense cape:
ShardClientUtil#fetchClientValues()
Fetches a client property value of each shard, or a given shard.
Same params as broadcastEval
So, here's a little issue.
Here's the following code:
client.shard.fetchClientValues(ws.status, 9)
With that, i get ws is not defined, defining it with client i get the error:
https://api.lockbot.dev/content/chrome_x7fKakVpAQ.png
The eval should be in string
"ws.status"
Oh.
Perfect thank you! Then converting the numbers [0-8] to string would be?
Documentation suggestion for @abstract elm:
Number.parseInt()
The Number.parseInt() method parses a string argument and returns an integer of the specified radix or base.
Status should be in the Constants object
Well, you can just create an array as the inverse mapping based on those values
@dense cape Got it to work, although when i killed a shard i got the error Error [SHARDING_NO_CHILD_EXISTS]: Shard 1 has no active process or worker., anyway of showing the embed or..?
Handle the rejection
Are there docs to it?
For error handling?
Mhm. It just automatically screams that error out.
Control flow and error handling
JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. This chapter provides an overview of these statements.
I'm guessing a return won't do it?
I don’t see how that’s relevant to error handling
I'm not quite sure if i'm explaining this properly. For if a shard is online/idle/reconnecting/offline etc to show that on the shard instead of it automatically throwing that error
throwing that error
That’s why you have to handle it
a try and catch?
Yes
Then you can do whatever you want with the error
How'd that work in my circumstance? With sending the embed even if a error throws up?
Catch the error first
You can send a message or edit the embed or smth in the catch
But a way of sending the embed which show's which shard is having issues instead of doing it a separate way? https://api.lockbot.dev/content/Discord_IKhbhXRuEd.png
Did you await the fetchClientValues?
I did.
Show code
If ur doing it like that, then you have to .catch it then return whatever the "dead" index is
I would just refactor that into a variable
So my ShardDisconnect is like still working right?
Is sharding needed for application based on slash commands?
Sharding doesn’t affect bots that only use slash commands bc it doesn’t have to be in the guild
alr thanks
can i put my client and the sharding manager in the same file?
No
ok
The manager would be creating more managers in that case
How much code do I need to change if I set shards: 'auto'?
None, also it's totalShards: 'auto'
Oh that is for v13, i see.
mhmm, I'm using v13.
Does d.js handle auto reconnections if shards go offline or do I have to listen for this event and attempt reconnection myself? For v12
some shards seem to be off on my bot rn so not sure
What is Sharding?
Guide suggestion for @terse cairn:
discordjs.guide results:
• Sharding: How does sharding work?
• Sharding: Sharding file
It should, yes.
Quick question - how would you pass a configuration file to a shard managed client?
I could create a singleton configuration client outside of the client that the client can import, but I'm trying to get away from that if possible. There's doesn't seem to be a straight forward way to pass a JS object to a client that's instantiated?
Mine go down sporadically as well - check your RAM usage
Documentation suggestion for @unborn cairn:
Shard#eval()
Evaluates a script or function on the shard, in the context of the Client.
Woah! Thanks for that!
Assuming there isn't an example lying around?
the arg is just a function with the client as a parameter
I'm not sure I follow - will I need to do this for each shard that is spawned?
I remember there is broadcastEval() function
that’s for between shards
ShardingManager#broadcastEval()
Evaluates a script on all shards, or a given shard, in the context of the Clients.
Yeah - I wouldn't need broadcastEval() here
Oh wait 🤔
broadcasteval is just eval but it does it on all shards
🙄
yep broadcasteval is better here mb
In the event that a shard goes down and a new one spawns though... it would need to be broadcasted again to that new shard right?
Guess I could track the "onShardSpawn" event (or whatever it is)
yeah. so you could listen to the spawn event in which case you could just use regular eval each time that fires
Right
I’m guessing there’s a reason you can’t just fetch the config directly?
I'm trying to refrain from using a singleton configuration object 👍
In the past, that's what I've done. I defined an object that read from environment variables and could be imported from any class. I didn't like this model, so I'm reading in a configuration file and passing in the relevant values to the client.
when i have sharding, will client.guilds.cache.get works?
No, it will gives the guilds of the current shard
I have code to do a rolling restart on my bot (runs <Shard>.respawn() for each shard one at a time). The past few times that I've used it, some shards somehow spawned more than 1 process. Does anyone know if there's a way to prevent this? Is it a bug?
async function rollingRestart(): Promise<void> {
const shards = manager.shards;
for (let [i, shard] of shards) {
try {
const respawned = await restartShard(shard);
} catch (e) { }
}
return;
}
async function restartShard(shard: Shard): Promise<void> {
return new Promise(async (resolve, reject) => {
try {
const newShard = await shard.respawn().catch(() => {
reject();
return null;
});
if (!newShard) return reject();
return resolve();
} catch (e) {
return reject();
}
});
}
It's also very difficult to fix the situation if someone reports it because broadcasteval will only run once so I can't easily find the process IDs to close them.
For TypeScript discord sharding, what do you all use as the client path?
I'm assuming you don't reference bot.ts or client.ts ... right?
i dont use sharding but i assume it would be your compiled main file, which would probably be dist/client.js or dist/bot.js
What kam said is correct ^
My compiled app.js and bot.js are in build/ and I use "./build/bot.js" for my path
That's what I thought as well - but I'm additionally packing everything up into a CLI command that can't find the directory / file. But, I guess that's not discordjs's issue
pretty sure it's just relative to where you run the command from but yeah not really d.js
Still need help w this
Anyone know a straight forward way to allow for a user to provide their own configuration file then load that config into the clients from the sharding perspective? Still struggling with that.
Most / all implementations I've seen all reference a source of truth which they can load at run time. At runtime, my config is still "undefined" until the configuration is specified by the user. The client technically needs this information before the shard is spawned; however, I'm not seeing a way to get this to work?
I created a Singleton configuration object that I load before the manager.spawn() method, but the import of it into client.js technically is evaluated at runtime (before the config is specified by the user). So, it evaluated to undefined.
The manager only provides one event: on('shardCreate') which is only emitted once the shard is created. I need to inject the config before that point. Any ideas? Is this even possible?
hey, how can i get guild data when i use shards?
i think, i need to get member of specific guild, in specific shard. iam obtaining guild data, but how should i get specific member from that data?
because guild data is an vanilla object
const req = await client.shard.broadcastEval(`this.guilds.cache.get("${ctx.guildID}")`);
const guild = new Guild(client, req.find(res => !!res));
``` throws https://i.imgur.com/rpqE8Ub.png
broadcastEval takes a function now
broadcastEval(client => ...)
huh, letme try
ShardClientUtil#broadcastEval()
Evaluates a script or function on all shards, or a given shard, in the context of the Clients.
but i will receive Guild structure or plain Guild object @pearl cove
because with this i get plain object
You can test it
I don't shard myself, so I can't
huh, now kind a weird error https://i.imgur.com/V354frO.png
and guildid is not defined
@pearl cove
Give me a minute
ok
Okay yes hello
You need to give it context
broadcastEval((client, guildId) => {
...
}, { context: guildId });
I think that will work
ok let me try
now im not getting any debug message in console https://i.imgur.com/E7UD7aL.png
return it
return client.guilds...
oh, xD i think thats good idea im going to try
still
Still what?
@mortal badge
I don't know, sorry
Never used sharding
okk np thx for try
damn, thats so weird. if i dont provide context, im getting error, when i provide context, im not getting response
@pearl cove i find issue, there is problem with this context
can anybody help me?
i need sharding and specified shards to be auto but it doesnt work
and if i manually raise it it doesnt even start up
please somebody
@edgy edge sorry for ping but can you help me 
#rules rule 6
oops i overread the mention
i thought only dms 
but please i really need help from somebody
getting this error related sharding
client.shard is undefined
why am i getting such an error
how can i pass a variable from index.js to each bot.js?
without knowing anything about how your project works, i'd say just use a database?
well, i want to pass exactly the database connection, so i don't have to create a connection in each shard
Is it possible to shard at 90 servers? And would it be good or bad?
the bot doesn't log in because of some crash
it is possible, but i cannot say if it's good or bad
i think there wouldn't be any benifit
welp, i got pretty confused here.
have never really played with broadcastEval before
let hmm = await client.shard.broadcastEval(`
[
this.shard.id,
this.guilds.cache.size
]
`)
Still need help with this
Duplicate shards spawned
djs V13?
yes, it is
broadcasteval was changed in v13, it takes a function with a client parameter instead of a string
i need value of sharding like
server
user
Ping
uptime
this server shard / total shard
any examples for that?
Documentation suggestion for @toxic island:
ShardClientUtil#broadcastEval()
Evaluates a script or function on all shards, or a given shard, in the context of the Clients.
Example is shown in docs ^
thanks
.
Documentation suggestion from @near nymph:
ShardingManager#totalShards
Amount of shards that all sharding managers spawn in total
#Duplicate shards spawned can someone help please
how can i set how many servers per shard 
Hello when spawning shards with ShardManager i cannot use process.send
i only found this but there are no replies to this dood
how would i get the shard id of a guild?
Guild#shard
The Shard this Guild belongs to.
Guild#shardId
The id of the shard this Guild belongs to.
Either of em work
thanks
what is djs shard
how it works i don't understand
https://discordjs.guide/sharding/ Learn more about sharding here
oh thank you.
manager.on('shardDisconnect', shard => console.log(`\nShard ID: ${shard.id} Disconnected`));
Can I use this event to find out if a shard get disconnected?
Is there a way to load values when using broadcastEval ?
that isn't a valid event on the docs
as in, pass variables via the context?
Yeah
First part is a function, second is the options, including the context.
The first variable of your function is the client, as noted in the example/code behind
the second is the assignment of the context variables
broadcastEval(script, options = {}) {
...
script = `(${script})(this, ${JSON.stringify(options.context)})`;
simple example to get a server from any shard:
client.shard.broadcastEval((c, { guildId }) => {
return c.guilds.cache.get(guildId)
}, { context: { guildId: your_input_here } })
first part is your function, second is the options + context.
Whenever enabling sharding, I get the error Unknown interaction when executing slash commands yet the slash commands run fine. My client crashes right after
#883788925540376578 still need help with this please
My bot needs to use sharding. I am limited by memory, not performance. I'm assuming I should use autosharding - is there a reason to manually implement sharding besides performance?
Also, are there any tricks for lowering memory usage besides using LimitedCollections for cache managers?
Hey sorry to ask for smth prolly stupid but i'm trying to do a broadcastEval
this.client.shard.broadcastEval('[this.client.guilds.cache.size, this.client.channels.cache.size]') //I used it in v11 yeah i missed a lot in v12 and v13 changes
But i get an SHARDING_INVALID_EVAL_BROADCAST any idea ?
v13 takes a function to eval
Wdym
Have you any example to just get the guilds number ? 🤔
The v13 update guide includes this change
Eval((client, {id}) => client.guilds.cache.get(id)?.memberCount, { context: { id: "…" } })
I'll see
Keep in mind you can’t use variables outside of the function, you’ll have to pass it in via the context
Thanks
Yeah .then(x...
Ik i had i used it v11 just i missed a lot 😂
.cache.get
@fallen sleet 👀 https://i.imgur.com/uch6b1e.png
I too have v11 relapses when I’m not using intelli-sense
yeah i thought i was wrong somehow 
The cache thing is the easier to remember thing
Np bro you're awesome :)
how can I restart a specific shard?
Hello, why do all the shards restart every 15 minutes ?
are they websocket shards? Maybe you have a bad Connection
no, and the connection is good
i upgraded my bot to v13 and now it does this, before it did not
does anyone know how to shard a bot? I tried so many times and it just doesn't work
Pass it in the client constructor
const client = new Discord.Client({
intents: ['GUILDS', 'GUILD_MEMBERS', 'GUILD_BANS', 'GUILD_MESSAGES', 'DIRECT_MESSAGES'],
partials: ['CHANNEL'],
allowedMentions: {
parse: ['users', 'roles'],
repliedUser: true
},
shards: 'auto'
});
if I set shards to auto it will add shards automatically?
yeah, that's internal sharding
but it's not ideal for bigger bots
do I have to reboot the bot?
reboot the bot for what
10 guilds don't worry xD
for adding shards
nope as it's automated
the same with using a sharding manager file, it'll do it automatically
ok and what is the better way when the bot is on a lot of guilds?
the better way is to use a sharding manager for bigger guilds:
Apart from ShardingManager, discord.js also supports a sharding mode known as Internal sharding. Internal sharding creates multiple websocket connections from the same process, and does not require major code changes. To enable it, simply pass "shards: 'auto'" as ClientOptions to the Client constructor. However, internal sharding is not ideal for bigger bots due to high memory usage of the single main process and will not be further discussed in this guide.
ok thanks, going to check the guide about that
np
is there a way to reboot some shards or we can just reboot all shards?
i'm getting Error [ERR_IPC_CHANNEL_CLOSED]: Channel closed for no reason
i was like coding my bot on beta bot with like 3 servers and it was working fine and then moved to bot with 5k servers and now i'm getting tons of different errors
Error [ERR_IPC_CHANNEL_CLOSED]: Channel closed
Emitted 'error' event on process instance at:
Error [TypeError]: Cannot read property 'id' of null
Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
and worst thing is that it doesn't tell where error actually is 😭
so I got a ready.js file for my ready event. When my bot starts with 2 shards I ofc got 2 ready.js events with 2 shards. How could I check the shard that is using which ready.js process?
#883788925540376578 still need help
Give the full error stack pls
i fixed it, apparently i was using client before it even started
whats sharding
Alright so, I'm using broadcastEval but I cannot access the iconURL method inside it
Code:
await client.shard.broadcastEval(async (client, {
guild,
logChannel
}) => {
const {
MessageEmbed
} = require('discord.js');
const channel = client.channels.cache.get(logChannel);
if (channel) {
channel.send({
embeds: [
new MessageEmbed()
.setTitle('ADDED TO GUILD!')
.setDescription(`**Guild Info**`)
.addFields({
name: `Name`,
value: `${guild.name}`
}, {
name: `ID`,
value: `${guild.id}`
}, {
name: `Members`,
value: guild.memberCount.toLocaleString()
})
.setFooter(`Currently in ${client.guilds.cache.size.toLocaleString()} guilds`)
.setTimestamp()
.setThumbnail(guild.iconURL({
dynamic: true
}))
.setColor('#81FF89')
]
});
}
}, {
context: {
guild,
logChannel
}
});
Error:
Unhandled promise rejection:
Error [TypeError]: guild.iconURL is not a function
Does anyone know why?
You can’t pass full structures into broadcastEval
Well, it will be jsonified, then parsed
I would just create the embed outside of the eval
Oh alright, will give it a try! Thank you :)
is there anything wrong with
const config = require('./config.json');
const Discord = require('discord.js');
const Statcord = require("statcord.js");
const manager = new Discord.ShardingManager('./index.js', {
token: config.token,
totalShards: 1
});
manager.spawn();
manager.on('shardCreate', shard => console.log(`launching shard #${shard.id + 1}`));
hey
i get this error
[shards] shard 1 loaded!
Error [SHARDING_NO_CHILD_EXISTS]: Shard 1 has no active process or worker.
at Shard.fetchClientValue (/root/legacyNewBot/node_modules/discord.js/src/sharding/Shard.js:240:62)
at ShardingManager._performOnShards (/root/legacyNewBot/node_modules/discord.js/src/sharding/ShardingManager.js:286:68)
at ShardingManager.fetchClientValues (/root/legacyNewBot/node_modules/discord.js/src/sharding/ShardingManager.js:264:17)
at ShardingManager.<anonymous> (/root/legacyNewBot/sharding.js:15:13)
at ShardingManager.emit (node:events:394:28)
at ShardingManager.createShard (/root/legacyNewBot/node_modules/discord.js/src/sharding/ShardingManager.js:164:10)
at ShardingManager.spawn (/root/legacyNewBot/node_modules/discord.js/src/sharding/ShardingManager.js:215:26) {
[Symbol(code)]: 'SHARDING_NO_CHILD_EXISTS'
}
and this is my shard.js
const { ShardingManager } = require('discord.js');
const config = require("./config.json");
const legacyShard = new ShardingManager('./index.js', {
totalShards: 2,
token: "token kek"
});
legacyShard.spawn();
legacyShard.on('shardCreate', shard => {
console.log(`[shards] shard ${shard.id} loaded!`);
legacyShard.fetchClientValues('guilds.cache.size')
.then(results => console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`))
.catch(console.error);
});
Any debug/error logs?
that happened when i added
legacyShard.fetchClientValues('guilds.cache.size')
.then(results => console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`))
.catch(console.error);
yes
C:\Users\weirdpc\Desktop\MuffinBot-v13> node .
C:\Users\weirdpc\Desktop\MuffinBot-v13\node_modules\discord.js\src\util\Util.js:336
given[key] = def[key];
^
TypeError: Cannot create property 'shardCount' on string 'TOKEN'
at Function.mergeDefault (C:\Users\weirdpc\Desktop\MuffinBot-v13\node_modules\discord.js\src\util\Util.js:336:20)
at new BaseClient (C:\Users\weirdpc\Desktop\MuffinBot-v13\node_modules\discord.js\src\client\BaseClient.js:20:25)
at new WebhookClient (C:\Users\weirdpc\Desktop\MuffinBot-v13\node_modules\discord.js\src\client\WebhookClient.js:26:5)
at Object.<anonymous> (C:\Users\weirdpc\Desktop\MuffinBot-v13\utils\logger.js:6:23)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
PS C:\Users\weirdpc\Desktop\MuffinBot-v13> ```
Show utils/logger.js line 6
It’s a WebhookClient issue, the params have changed iirc
const webhookClient = new Discord.WebhookClient(config.webhook_id, config.webhook_url);```
Yea, it takes an object now
oh
You only need the id + token or the url
{ id, token, url }
yeah
const webhookClient = new Discord.WebhookClient({config.webhook_id, config.webhook_url});``` is fine right
url is token in config.json
No
url is token
You need to specify the object keys
im confused
{ myToken } is not the same as { token }
const myToken = "12345"
const token = myToken
const objA = { token }
const objB = { myToken }
const objC = { token: myToken }
objA.token // "12345"
objB.token // undefined
objC.token// "12345"```
Is it possible to shard at 90 servers, and would it be recommended?
I say recommended as in, will it break my bot or not?
yes it is possible, no it's not recommended and the answer is maybe
it depends on your code
looks like i didnt do a great job on updating everything
How to fix ?
I'm trying to get the total membercount through this piece of code
const memberValues = [];
await client.shard.broadcastEval((client, {
memberValues
}) => {
memberValues.push(client.guilds.cache.reduce((prev, guild) => prev + guild.memberCount, 0));
}, {
context: {
memberValues
}
});
console.log(memberValues.reduce((prev, curr) => prev + curr, 0));
It outputs 0 every time
any idea to why?
what is sharding?
Can’t have side-effects in the function
Well, it won’t work bc the reference via context and outer scope is lost
It’s better to just return the number in the eval and resolve the data from the eval
Splitting ur bot into separate processes to distribute load
Got it, thanks!
lots of users getting the same error, you can see this old tag: <#djs-help-v14 message>
Any idea to list ALL the guilds in all Shards ? With the broadcastEval, i tried smth but it was sending first the guilds of the Shard 0 then Shard 1 (using 2 messages)
Solved
I don't know what happened but my bot just received everything at once and processed it for shard 0 at once and now I cant login due to 429.
I understand the 429 part but the receiving everything at once is a mystery
would making separate js files to do certain things be sharding?
no
No, it's basically a bot that serves X amount of server per shard
Maybe bc of Dms. Discord.js should handle ratelimits
In the end, I couldn't figure it out xd. Wasn't the VPS's internet as other shards responded fine but it seems fine now
oh so it's like having a bot on multiple guilds?
It could be a global ratelimit. Since ratelimits dont sync across Shards or when it is a shared VPS
Does anyone have information on the ideal infrastructure for scaling your bot with sharding? I’m trying to understand if I can have the bot running on several different physical servers or if I have to get one beefy server and just utilize sharding to split up the processes, or a combination of both. Just looking for more concrete info.
Basically yes
It relays on your Bot Structure. When you do not need a ipc then you can vertical scale your Bot => More Machines => Less downtime.
When you want to use the same Machine, then use horizantal scaling. The upgrades depends on your Bot growth and a other advantage is that the maintaince a lot more easier is.
Hey, i have my sharding file like this., although it does not want to spawn more shards.
const { ShardingManager } = require('discord.js');
const config = require("./botconfig/config.json");
const manager = new ShardingManager('./bot.js', { token: config.token, totalShards: 'auto', respawn: true });
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn();```
how would this be if i for example want to manually shard? with lets say 5 shards?
totalShards: 5, no?
o hm lemme try