Merge pull request #100 from mariusbegby/sharding-discord-js

Sharding discord js
This commit is contained in:
Marius Begby authored and GitHub committed 2023-07-21 14:18:59 +02:00
commit 628c3869da
31 files changed
+396 -162

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
require('dotenv').config();
const logger = require('./services/logger');
const { registerEventListeners } = require('./utils/registerEventListeners.js');
const { registerClientCommands } = require('./utils/registerClientCommands.js');
const { createClient } = require('./utils/factory/createClient.js');
const { createPlayer } = require('./utils/factory/createPlayer.js');
(async () => {
const client = await createClient();
const player = await createPlayer(client);
client.on('allShardsReady', async () => {
registerEventListeners(client, player);
registerClientCommands(client);
client.emit('ready', client);
});
client.login(process.env.DISCORD_BOT_TOKEN);
})().catch((error) => {
logger.error(error);
});
+15 -5
View File
@@ -78,7 +78,9 @@ module.exports = {
],
components: [filterActionRow, disableFiltersActionRow]
});
logger.debug(`Sent embed for command ${interaction.commandName}, awaiting interaction response.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Sent embed for command ${interaction.commandName}, awaiting interaction response.`
);
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
@@ -87,7 +89,9 @@ module.exports = {
time: 60000
});
logger.debug(`Received interaction response for command ${interaction.commandName}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Received interaction response for command ${interaction.commandName}.`
);
confirmation.deferUpdate();
@@ -128,7 +132,11 @@ module.exports = {
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values);
logger.debug(`Enabled filters ${confirmation.values.join(', ')} for command ${interaction.commandName}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Enabled filters ${confirmation.values.join(', ')} for command ${
interaction.commandName
}.`
);
return await interaction.editReply({
embeds: [
@@ -157,13 +165,15 @@ module.exports = {
});
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug(`Interaction response timed out for command ${interaction.commandName}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Interaction response timed out for command ${interaction.commandName}.`
);
return;
}
logger.debug(
error,
`Unhandled error while awaiting interaction response for command ${interaction.commandName}, throwing error.`
`[Shard ${interaction.guild.shardId}] Unhandled error while awaiting interaction response for command ${interaction.commandName}, throwing error.`
);
throw error;
}
+6 -2
View File
@@ -19,7 +19,9 @@ module.exports = {
const queue = useQueue(interaction.guild.id);
if (!queue) {
logger.debug(`User used command ${interaction.commandName} but there was no queue.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -33,7 +35,9 @@ module.exports = {
if (!queue.deleted) {
queue.delete();
logger.debug(`User used command ${interaction.commandName} and deleted the queue.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and deleted the queue.`
);
return await interaction.editReply({
embeds: [
+16 -6
View File
@@ -46,7 +46,9 @@ module.exports = {
const currentModeUserString = loopModesFormatted.get(currentMode);
if (!mode && mode !== 0) {
logger.debug(`User used command ${interaction.commandName} but no mode was provided.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but no mode was provided.`
);
return await interaction.editReply({
embeds: [
@@ -63,7 +65,7 @@ module.exports = {
if (mode === currentMode) {
logger.debug(
`User used command ${interaction.commandName} but loop mode was already set to ${modeUserString}.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but loop mode was already set to ${modeUserString}.`
);
return await interaction.editReply({
@@ -80,7 +82,9 @@ module.exports = {
queue.setRepeatMode(mode);
if (!queue.repeatMode === mode) {
logger.debug(`User used command ${interaction.commandName} but failed to change loop mode.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but failed to change loop mode.`
);
return await interaction.editReply({
embeds: [
@@ -94,7 +98,9 @@ module.exports = {
}
if (queue.repeatMode === 0) {
logger.debug(`User used command ${interaction.commandName} and disabled loop mode.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and disabled loop mode.`
);
return await interaction.editReply({
embeds: [
@@ -112,7 +118,9 @@ module.exports = {
}
if (queue.repeatMode === 3) {
logger.debug(`User used command ${interaction.commandName} and enabled autoplay.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and enabled autoplay.`
);
return await interaction.editReply({
embeds: [
@@ -129,7 +137,9 @@ module.exports = {
});
}
logger.debug(`User used command ${interaction.commandName} and enabled loop mode.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and enabled loop mode.`
);
return await interaction.editReply({
embeds: [
+21 -8
View File
@@ -93,7 +93,9 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(`User used command ${interaction.commandName}, finished intializing data.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName}, finished intializing data.`
);
const response = await interaction.editReply({
embeds: [
@@ -143,7 +145,9 @@ module.exports = {
components: [nowPlayingActionRow]
});
logger.debug(`User used command ${interaction.commandName}, finished sending response.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName}, finished sending response.`
);
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
@@ -155,10 +159,12 @@ module.exports = {
confirmation.deferUpdate();
if (confirmation.customId === 'nowplaying-skip') {
logger.debug(`User used command ${interaction.commandName}, received skip confirmation.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName}, received skip confirmation.`
);
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
logger.debug(
`User used command ${interaction.commandName} and tried skipping but there was no queue.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and tried skipping but there was no queue.`
);
return await interaction.followUp({
embeds: [
@@ -174,7 +180,7 @@ module.exports = {
if (queue.currentTrack !== currentTrack) {
logger.debug(
`User used command ${interaction.commandName} and tried skipping but the track was already removed.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and tried skipping but the track was already removed.`
);
return await interaction.followUp({
embeds: [
@@ -197,7 +203,9 @@ module.exports = {
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(`User used command ${interaction.commandName} and skipped the track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and skipped the track.`
);
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -225,11 +233,16 @@ module.exports = {
}
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug(`User used command ${interaction.commandName} but did not respond to the skip prompt.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but did not respond to the skip prompt.`
);
return;
}
logger.debug(error, `User used command ${interaction.commandName} but there was an unhandled error.`);
logger.debug(
error,
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was an unhandled error.`
);
throw error;
}
}
+5 -1
View File
@@ -32,7 +32,11 @@ module.exports = {
// change paused state to opposite of current state
queue.node.setPaused(!queue.node.isPaused());
logger.debug(`User used command ${interaction.commandName} and set paused state to ${queue.node.isPaused()}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${
interaction.commandName
} and set paused state to ${queue.node.isPaused()}.`
);
return await interaction.editReply({
embeds: [
+27 -11
View File
@@ -28,12 +28,12 @@ module.exports = {
requestedBy: interaction.user
});
} catch (error) {
logger.error('Failed to search for track with player.search()');
logger.error('[Shard ${interaction.guild.shardId}] Failed to search for track with player.search()');
logger.error(error);
}
if (!searchResult || searchResult.tracks.length === 0) {
logger.debug(`No results found for query: ${query}`);
logger.debug(`[Shard ${interaction.guild.shardId}] No results found for query: ${query}`);
return await interaction.editReply({
embeds: [
@@ -51,7 +51,9 @@ module.exports = {
searchResult.tracks[0].raw.duration === 0 &&
searchResult.tracks[0].source === 'youtube'
) {
logger.debug(`Unsupported audio source. Query: ${query}. Track is live, 0 duration and from YouTube.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Unsupported audio source. Query: ${query}. Track is live, 0 duration and from YouTube.`
);
return await interaction.editReply({
embeds: [
@@ -88,7 +90,7 @@ module.exports = {
}
}));
logger.debug(`player.play() successful. Query: ${query}.`);
logger.debug(`[Shard ${interaction.guild.shardId}] player.play() successful. Query: ${query}.`);
} catch (error) {
if (error.message.includes('Sign in to confirm your age')) {
return await interaction.editReply({
@@ -108,7 +110,10 @@ module.exports = {
error.message.includes('Failed to fetch resources for ytdl streaming'))) ||
error.message.includes('Could not extract stream for this track')
) {
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
logger.debug(
error,
`[Shard ${interaction.guild.shardId}] Found track but failed to retrieve audio. Query: ${query}.`
);
return await interaction.editReply({
embeds: [
@@ -122,7 +127,7 @@ module.exports = {
}
if (error.message === 'Cancelled') {
logger.debug(error, `Operation cancelled. Query: ${query}.`);
logger.debug(error, `[Shard ${interaction.guild.shardId}] Operation cancelled. Query: ${query}.`);
return await interaction.editReply({
embeds: [
@@ -135,13 +140,18 @@ module.exports = {
});
}
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
logger.error(
error,
'[Shard ${interaction.guild.shardId}] Failed to play track with player.play(), unhandled error.'
);
}
let queue = useQueue(interaction.guild.id);
if (!queue) {
logger.warn(`After player.play(), queue is undefined. Query: ${query}.`);
logger.warn(
`[Shard ${interaction.guild.shardId}] After player.play(), queue is undefined. Query: ${query}.`
);
return await interaction.editReply({
embeds: [
@@ -162,7 +172,9 @@ module.exports = {
let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: ${query}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Playlist found and added with player.play(). Query: ${query}.`
);
return await interaction.editReply({
embeds: [
@@ -185,7 +197,9 @@ module.exports = {
}
if (queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(`Track found and added with player.play(), started playing. Query: ${query}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Track found and added with player.play(), started playing. Query: ${query}.`
);
return await interaction.editReply({
embeds: [
@@ -204,7 +218,9 @@ module.exports = {
});
}
logger.debug(`Track found and added with player.play(), added to queue. Query: ${query}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Track found and added with player.play(), added to queue. Query: ${query}.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+15 -5
View File
@@ -21,7 +21,9 @@ module.exports = {
if (!queue) {
if (pageIndex >= 1) {
logger.debug(`User used command ${interaction.commandName} but there was no queue.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -35,7 +37,9 @@ module.exports = {
});
}
logger.debug(`User used command ${interaction.commandName} but there was no queue.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
queueString = 'The queue is empty, add some tracks with **`/play`**!';
return await interaction.editReply({
embeds: [
@@ -57,7 +61,9 @@ module.exports = {
const totalPages = Math.ceil(queueLength / 10) || 1;
if (pageIndex > totalPages - 1) {
logger.debug(`User used command ${interaction.commandName} but page was higher than total pages.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but page was higher than total pages.`
);
return await interaction.editReply({
embeds: [
@@ -106,7 +112,9 @@ module.exports = {
}`;
if (!currentTrack) {
logger.debug(`User used command ${interaction.commandName} but there was no current track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no current track.`
);
return await interaction.editReply({
embeds: [
@@ -139,7 +147,9 @@ module.exports = {
bar = '_No duration available._';
}
logger.debug(`User used command ${interaction.commandName} and got queue in reply with current track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and got queue in reply with current track.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+6 -2
View File
@@ -31,7 +31,9 @@ module.exports = {
const removeTrackNumber = interaction.options.getNumber('tracknumber');
if (removeTrackNumber > queue.tracks.data.length) {
logger.debug(`User used command ${interaction.commandName} but track number was higher than total tracks.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but track number was higher than total tracks.`
);
return await interaction.editReply({
embeds: [
@@ -49,7 +51,9 @@ module.exports = {
let durationFormat =
removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' ? '' : `\`${removedTrack.duration}\``;
logger.debug(`User used command ${interaction.commandName} and removed track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and removed track.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+11 -5
View File
@@ -46,7 +46,9 @@ module.exports = {
}
if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug(`User used command ${interaction.commandName} but entered an invalid duration.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered an invalid duration.`
);
return await interaction.editReply({
embeds: [
@@ -74,7 +76,7 @@ module.exports = {
if (!validElements) {
logger.debug(
`User used command ${interaction.commandName} but entered an invalid duration after parsing duration.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered an invalid duration after parsing duration.`
);
return await interaction.editReply({
embeds: [
@@ -97,7 +99,7 @@ module.exports = {
if (!isValidDuration) {
logger.debug(
`User used command ${interaction.commandName} but entered an invalid duration after regex checks.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered an invalid duration after regex checks.`
);
return await interaction.editReply({
@@ -118,7 +120,9 @@ module.exports = {
const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000;
if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
logger.debug(`User used command ${interaction.commandName} but entered a duration longer than the track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered a duration longer than the track.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -132,7 +136,9 @@ module.exports = {
queue.node.seek(durationInMilliseconds);
logger.debug(`User used command ${interaction.commandName} and seeked to duration.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and seeked to duration.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+8 -4
View File
@@ -33,7 +33,7 @@ module.exports = {
if (skipToTrack) {
if (skipToTrack > queue.tracks.data.length) {
logger.debug(
`User used command ${interaction.commandName} but track number was higher than total tracks.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but track number was higher than total tracks.`
);
return await interaction.editReply({
embeds: [
@@ -52,7 +52,9 @@ module.exports = {
: `\`${skippedTrack.duration}\``;
queue.node.skipTo(skipToTrack - 1);
logger.debug(`User used command ${interaction.commandName} and skipped to track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and skipped to track.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -71,7 +73,7 @@ module.exports = {
} else {
if (queue.tracks.data.length === 0 && !queue.currentTrack) {
logger.debug(
`User used command ${interaction.commandName} but there was no tracks in queue or current track.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no tracks in queue or current track.`
);
return await interaction.editReply({
embeds: [
@@ -100,7 +102,9 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(`User used command ${interaction.commandName} and skipped track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and skipped track.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+8 -4
View File
@@ -34,7 +34,7 @@ module.exports = {
const currentVolume = queue.node.volume;
logger.debug(
`User used command ${interaction.commandName} but no volume was provided, providing info of current volume.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but no volume was provided, providing info of current volume.`
);
return await interaction.editReply({
embeds: [
@@ -49,7 +49,7 @@ module.exports = {
});
} else if (volume > 100 || volume < 0) {
logger.debug(
`User used command ${interaction.commandName} but volume was higher than 100% or lower than 0%.`
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but volume was higher than 100% or lower than 0%.`
);
return await interaction.editReply({
embeds: [
@@ -64,7 +64,9 @@ module.exports = {
queue.node.setVolume(volume);
if (volume === 0) {
logger.debug(`User used command ${interaction.commandName} and muted volume.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and muted volume.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -80,7 +82,9 @@ module.exports = {
});
}
logger.debug(`User used command ${interaction.commandName} and changed volume.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and changed volume.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+22 -5
View File
@@ -1,3 +1,4 @@
const logger = require('../../services/logger');
const { embedOptions } = require('../../config');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidation');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
@@ -10,10 +11,26 @@ module.exports = {
.setDMPermission(false),
execute: async ({ interaction, client }) => {
if (await notValidGuildId(interaction)) {
logger.debug(`[Shard ${client.shard.ids[0]}] Not a valid guild id.`);
return;
}
let guildsList = client.guilds.cache
let shardGuilds = [];
let totalGuildCount = 0;
await client.shard
.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
return guild;
});
})
.then((guilds) => {
shardGuilds = guilds.flat(1);
});
totalGuildCount = shardGuilds.length;
let guildListFormatted = shardGuilds
.map((guild) => {
return {
name: guild.name,
@@ -21,16 +38,16 @@ module.exports = {
};
})
.sort((a, b) => b.memberCount - a.memberCount)
.slice(0, 50)
.slice(0, 25)
.map((guild, index) => `${index + 1}. \`${guild.name} (#${guild.memberCount})\``)
.join('\n');
const totalMemberCount = client.guilds.cache.reduce((a, b) => a + b.memberCount, 0);
const totalMemberCount = shardGuilds.reduce((a, b) => a + b.memberCount, 0);
let embedDescription =
`**${embedOptions.icons.bot} ${
client.guilds.cache.size < 50 ? `Top ${client.guilds.cache.size} guilds` : 'Top 50 guilds'
} by member count (${client.guilds.cache.size} total)**\n${guildsList}` +
totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds'
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** \`${totalMemberCount}\``;
if (embedDescription.length >= 4000) {
+34 -2
View File
@@ -1,7 +1,7 @@
const logger = require('../../services/logger');
const { embedOptions } = require('../../config');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidation');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
const osu = require('node-os-utils');
const { version, dependencies } = require('../../../package.json');
@@ -28,6 +28,28 @@ module.exports = {
const discordPlayerVersion = dependencies['discord-player'];
const discordApiLatency = client.ws.ping;
let activeVoiceConnections = 0;
let guildCount = 0;
await client.shard
.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
return guild.id;
/*
const queue = useQueue(guild.id);
let shardVoiceConnections = 0;
if (queue) {
activeVoiceConnections++;
}
return shardVoiceConnections;
*/
});
})
.then((results) => {
// array of arrays with guild ids for each shard
logger.debug(results, 'Shard guild ids');
});
/*
client.guilds.cache.forEach((guild) => {
const queue = useQueue(guild.id);
@@ -35,6 +57,16 @@ module.exports = {
activeVoiceConnections++;
}
});
*/
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.`);
});
return await interaction.editReply({
embeds: [
@@ -54,7 +86,7 @@ module.exports = {
`Discord API latency: \`${discordApiLatency} ms\`\n` +
`Interaction latency: \`${interactionLatency} ms\`\n` +
`Active voice connections: \`${activeVoiceConnections}\`\n` +
`Joined guilds: \`${client.guilds.cache.size}\``
`Joined guilds: \`${guildCount}\``
)
.setColor(embedOptions.colors.info)
]
+10
View File
@@ -9,6 +9,16 @@ module.exports.botOptions = {
serverInviteUrl: 'Unknown'
};
// Sharding options for the bot.
// See https://old.discordjs.dev/#/docs/discord.js/main/typedef/ShardingManagerOptions for valid options.
// Do not change if you don't know what you are doing.
module.exports.shardingOptions = {
totalShards: 'auto',
shardList: 'auto',
mode: 'process',
respawn: true
};
// Logging options for the bot, can set logging level to file and console separately.
module.exports.loggerOptions = {
minimumLogLevel: 'debug',
+14 -11
View File
@@ -7,20 +7,23 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client) => {
logger.warn(`${client.user.tag} lost connection to Discord APIs. Disconnected.`);
logger.warn(`[Shard ${client.shard.ids[0]}] ${client.user.tag} lost connection to Discord APIs. Disconnected.`);
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
await client.channels.cache.get(systemOptions.systemMessageChannelId).send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.warning} **${client.user.tag}** is **\`disconnected\`**!` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.warning)
]
});
const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.warning} **${client.user.tag}** is **\`disconnected\`**!` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.warning)
]
});
}
}
}
};
+1 -1
View File
@@ -6,6 +6,6 @@ module.exports = {
isDebug: false,
once: false,
execute: async (guild) => {
logger.info(`Added to guild '${guild.name}' with ${guild.memberCount} members.`);
logger.info(`[Shard ${guild.shardId}] Added to guild '${guild.name}' with ${guild.memberCount} members.`);
}
};
+3 -1
View File
@@ -6,6 +6,8 @@ module.exports = {
isDebug: false,
once: false,
execute: async (guild) => {
logger.info(`Removed from guild '${guild.name}' with ${guild.memberCount} members.`);
logger.info(
`[Shard ${guild.shardId}] Removed from guild '${guild.name}' with ${guild.memberCount} members.`
);
}
};
+16 -9
View File
@@ -1,28 +1,35 @@
const logger = require('../../services/logger');
const { embedOptions, systemOptions, presenceStatusOptions } = require('../../config');
const { Events, EmbedBuilder } = require('discord.js');
const { postBotStats } = require('../../utils/other/postBotStats.js');
const { Events, EmbedBuilder } = require('discord.js');
module.exports = {
name: Events.ClientReady,
isDebug: false,
once: true,
once: false,
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);
// Post bot stats to bot lists in production
process.env.NODE_ENV === 'production' ? postBotStats(client) : null;
const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
// send message to system message channel for event
if (systemOptions.systemMessageChannelId) {
await client.channels.cache.get(systemOptions.systemMessageChannelId).send({
// Check if the channel exists in curent shard and send a message
if (channel) {
logger.info(
`[Shard ${client.shard.ids[0]}] ALL SHARDS READY, sending system message to channel id ${channel.id}.`
);
channel.send({
embeds: [
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)
]
});
}
process.env.NODE_ENV === 'production' ? await postBotStats(client) : null;
}
};
+16 -11
View File
@@ -7,20 +7,25 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client) => {
logger.warn(`${client.user.tag} is reconnecting to Discord APIs.`);
logger.warn(`[Shard ${client.shard.ids[0]}] ${client.user.tag} is reconnecting to Discord APIs.`);
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
await client.channels.cache.get(systemOptions.systemMessageChannelId).send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.warning} **${client.user.tag}** is **\`reconnecting\`**!` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.warning)
]
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.warning} **${client.user.tag}** is **\`reconnecting\`**!` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.warning)
]
});
}
}
}
}
};
+7 -5
View File
@@ -12,7 +12,9 @@ module.exports = {
const command = client.commands.get(interaction.commandName);
if (!command) {
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
logger.warn(
`[Shard ${interaction.guild.shardId}] Interaction created but command '${interaction.commandName}' was not found.`
);
return;
}
@@ -32,13 +34,13 @@ module.exports = {
executionTime > 55000
) {
logger.info(
`(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' executed in ${executionTime} ms.`
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Command '${interaction}' executed in ${executionTime} ms.`
);
return;
}
logger.warn(
`(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' took ${executionTime} ms to execute.`
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Command '${interaction}' took ${executionTime} ms to execute.`
);
return await interaction.followUp({
@@ -54,13 +56,13 @@ module.exports = {
});
} else {
logger.info(
`(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' executed in ${executionTime} ms.`
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Command '${interaction}' executed in ${executionTime} ms.`
);
}
} catch (error) {
logger.error(
error,
`(${interaction.guild.memberCount}) ${interaction.guild.name}> Command '${interaction}' failed to execute.`
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Command '${interaction}' failed to execute.`
);
await interaction.followUp({
+17 -11
View File
@@ -8,7 +8,10 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, error) => {
logger.error(error, 'player.events.on(\'error\'): Player queue encountered error event');
logger.error(
error,
`[Shard ${queue.metadata.client.shard.ids[0]}] player.events.on('error'): Player queue encountered error event`
);
await queue.metadata.channel.send({
embeds: [
@@ -21,16 +24,19 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId).send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('error')**\n${error.message}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
]
});
const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId);
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('error')**\n${error.message}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
]
});
}
}
process.env.NODE_ENV === 'development' ? logger.trace(queue, 'Queue object') : null;
+17 -11
View File
@@ -8,7 +8,10 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, error) => {
logger.error(error, 'player.events.on(\'playerError\'): Player error while streaming track');
logger.error(
error,
`[Shard ${queue.metadata.client.shard.ids[0]}] player.events.on('playerError'): Player error while streaming track`
);
await queue.metadata.channel.send({
embeds: [
@@ -21,16 +24,19 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId).send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('playerError')**\n${error.message}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
]
});
const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId);
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('playerError')**\n${error.message}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
]
});
}
}
process.env.NODE_ENV === 'development' ? logger.trace(queue, 'Queue object') : null;
+16 -11
View File
@@ -8,7 +8,9 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, track) => {
logger.error(`player.events.on('playerSkip'): Failed to play '${track.url}'.`);
logger.error(
`[Shard ${queue.metadata.client.shard.ids[0]}] player.events.on('playerSkip'): Failed to play '${track.url}'.`
);
await queue.metadata.channel.send({
embeds: [
@@ -21,16 +23,19 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId).send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('playerSkip')**\n${track.url}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
]
});
const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId);
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('playerSkip')**\n${track.url}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
]
});
}
}
process.env.NODE_ENV === 'development' ? logger.trace(queue, 'Queue object') : null;
+3 -1
View File
@@ -5,7 +5,9 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, track) => {
logger.debug(`playerStart event: Started playing '${track.raw.source}'.`);
logger.debug(
`[Shard ${queue.metadata.client.shard.ids[0]}] playerStart event: Started playing '${track.raw.source}'.`
);
process.env.NODE_ENV === 'development' ? logger.trace(queue) : null;
}
};
+20 -14
View File
@@ -1,18 +1,24 @@
require('dotenv').config();
const { shardingOptions } = require('./config');
const logger = require('./services/logger');
const { registerEventListeners } = require('./utils/registerEventListeners.js');
const { registerClientCommands } = require('./utils/registerClientCommands.js');
const { createClient } = require('./utils/factory/createClient.js');
const { createPlayer } = require('./utils/factory/createPlayer.js');
const { ShardingManager, ShardEvents } = require('discord.js');
(async () => {
const client = await createClient();
const player = await createPlayer(client);
registerEventListeners(client, player);
registerClientCommands(client);
client.login(process.env.DISCORD_BOT_TOKEN);
})().catch((error) => {
logger.error(error);
const manager = new ShardingManager('./src/bot.js', {
token: process.env.DISCORD_BOT_TOKEN,
...shardingOptions
});
const readyShards = new Set();
manager.on('shardCreate', (shard) => {
logger.debug(`[Shard ${shard.id}] Launched shard with id ${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();
+1
View File
@@ -30,6 +30,7 @@ exports.createClient = async () => {
}
}
});
return client;
} catch (error) {
logger.error('Failed to create Discord.js client', error);
+3 -3
View File
@@ -4,7 +4,7 @@ const { stream } = require('yt-stream');
exports.createPlayer = async (client) => {
try {
logger.info('Creating discord-player player...');
logger.info(`[Shard ${client.shard.ids[0]}] Creating discord-player player...`);
const player = new Player(client, {
useLegacyFFmpeg: false,
@@ -35,11 +35,11 @@ exports.createPlayer = async (client) => {
});
await player.extractors.loadDefault();
logger.debug(`discord-player loaded dependencies:\n${player.scanDeps()}`);
logger.debug(`[Shard ${client.shard.ids[0]}] discord-player loaded dependencies:\n${player.scanDeps()}`);
return player;
} catch (error) {
logger.error('Failed to create discord-player player', error);
logger.error(`[Shard ${client.shard.ids[0]}] Failed to create discord-player player`, error);
throw error;
}
};
+22 -4
View File
@@ -1,9 +1,27 @@
const logger = require('../../services/logger');
const https = require('node:https');
exports.postBotStats = (client) => {
exports.postBotStats = async (client) => {
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 */
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) => {
let options = {
protocol: 'https:',
@@ -75,6 +93,6 @@ exports.postBotStats = (client) => {
request.end();
});
} 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.`);
}
};
+5 -3
View File
@@ -4,7 +4,7 @@ const path = require('node:path');
const { Collection } = require('discord.js');
exports.registerClientCommands = (client) => {
logger.debug('Registering client commands...');
logger.debug(`[Shard ${client.shard.ids[0]}] Registering client commands...`);
client.commands = new Collection();
const commandFolders = fs.readdirSync(path.resolve('./src/commands'));
@@ -15,11 +15,13 @@ exports.registerClientCommands = (client) => {
for (const file of commandFiles) {
try {
logger.debug(`Registering command ${folder}/${file}...`);
logger.debug(`[Shard ${client.shard.ids[0]}] Registering command ${folder}/${file}...`);
const command = require(`../commands/${folder}/${file}`);
client.commands.set(command.data.name, command);
} catch (error) {
logger.error(`Error registering command ${folder}/${file}: ${error.message}`);
logger.error(
`[Shard ${client.shard.ids[0]}] Error registering command ${folder}/${file}: ${error.message}`
);
throw error;
}
}
+10 -6
View File
@@ -3,7 +3,7 @@ const fs = require('node:fs');
const path = require('node:path');
exports.registerEventListeners = (client, player) => {
logger.debug('Registering event listeners...');
logger.debug(`[Shard ${client.shard.ids[0]}] Registering event listeners...`);
const eventFolders = fs.readdirSync(path.resolve('./src/events'));
for (const folder of eventFolders) {
@@ -15,7 +15,7 @@ exports.registerEventListeners = (client, player) => {
const event = require(`../events/${folder}/${file}`);
switch (folder) {
case 'client':
logger.debug(`Registering client event listener ${event.name}...`);
logger.debug(`[Shard ${client.shard.ids[0]}] Registering client event listener ${event.name}...`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
@@ -26,17 +26,19 @@ exports.registerEventListeners = (client, player) => {
break;
case 'interactions':
logger.debug(`Registering interactions event listener ${event.name}...`);
logger.debug(
`[Shard ${client.shard.ids[0]}] Registering interactions event listener ${event.name}...`
);
client.on(event.name, (...args) => event.execute(...args, { client }));
break;
case 'process':
logger.debug(`Registering process event listener ${event.name}...`);
logger.debug(`[Shard ${client.shard.ids[0]}] Registering process event listener ${event.name}...`);
process.on(event.name, (...args) => event.execute(...args));
break;
case 'player':
logger.debug(`Registering player event listener ${event.name}...`);
logger.debug(`[Shard ${client.shard.ids[0]}] Registering player event listener ${event.name}...`);
if (
!event.isDebug ||
process.env.NODE_ENV === 'development' ||
@@ -52,7 +54,9 @@ exports.registerEventListeners = (client, player) => {
break;
default:
logger.error(`Unknown event folder '${folder}' while trying to register events.`);
logger.error(
`[Shard ${client.shard.ids[0]}] Unknown event folder '${folder}' while trying to register events.`
);
}
}
}