#archive-sharding

12465 messages · Page 5 of 13

strange echo

may have to bEval the code to get the channel and send but not sure

next plaza

How can I restart a websocket shard?
I destroyed it

proud mortarBOT
terse cairn

600 shards hypelol

next plaza
vivid bough

How to Add Shards?

astral rampart
vivid bough
vivid bough
primal heron

Replace "1" with 1 ?!

terse cairn

Yup

last creek
versed temple

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?

strange echo

?softban @eternal cedar spamming question across multiple channels

icy crowBOT

Successfully softbanned Kartik#1234

fiery dagger

How would you display your bot's whole server count in it's status?

strange echo

~~use client.guilds.cache.size~~mb didn't realize this was sharding

terse cairn

whats the max amount of shards I could use?

surreal tulip

i don't think there is any limit

terse cairn

hmms

lament plover

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 :))

lament plover

anyone?

winged bobcat

Iirc v13 takea a function

lament plover

yeah i know thats what i did in second code block, i already got the fix in #djs-help-v14

winged bobcat

Ah k

next plaza
terse cairn whats the max amount of shards I could use?

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

versed temple

This is not working and I'm using sharding

And it happends to me also with guildmemberAdd or some other ones

terse cairn

?shitty-buttons

icy crowBOT

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)

static pulsar

Ping me if you know

fair cairn

know what

urban lintel

how do i restart bot on sharding? previously without sharding. I just do process.exit(1) but how i do 'restart bot' with sharding?

next plaza
urban lintel
next plaza
urban lintel
steep otter

Would be nice if you posted the solution

versed temple

Is there any way to restart a specific shard?

urban lintel
tawny lantern

anyone have a guide on sharding?

raw river

?sharding

icy crowBOT
tawny lantern
sudden sequoia

what ever is ur main bot file is put there (or path to id)

dusty gate

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?

near nymph

?sharding

icy crowBOT
loud walrus

Hey, how can I spawn 2 shards ?

winged bobcat
loud walrus

I'm using the sharding manager

dense cape

Put in totalShards: 2 in the ShardManager options

Or you can specify a list of ids in shardList

loud walrus

I tried, but the but the event that signals when a shard is launched no longer works (nothing is sent to the console)

dense cape

Can you show the code you used?

loud walrus
terse cairn

?shitty-buttons

icy crowBOT

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)

winged bobcat

What...

winged bobcat
loud walrus

Iirc u need to listen to the evnt before calling the <manager>.spawn function

loud walrus

Okay thx

terse cairn
sudden sequoia

that will not work for him, assuming he dont use broadcast eval and just place it, as bot will only be the current shard

stiff fulcrum
pallid depot
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

lusty smelt

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?

lusty smelt
pallid depot

if you have a code that executes in the ready event it can stop the shard from becoming ready

winged bobcat

The code doesnt stop the shard from becoming ready as it gets emitted the same time as the client ready event

winged bobcat
lost saddle

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

next plaza
lost saddle
fiery dagger

to find a guild, would you use this.guild.cache.get('')?

proud mortarBOT
dense cape
languid yoke
lost saddle

After some testing, it worked. Thanks!

languid yoke
solemn pewter

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)
})
winged bobcat
loud walrus

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 :

loud walrus

AG_question

winged bobcat
  1. The property res is undefined

  2. Res is undefined because you cannot perform an eval untill all shards have been spawned

loud walrus

Yes, but how can I change that ?

winged bobcat

Change what

loud walrus

To make it work

winged bobcat

Well you can add a check to see of res is undefined

loud walrus

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.

winged bobcat

You would need to have your express server run in your file with the shard manager

loud walrus

And I need to get my client to start the express server

winged bobcat

Why

loud walrus

I need to get some informations about the bot on some pages

winged bobcat

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

loud walrus

how can I broadcasteval without the client ? 🤔

winged bobcat

?docs ShardingManager#broadcastEval

icy crowBOT
solemn pewter

Any docs to use emoji with v13 ?

wild moat
blazing crescent

When's a good point to start clustering?

I'm already sharding

terse cairn

do I need multiple machines for sharding?

terse cairn

How do i respawn all shards

client.shard.respawnAll()

this seems to not work

winged bobcat
winged bobcat
terse cairn
winged bobcat

Okay

terse cairn
winged bobcat

uh no, but a simple way is by passing the shardList option to what shards you want spawned on x machine

next plaza
solemn pewter
next plaza
solemn pewter

ok

solemn pewter
lusty smelt
[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

dense cape

You have multiple things listening to the same port

dusty gate

hey, how do i get total amount of shards? and all sharding statistics?

real spire

How do I do sharding

icy crowBOT
next plaza

@real spire Agree here

thorn tinsel

api problem ?

winged bobcat

No

?shardreadytimeout

icy crowBOT

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.

dense cape

Could also be caused by not calling client.login

lusty smelt

How do I start a dm message collector from different shard?

next plaza
lusty smelt

👍

lusty smelt
[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?
Bumping. Well the docs says you need to manually reconnect. But why is it happening frequently in random shards?

ashen musk
ashen musk

How are you spawning them?

next plaza
ashen musk

I was asking for code, really.

You're giving barely any information to diagnose with :p

next plaza
ashen musk

Got it. That's relatively small, I wouldn't expect any issues

next plaza

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

ashen musk

Perhaps, yeah. Odd that it'd be on one shard and not the others

next plaza
amber shoal

Hi

lusty smelt
lusty smelt
lusty smelt

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

next plaza
ashen musk
lusty smelt
ashen musk

Ah 👍

You could try removing the compression, per meister's suggestion.

calm kernel

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'
}

icy crowBOT

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.

calm kernel

i've tried that, still happens

next plaza

Did you actually logged in?

calm kernel

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` }));
next plaza
calm kernel

sure let me try

nvm i had an invalid token i think

fleet hound

what are shards

proud mortarBOT

djs 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.

winged bobcat
fleet hound

wait so it basically just keeps the bot alive?

winged bobcat

No

That is just saying when a shard dies(process exit) a new one will automatically be created

fleet hound

when would the process exit?

winged bobcat

Errors, you calling the kill method note this will not create a new one and other things

dense cape

Sharding is just splitting up the guilds ur bot is in into different processes

?sharding

icy crowBOT
dense cape

Shards will only receive events for its own guild

terse cairn

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?

lost saddle
icy crowBOT

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.

lost saddle

This can … successful launch.

jade onyx
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

peak roost

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

next plaza
peak roost
next plaza
peak roost
next plaza
peak roost
jade onyx

Will there be always be one shard where a user would be cached?

marble maple
umbral cradle

how to Check all shards are running or not.

shard status kinda.. maybe a comamnd.

I use discord sharding amanger

next plaza

0 is ready

umbral cradle

missing access, then shard 2 died. why?

ashen musk

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.

terse cairn

How i put status per shard like if guild is on shard 1 bot have status shard 1/3

winter garnet

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

next plaza

You can do single requests too

winter garnet

Okey!

winter garnet

And i cant do like: ID: this.shard.id to keep it better as a json

next plaza
winter garnet

Nice!

proud lava

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

winged bobcat
proud lava
winged bobcat

Iirc it does

winter summit
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?

sour merlin

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

winged bobcat

Its not the api

?shardreadytimeout

icy crowBOT

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

Same host same code just the token that is replaced

I’m new to these stuff I don’t really know much about it

winged bobcat

That has nothing to do with this error

sour merlin

I guess it’s the amount of servers the bot is in

Cause currently it’s in 125

winged bobcat

Could be your connection

sour merlin

Nope not the connection

Cause I used a different bot token which I use for testing and it worked perfectly fine

winged bobcat

Try setting the spawnTimeout to -1 or Infinity

sour merlin

Ok

fiery dagger

It’s just the client

winter summit

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?

fiery dagger

Could be the bot can’t find the channel

terse cairn
lost saddle
thin trench

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.
novel haven

The shards' ids start at 0, so if you have 10 shards, the ids will be in a range from 0 to 9

thin trench
covert mountain

Is it possible to have different profile depending on different server?

or bot's status different in different servers

mellow grove
thin trench

how do I check if a shard is online from its ID?

mellow grove
mellow grove

one second

thin trench
mellow grove
await client.user.setPresence({ status: "online", 
    activity:{ 
        name: `over shard 5`, 
        type: `WATCHING`
        shardID: 5
    } 
})
thin trench
mellow grove

Isn't it just this.client.shard.id? (this only really needed in broadcasteval)

thin trench
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 ^^

covert mountain

is there a limit on how many sharding I could have

thin trench

how do I check if a shard is online from its ID?

unkempt onyx

how do i find a channel from another shard?

winged bobcat
winged bobcat
winged bobcat
fiery dagger

Pro 👏

daring aspen

scam

fallen sleet

<@&839912195994812420> ^

thanks

winged bobcat

Thats because the shard process/worker is not ready

gritty comet

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.
// 
terse cairn
terse cairn

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();

next plaza

?shardreadytimeout

icy crowBOT

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.

next plaza

@terse cairn add in the spawn(undefined, undefined, -1)

terse cairn

Well, that solves the shard timeout issue, but only 1 out of 3 shards spawn.

thin trench
next plaza
gritty comet

@next plazaNo i want one guild

terse cosmos

Can someone help me ?

thin trench
icy crowBOT

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.

thin trench

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.

terse cairn
versed temple

How can I force a shard to crash?

proud mortarBOT

djs Shard#kill()
Immediately kills the shard's process/worker and does not restart it.

next plaza

@versed temple you can kill it with this Agree

versed temple

oh nice

terse cairn
versed temple

HAHAHAHAHAHAHHAHAHA

umbral cradle

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

terse cairn

Hello, was just curious: What do people recommend using for a database when sharding?

coarse arch

Just use one you're comfortable with

terse cairn
coarse arch
terse cairn
coarse arch

dms

terse cairn

@coarse arch Can I have it too?

coarse arch

sure

terse cairn

@coarse arch can I also have?

coarse arch

s u r e

winter summit
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

winter summit
next plaza
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.
lost saddle
coarse arch

sure

dense badge

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 ? pikalurk

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

pikaheartbig

next plaza
dense badge
next plaza
dense badge

No, it's a local test

next plaza

are all shards is the same node/process?

dense badge

The cache is separated correctly but there is juste one sharId in the this.client.shard.ids

dense badge
next plaza
dense badge
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)
  })
next plaza
dense badge

But it's not the problem, it's better for us WSemolgaShrug

last creek

A question do all shards have to start before the bot starts? or can you start all shards at once?

last creek
dense badge

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])
    }
terse cairn
last creek

Lmao

terse cairn

they generally don't restart for no reasons, they do maintenance downtimes etc to minimise it

dense badge

_But, I would be surprised if many people are concerned about getting 200 shards 👀 _

last creek
next plaza
dense badge
next plaza
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

dense badge
last creek

Where ?

dense badge
dense badge
next plaza
dense badge

I'm using djs 13 Meister

next plaza

yeah, ik

dense badge

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)
    }
next plaza
dense badge

Lmao i'm tired thanks Smiley_facepalm

pikaheartbig

rapid token

is client.ws.shards.size the number how many shards i have?

rapid token

cool

but when i spawn 2 shards for testing it only has 1 shard

even tho i spawned 2

coarse arch
rapid token

oh

but why did you say yes then ._.

anyways still shanks tho

coarse arch
rapid token

btw that doesnt exist

coarse arch

its a private property

rapid token

rip ts then

still nothing

same result both give 1 no matter now many shards i spawn

coarse arch

then idk

rapid token

oof thanks tho

ill just do it via broadcasteval

coarse arch

O, You can use that and get the length of what it returns

rapid token

yup

tame bridge

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

coarse arch
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

coarse arch

I feel stupid

It's from my index.js file

winter summit
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?

sour merlin

does anyone know how to fix this

next plaza

?shardreadytimeout

icy crowBOT

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.

next plaza

@sour merlin add manager.spawn(undefined, undefined, -1)

sour merlin
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

next plaza
sour merlin
next plaza
sour merlin

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

versed temple

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

winter summit
terse cairn

what is sharding?

ashen musk
terse cairn

I did already
That's from a few hours ago

terse cairn

hello im new

lyric lantern
primal heron

?off topic

icy crowBOT
nova dew

How can I host specific shards but on different hosts?

winged bobcat

specify shardLists option on each manager with the shards you want on that machine or use a package

proud mortarBOT
winged bobcat

...

deft elk

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

terse cairn

@winged bobcat What package dogoy recommend

terse cairn

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..

inland oyster

how can i get total member count from all servers in one shard

inland oyster

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

jade onyx
inland oyster

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);

jade onyx

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

inland oyster

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

jade onyx

So you want to create an invite for a guild with an ID targetID?

inland oyster

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,

jade onyx
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)

inland oyster

no luck, its not working for me

any idea @jade onyx, thank you for helping BTW

jade onyx

Is there an error? What is it logging?

inland oyster

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

jade onyx

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

gloomy totem

can someone ban this indog outta here for advertising

@light oar

digital quail

@terse cairn literally advertised on the sharding channel

light oar

?ban 461468886920069130 ads

icy crowBOT

You sure you want me to ban this [no gender specified]?

light oar

Y

icy crowBOT

Successfully banned apaan lu#1111

light oar

Just ping mods

digital quail

<@&839912195994812420>s

terse cairn

I have a kinda dum question so when I shard my bot what will I have to necessarily use broadcast eval for?

fiery dagger

I guess contacting other shards. Such as find a guild from a shard

peak roost

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)

vale bolt

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.

ashen musk
ashen musk

However, have you just considered requiring the database connection file/object directly, rather than passing it through method params?

inland oyster

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

lusty smelt
sour merlin

?shard

icy crowBOT
sour merlin

?sharding ready timeout

?shardingreadytimeout

inland oyster

Thank you.

sour merlin

could someone help me with sharding ready timeout

even after adding JS manager.spawn(undefined, undefined, -1) it doesnt work 😦

inland oyster
inland oyster

i have tried it with just shards and just shardCount neither are loading more than one shard.

lusty smelt

perhaps omit shardCount?

inland oyster

Still only creates one shard

as you can see, it still says shard are null

tawny lantern

why is my bots status not on the 2nd shard?

its only on the first shard

inland oyster

Ignore me, it is working, im just looking in the wrong place as im stupid

sour merlin

ive tried alot of methods on this issue but non of them worked 😦

manager.spawn(undefined, undefined, -1)
even with this it doesnt work

fiery dagger

Edit one of the fields

analog dagger

What is sharding? :O

lime sluice
versed temple

How can I execute a command on each shard using a .eval?

I mean something like client.emit('event') for events, but for commands

fiery dagger

Use broadcastEval()

covert vortex

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...

naive grail

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)

terse cairn

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

  1. What part of a code do i need to change/edit?
    ^^^^^ Ex. Send message, Fetch channel by id, Fetch channel across shard
  2. How can i increate the shard like 600 server for 1 shard
  3. 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?)
fiery dagger

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

crystal patrol
covert vortex

the problem is not that.

terse cairn

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.

fiery dagger

I am pretty sure djs sharding does not even split the shards. Ex 100 servers shard 1 52 servers shard 2 48 servers

next plaza
crystal patrol
terse cairn

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.

echo arch

They will be split

My test bot is in 3 servers and I spawn 2 shards and it gets split

terse cairn

the shards got split

terse cairn

can I use multiple bot tokens when sharding?

marble maple

nope sharding is for one bot

terse cairn
echo arch

Yea I manually spawn them

terse cairn

how do you do that?

echo arch

you just provide the shard count instead of auto xd

odd sequoia

Does anyone have a good sharding tutorial?
I dont like using the documentation because its so impractical and confusing xD

strange echo

please see the pins

odd sequoia

Whoops sorry!

sullen shard

Is there a point where the bot needs to start sharding? When does it become required

terse cairn

1.5k guilds iirc

winged bobcat

2.5k

winter summit

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?

terse cairn

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.

scarlet helm

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

lime sluice

?shardreadytimeout

icy crowBOT

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

how do i force the shardmanager to create 2 shards for example when the bot only has 2 guilds?

proud mortarBOT
next plaza

@terse cairn ⏫ provide a Total Shard count

terse cairn

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)

next plaza

bc, Discord decides which Guild belongs to which Websocket

On 2 guilds, its likely that the other shard has no guilds on the Websocket

terse cairn

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

primal heron
terse cairn
winter summit

How to use message.guild.members.cache in Shards?

fiery dagger

Use broadcastEval()

If it’s fetching a member

winter summit
fiery dagger

If it’s within the guild you don’t need to

It’s only used when fetching from different shards

little bluff

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?

next plaza

When your Cpu usage isnt so high, then Clustering is reasonable

still palm

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?

fair cairn

dont run more than 1 server boom problem solved

still palm

DoubleFacepalm

lost saddle
next plaza
still palm

thx

halcyon arch

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

little bluff

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

winged bobcat
little bluff

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?

winged bobcat
terse cairn

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' });
fiery dagger

?shardreadytimeout

icy crowBOT

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.

tame bridge

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

idle glacier

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

icy crowBOT
hoary stream

sometime one guild is getting cached in multiple shards, how to stop it?

ashen musk

That shouldn't happen. How are you sharding?

hoary stream

ShardingManager

sometimes getting same guild id in this.client.guilds.cache.keyArray() in different shards

ashen musk

Can you share where you define your sharding manager.

hoary stream

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'] });

ashen musk

What do totalShards and shardList log as?

hoary stream

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

ashen musk

Try removing both of those (or setting them both to "auto") and see if it makes any difference.

hoary stream

ok

hoary stream

to be on safe side can i do something like this before processing anything

if (guild.shardID != this.client.shard.ids[0]) return;

terse cairn

I mean it's your code you surely can?

Might be a bit unnecessary though if the issue was already fixed by the above

hoary stream

@ashen musk ?

sorry for the ping

ashen musk

You can always ping me. No problem.

Did the above not fix the issue?

@hoary stream ^

hoary stream

still testing as this happens only sometimes not always

next plaza
terse cairn

how can I monitor sharders?\

brittle marsh

does this issue related to sharding ?

halcyon arch

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);
ashen musk
brittle marsh
halcyon arch
ashen musk

Ask discord MagystShrug

devout jungle

But anyway this isn't really on-topic anymore

hearty pewter

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

strange echo

Probably need to reference the client on each shard instead of message.client

hearty pewter
strange echo

No idea, I don't do sharding. That's just my guess based off using message.client

hearty pewter

@ me if someone has a answer

next plaza
next plaza

you broadcast a string (or function in v13)

It would be client.shard.broadcastEval("this.commands.set('${newCommand.name}', ${newCommand})")

lusty smelt
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? woahhh

ashen musk

context is an object, not a string.

{
  context: {
    id: req.query.userId
  }
}

@lusty smelt you're on v13, yes?^

lusty smelt
ashen musk

Best moved to #djs-help-v14, but that should be the fix you need

@lusty smelt (keep forgetting to reply)

lusty smelt

tyty!

winter summit

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?
hearty pewter
next plaza It would be `client.shard.broadcastEval("this.commands.set('${newCommand.name}',...

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})`)
hearty pewter
next plaza 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})")
copper solstice
winter summit

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?

random jackal

how would i set the client status to be
Shard: shard id/total shards

next plaza

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)

lusty smelt
next plaza

lol, good

lusty smelt

um why?

crystal patrol

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

crystal patrol
real spire

How do I get the shard count of my bot?

hearty pewter
real spire

How do I get the shard count of my bot?

lime sluice

client.shard.count i think

tawny lantern

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

sterile hound
glad stump

Do you need to have 2,000+ guilds to shard?

lime sluice

Nope, you can do it whenever you want

glad stump

Okay thanks you

winged bobcat
winged bobcat
zinc parrot

ok

crystal patrol

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 ?

tawny lantern

why is my bots status not on every shard?

terse cairn
tawny lantern
terse cairn
winged bobcat

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

ashen musk

We're not here to explain modules/express. Check out #resources for information on that.

random jackal

how would i set the client status to be
Shard: shard id/total shards

strange echo

?ban @analog flax shitpost in support

icy crowBOT

You sure you want me to ban this [no gender specified]?

strange echo

y

icy crowBOT

Successfully banned cool boi abc#3709

polar idol

everytime i use my shard stats command it shows cannot read property of broadcastEval
any solution for this?

next plaza

you are probably not sharding or using it wrong, could you show your code?

polar idol
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);```
polar idol
polar idol

bruh after sharding the ping is like 10k + ms

crystal patrol

hey why discord.js sharding is so fucking bad and when shard dies they no respawning with the options respawn true

tawny lantern

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

winged bobcat
winter summit

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?

delicate ivy

I have question?
What do shards do?

fiery dagger

splits the bots code

crystal patrol
crystal patrol

like wtf some shard respawn all the time it’s not stable and other just died and never respawn

pallid spindle
lyric lantern

Does dms use sharding?

ashen musk
lyric lantern
ashen musk

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

lyric lantern

thank you

terse cairn
little river
stark plank

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

marsh finch

You might want to show relevant code.

dapper quiver

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

icy crowBOT

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)

pale sable

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?

dapper quiver
random jackal

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?

sharp void
[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?

winged bobcat
lofty plover

?ban 801088898217410570 ads

icy crowBOT

You sure you want me to ban this [no gender specified]?

lofty plover

y

icy crowBOT

Successfully banned Shreyansh#6963

abstract saddle

I have this error

why ?

winged bobcat

?shardreadytimeout

icy crowBOT

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.

winged bobcat
abstract saddle

ty

stark plank

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

winged bobcat
terse cairn

how i can add shard id to bot activity ?

winged bobcat

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

terse cairn

ok

worthy surge

What is Shards and what do they do :?

pallid depot
const manager = new ShardingManager('./OFF/offlimits.js', { token: config.token });
Cannot create property 'shardCount' on string 'token'```
thin trench

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] { } ]

abstract elm
dense cape

You forgot the spread operator

[…<Map>.values()]

thin trench
abstract elm

Oh

thin trench
dense cape

Can’t you just broadcastEval then?

thin trench
dense cape

Show code

abstract elm

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}`) ? '![Active](https://cdn.discordapp.com/emojis/577568551414792216.webp?size=128 "Active") Online' : '![Issues](https://cdn.discordapp.com/emojis/577568551368654849.webp?size=128 "Issues") Offline'}

thin trench
dense cape Show code

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

dense cape

You have the shard id defined, but never used it

Always passing in 0 for the id

thin trench
thin trench
vestal ridge

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.

dense cape

Prob need to convert the id to a number

thin trench
thin trench

There is an example for this on the docs

vestal ridge

oh ok

any example with command handler

abstract elm
dense cape What does it output?

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

hybrid terrace

bestie

lofty plover

?kick 756503000016486402 spamming threads in support

icy crowBOT

Successfully kicked ThatOneExplorer#9387

hybrid terrace

Nvm

abstract elm

How would i get an argument "inside" of a broadcastEval?

nova dew

Hey! How can I make regional shards?

next plaza
terse cairn

If you know what we mean

nova dew

Yep ^^

winged bobcat
nova dew Hey! How can I make regional shards?

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

nova dew
winged bobcat

Pass the shardList on the Shardingmanager options with an array of shard ids you want the ShardingManager to spawn

?docs ShardingManager#shardList

icy crowBOT
dark cape

after im trying to spawn the bot, I think the bot is not really stable, shard keep reloading. I'm using v12, any advices ?

steep otter

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));
next plaza

@steep otter check this

covert patio

How do I change the number of shards and how many servers go on each?

next plaza

Discord decides how many servers will be a shard. But you can make a rough calculation

covert patio

Oh cool ty

covert patio

Does anyone have a shard friendly ping command?

steep otter
next plaza
covert patio

Thanks, I'll give it a go

covert patio
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

covert patio

It should be ready, I have a ready event that gets triggered

covert patio
next plaza your bot has to become ready

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?

covert patio

I'm having to use this.guilds.cache.first().shardID

And this.users.cache.size is returning the same as this.guilds.cache.size

digital vine
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.

steep otter

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 } });
dense cape

If you know the shard count, you can determine which shard to send it to

proud mortarBOT
steep otter

I'll look into that method

deft nest

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

dense cape
deft nest

basicly 1. [0 & 1]

dense cape

You can’t specify which guilds go to which shard

It’s determined by a formula

terse cairn

What's the formula

proud mortarBOT
polar idol

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 :/
next plaza
polar idol

wait imma show you

next plaza

could you log out client.shard

polar idol
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?
next plaza
polar idol

it's sharded,
i guess this wont work if it was not sharded

i see

next plaza
polar idol

ok

covert patio

How do I get CPU usage on a shard?

dense bough

hello, what does the replayed event parameter in the cliend.shardReconnect mean?

steep otter

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,
};
south fjord

Is there anyway to host a bot on many separated physic servers?

limpid jackal
winged bobcat
covert patio

How do I get CPU usage on a specific shard?

serene smelt

I built a fully functional "Portable IDE Sandbox"

jagged vector
dense cape
covert patio

How do I get the number of shards?

terse cairn

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

next plaza
next plaza
covert patio
next plaza
covert patio 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));
}
covert patio

Oh wow! tysm!

covert patio

I multiplied the CPU usage by 100 because .2% didn't look right

next plaza
covert patio

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

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

covert patio

Do shards only respond to broadcast eval if they have a server on the shard?

next plaza
covert patio

Yeah, my issue is that when I broadcast eval "console.log(1)" I only get 1 response but no errors

dense cape

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

covert patio

I couldn't work out how to directly pass it in because the function has the first argument as client for some reason

dense cape

You can provide a context in the second param of broadcastEval, then it’ll show up in the second param of the callback function

proud mortarBOT
covert patio
dense cape

The context option was only added bc of that change

covert patio
dense cape

Still need to pass it in via options.context

terse cairn
covert patio

Sorry, my emojis are custom designed so id rather keep them private

dense cape

Ur code doesn’t come with emojis tho

I guess you could download it with the id

covert patio

I was guessing they wanted it because of how good the emojis looked

terse cairn
covert patio
dense cape

I also linked the docs earlier

covert patio

Oh ty

covert patio

shards = await client.shard.broadcastEval(function() {}, {context: ????})

dense cape

context: code

@covert patio

covert patio

oh ty

steady nimbus

@dense cape you know what the problem is

next plaza

in v13 WebhookClient Class has been changed. It is now:

- new WebhookClient(WEBHOOKID, WEBHOOKTOKEN)
+ new WebhookClient({id: WEBHOOKID, token: WEBHOOKTOKEN})
steady nimbus

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

next plaza
glacial forge

What mode of sharding is 'better' for performance, process or worker?

vivid bough

how to add shard?

proud mortarBOT

• 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

next plaza
covert patio
covert patio
covert patio

k, tysm!

terse cairn
next plaza
terse cairn
next plaza
terse cairn
next plaza
terse cairn
heady pendant
heady pendant

i'll give a try thank you

I'm unable to make it work

tried this and this

steep otter

try passing that into the broadcastEval instead (as well as keeping it in the context)

broadcastEval((client, { commandName }) => ...

heady pendant

alr one sec

yay, seems to be working

it's the way I made it, sharing purpose

@steep otter and thanks, appreciate your help

steep otter

👍

terse cairn
next plaza
terse cairn

Can it be my version of node?

next plaza
terse cairn

node v16.4

terse cairn
subtle sedge

what's sharding

rancid pier
mighty fog

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?

dense cape

Eval(…, { context: d })

mighty fog

thanx, will try

gaunt igloo

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?

stoic remnant

WebhookClient or Client?

gaunt igloo

Client

stoic remnant

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?

gaunt igloo

const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES]});

stoic remnant

Then it's not coming from there, might as well wait for someone else who knows

gaunt igloo
brisk grove

bro...

stoic remnant

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

gaunt igloo

Already regenerated when I posted that

stoic remnant

Could you show the full error trace?

gaunt igloo
        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)```
stoic remnant

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)

gaunt igloo
oblique leaf

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?

sleek imp

how can i send something from the bot's process to the manager's process

winged bobcat
sleek imp
winged bobcat

Yes

sleek imp

okay

so in bot.js i put process.send and in the manager file i put process.on("message")

winged bobcat
winged bobcat
sleek imp

oh

works now, thanks

oblique leaf
winged bobcat
oblique leaf

No, because the context is different somehow. It throws a failed reference error.

sleek imp
oblique leaf
winged bobcat

Okie

winged bobcat

Wdym by forked

sleek imp
winged bobcat

So the sharding manager is not the main process right

sleek imp

nope

main process => sharding manager => bot

sleek imp
winged bobcat

Ok

This is heading to not djs related but on thr main process are you listening for messages from the worker

oblique leaf

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 })
//...
}```