feat: update ready events to handle sharding

This commit is contained in:
Marius Begby committed 2023-07-21 12:27:49 +02:00
1 parent 006f2fab51
commit 184b528f56
4 files changed
+55 -17

No files matched your search

+6 -2
View File
@@ -1,3 +1,4 @@
require('dotenv').config();
const logger = require('./services/logger'); const logger = require('./services/logger');
const { registerEventListeners } = require('./utils/registerEventListeners.js'); const { registerEventListeners } = require('./utils/registerEventListeners.js');
const { registerClientCommands } = require('./utils/registerClientCommands.js'); const { registerClientCommands } = require('./utils/registerClientCommands.js');
@@ -8,8 +9,11 @@ const { createPlayer } = require('./utils/factory/createPlayer.js');
const client = await createClient(); const client = await createClient();
const player = await createPlayer(client); const player = await createPlayer(client);
registerEventListeners(client, player); client.on('allShardsReady', async () => {
registerClientCommands(client); registerEventListeners(client, player);
registerClientCommands(client);
client.emit('ready', client);
});
client.login(process.env.DISCORD_BOT_TOKEN); client.login(process.env.DISCORD_BOT_TOKEN);
})().catch((error) => { })().catch((error) => {
+16 -9
View File
@@ -1,28 +1,35 @@
const logger = require('../../services/logger'); const logger = require('../../services/logger');
const { embedOptions, systemOptions, presenceStatusOptions } = require('../../config'); const { embedOptions, systemOptions, presenceStatusOptions } = require('../../config');
const { Events, EmbedBuilder } = require('discord.js');
const { postBotStats } = require('../../utils/other/postBotStats.js'); const { postBotStats } = require('../../utils/other/postBotStats.js');
const { Events, EmbedBuilder } = require('discord.js');
module.exports = { module.exports = {
name: Events.ClientReady, name: Events.ClientReady,
isDebug: false, isDebug: false,
once: true, once: false,
execute: async (client) => { execute: async (client) => {
logger.info(`Client logged in successfully as ${client.user.tag}!`); logger.debug(`Shard ${client.shard.ids[0]}> Client 'ready' event emitted after 'allShardsReady'.`);
await client.user.setPresence(presenceStatusOptions);
await client.user.setPresence(presenceStatusOptions); await client.user.setPresence(presenceStatusOptions);
// Post bot stats to bot lists in production const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
process.env.NODE_ENV === 'production' ? postBotStats(client) : null;
// send message to system message channel for event // Check if the channel exists in curent shard and send a message
if (systemOptions.systemMessageChannelId) { if (channel) {
await client.channels.cache.get(systemOptions.systemMessageChannelId).send({ logger.info(
`Shard ${client.shard.ids[0]}> All shards ready, sending system message to channel id ${channel.id}.`
);
channel.send({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
.setDescription(`${embedOptions.icons.success} **${client.user.tag}** is now **\`online\`**!`) .setDescription(
`**${embedOptions.icons.success} All shards ready**\n**${client.user.tag}** is now **\`online\`**!`
)
.setColor(embedOptions.colors.success) .setColor(embedOptions.colors.success)
] ]
}); });
} }
process.env.NODE_ENV === 'production' ? await postBotStats(client) : null;
} }
}; };
+11 -2
View File
@@ -1,17 +1,26 @@
require('dotenv').config(); require('dotenv').config();
const logger = require('./services/logger'); const logger = require('./services/logger');
const { ShardingManager } = require('discord.js'); const { ShardingManager, ShardEvents } = require('discord.js');
const manager = new ShardingManager('./src/bot.js', { const manager = new ShardingManager('./src/bot.js', {
token: process.env.DISCORD_BOT_TOKEN, token: process.env.DISCORD_BOT_TOKEN,
totalShards: 'auto', totalShards: 2,
shardList: 'auto', shardList: 'auto',
mode: 'process', mode: 'process',
respawn: true respawn: true
}); });
const readyShards = new Set();
manager.on('shardCreate', (shard) => { manager.on('shardCreate', (shard) => {
logger.debug(`Launched shard ${shard.id}`); logger.debug(`Launched shard ${shard.id}`);
// When all shards are ready, emit event 'allShardsReady' to all shards
shard.on(ShardEvents.Ready, () => {
readyShards.add(shard.id);
if (readyShards.size === manager.totalShards) {
manager.broadcastEval((client) => client.emit('allShardsReady'));
}
});
}); });
manager.spawn(); manager.spawn();
+22 -4
View File
@@ -1,9 +1,27 @@
const logger = require('../../services/logger'); const logger = require('../../services/logger');
const https = require('node:https'); const https = require('node:https');
exports.postBotStats = (client) => { exports.postBotStats = async (client) => {
try { try {
const guildCount = client.guilds.cache.size; if (client.shard.ids[0] !== 0) {
return logger.debug(`Shard ${client.shard.ids[0]}> Shard is not the first shard, not posting stats.`);
}
logger.debug(
client.shard.ids,
`Shard ${client.shard.ids[0]}> Posting stats to bot lists from client with shard id 0.`
);
let guildCount = 0;
await client.shard
.fetchClientValues('guilds.cache.size')
.then((results) => {
guildCount = results.reduce((acc, guildCount) => acc + guildCount, 0);
})
.catch((error) => {
logger.error(error, `Shard ${client.shard.ids[0]}> Failed to fetch client values from shards.`);
});
/* eslint-disable camelcase */ /* eslint-disable camelcase */
const sites = [ const sites = [
@@ -51,7 +69,7 @@ exports.postBotStats = (client) => {
} }
]; ];
logger.info(`Posting stats to bot lists with guildCount ${guildCount}...`); logger.info(`Shard ${client.shard.ids[0]}> Posting stats to bot lists with guildCount ${guildCount}...`);
sites.map((site) => { sites.map((site) => {
let options = { let options = {
protocol: 'https:', protocol: 'https:',
@@ -75,6 +93,6 @@ exports.postBotStats = (client) => {
request.end(); request.end();
}); });
} catch (error) { } catch (error) {
logger.error(error, 'Failed to post stats to bot lists'); logger.error(error, `Shard ${client.shard.ids[0]}> Failed to post stats to bot lists.`);
} }
}; };