Search code examples
javascripteventsdiscord.jsbroadcastsharding

How to pass dynamic content from shardManager to shard instances using discord.js?


I am fairly new to discord.js. I would like to pass dynamic content from my 'index.js' file, which instantiates my shardingManager, to the shard instances in my 'bot.js' file. I have tried this in a few different ways. Most recently, I have tried using the .broadcast method on the sharding manager, but I do not understand how each shard is supposed to receive the argument passed by the broadcast method. I have had a hard time finding documentation on the methods available on the shardingmanager. I have read through https://discord.js.org/#/docs/main/main/class/ShardingManager?scrollTo=broadcast, and https://anidiots.guide/understanding/sharding/, but neither provide any significant information on the .broadcast method, in particular.

Here is one approach that I have tried:

index.js:

//import libraries, login to create etc... 

client.login(token);
const shardManager = new ShardingManager('./bot.js', {
  token,
});
shardManager.spawn();
shardManager.broadcast('message');

bot.js

//import libraries, login to create etc... 

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on('message', (message) => {
  if (message === 'message') {
    console.log('Received the event message');
  }
});

This, sadly, did not log 'Received the event message' to my console...

I am using discord.js version 14.7.1


Solution

  • After a bit more research (I defer the source), the following changes got my code to work. index.js: shardManager.broadcast({ type: 'update', data: 'new data'});

    bot.js

    client.on('message', (message) => {
      if (message.type === 'update') {
        console.log(`received ${message.data)`;
      }
    });
    

    using the 'process' class instead of the 'client' class and passing this object with two properties (type and data), and accessing the type and data properties on the message seemed to work.

    Thanks! Dan