Sharding

Learn how to use the SlashCommandHandler with discord's sharding manager.

When you are using discord's sharding manager in your bot, loading commands will be a bit different to prevent serious issues and rate limiting.

This will be in the index.js file (The main).

// Imports

const { Client, ShardingManager } = require('discord.js');
const { SlashCommandHandler } = require('slashdiscord.js');

// The bot's token and id

const token = 'BOT_TOKEN';
const id = 'BOT_ID';

// Make sure that this part is runny async, the sharding manager can
// only spawn when the commands are fully loaded to prevent issues.

(async () => {

  // Creating the handler.
  // We will be using the ClientLike object when using the Sharding Manager

  const handler = new SlashCommandHandler({
    client: {
      token: token,
      id: id
    }
  });

  // Creating the commands, you don't need to include a run function since
  // this handler won't listen for commands.

  handler.addCommand({
   name: 'shard',
   description: 'Get the shard this bot is running from.'
  });

  // Loading the commands

  await handler.start();
  console.log('Loaded commands');

  // Creating the ShardingManager

  const manager = new ShardingManager('bot.js', {
    token: token
  });

  // and lets spawn the shards now

  manager.spawn();
})();

Now lets make the bot.js file, this is where your main client will be ran from.

//	Imports

const { Client } = require('discord.js');
const { SlashCommandHandler } = require('slashdiscord.js');

// Creating the Discord Client

const client = new Client();

// The command handler will have a option to prevent it from editing the commands

const handler = new SlashCommandHandler({
  client: client,
  registerCommands: false,
});

// Adding the commands, the commands MUST be an exact copy of the ones in
// the ShardingManager.

handler.addCommand({
  name: 'shard',
  description: 'Get the shard this bot is running from.'
})
.run(interaction => {
  interaction.reply(`This guild is using shard #${client.shard.ids[0]}`);
});


// Logging in the client, we don't need a token here since the ShardingManager
// will provide that for us.

client.once('ready', () => {
  console.log(`Shard ${client.shard.ids[0]} has started.`);
})

client.login();

An example using TypeScript can be found here

Last updated

Was this helpful?