mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-03 14:38:49 +00:00
feat!: Change interaction structure and handling of component responses
This commit is contained in:
1 parent
905df36ef8
commit
9b02b21283
24 files changed
+232
-239
No files matched your search
@@ -0,0 +1,88 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
|
||||
|
||||
import loggerModule from '../../../services/logger';
|
||||
import { CommandParams } from '../../../types/commandTypes';
|
||||
import { EmbedOptions } from '../../../types/configTypes';
|
||||
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
module.exports = {
|
||||
isSystemCommand: true,
|
||||
isNew: false,
|
||||
isBeta: false,
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('guilds')
|
||||
.setDescription('Show list of guilds where bot is added.')
|
||||
.setDMPermission(false)
|
||||
.setNSFW(false),
|
||||
execute: async ({ interaction, client, executionId }: CommandParams) => {
|
||||
const logger = loggerModule.child({
|
||||
source: 'guilds.js',
|
||||
module: 'slashCommand',
|
||||
name: '/guilds',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
|
||||
if (await notValidGuildId({ interaction, executionId })) {
|
||||
return;
|
||||
}
|
||||
|
||||
let shardGuilds: Guild[] = [];
|
||||
let totalGuildCount = 0;
|
||||
|
||||
if (!client || !client.shard) {
|
||||
logger.error('Client is undefined or does not have shard property.');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug('Fetching guilds from all shards.');
|
||||
await client.shard
|
||||
.broadcastEval((c) => {
|
||||
return c.guilds.cache.map((guild) => {
|
||||
return guild;
|
||||
});
|
||||
})
|
||||
.then((guilds) => {
|
||||
shardGuilds = guilds.flat(1) as Guild[];
|
||||
});
|
||||
|
||||
totalGuildCount = shardGuilds.length;
|
||||
|
||||
logger.debug(`Successfully fetched ${totalGuildCount} guilds.`);
|
||||
|
||||
const guildListFormatted = shardGuilds
|
||||
.map((guild) => {
|
||||
return {
|
||||
name: guild.name,
|
||||
memberCount: guild.memberCount
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.memberCount - a.memberCount)
|
||||
.slice(0, 25)
|
||||
.map((guild, index) => `${index + 1}. \`${guild.name} (#${guild.memberCount})\``)
|
||||
.join('\n');
|
||||
|
||||
const totalMemberCount = shardGuilds.reduce((a, b) => a + b.memberCount, 0);
|
||||
|
||||
let embedDescription =
|
||||
`**${embedOptions.icons.bot} ${
|
||||
totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds'
|
||||
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
|
||||
`\n\n**Total members:** **\`${totalMemberCount}\`**`;
|
||||
|
||||
logger.debug('Transformed guild into into embed description.');
|
||||
|
||||
if (embedDescription.length >= 4000) {
|
||||
logger.debug('Embed description is too long, truncating.');
|
||||
embedDescription = `${embedDescription.slice(0, 3996)}...`;
|
||||
}
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)]
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
|
||||
import loggerModule from '../../../services/logger';
|
||||
import { ExtendedClient } from '../../../types/clientTypes';
|
||||
import { CommandParams } from '../../../types/commandTypes';
|
||||
import { EmbedOptions } from '../../../types/configTypes';
|
||||
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
module.exports = {
|
||||
isSystemCommand: true,
|
||||
isNew: false,
|
||||
isBeta: false,
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('reload')
|
||||
.setDescription('Reload the bot commands.')
|
||||
.setDMPermission(false)
|
||||
.setNSFW(false),
|
||||
execute: async ({ interaction, client, executionId }: CommandParams) => {
|
||||
const logger = loggerModule.child({
|
||||
source: 'reload.js',
|
||||
module: 'slashCommand',
|
||||
name: '/reload',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
|
||||
if (await notValidGuildId({ interaction, executionId })) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!client || !client.shard) {
|
||||
logger.error('Client is undefined or does not have shard property.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug('Reloading commands across all shards.');
|
||||
await client.shard
|
||||
.broadcastEval(
|
||||
async (shardClient: ExtendedClient, { executionId }) => {
|
||||
if (!shardClient.registerClientCommands) {
|
||||
return;
|
||||
}
|
||||
|
||||
shardClient.registerClientCommands({ client: shardClient, executionId });
|
||||
},
|
||||
{ context: { executionId: executionId } }
|
||||
)
|
||||
.then(() => {
|
||||
logger.debug('Successfully reloaded commands across all shards.');
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to reload commands across shards.');
|
||||
|
||||
logger.debug('Responding with error embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
|
||||
.setDescription(
|
||||
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.`
|
||||
)
|
||||
.setColor(embedOptions.colors.error)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
const commands = client.commands?.map((command) => {
|
||||
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
|
||||
return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`;
|
||||
});
|
||||
|
||||
const embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n');
|
||||
|
||||
logger.debug('Responding with success embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.success)]
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,200 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
|
||||
|
||||
import loggerModule from '../../../services/logger';
|
||||
import { ExtendedClient } from '../../../types/clientTypes';
|
||||
import { CommandParams, ShardInfo } from '../../../types/commandTypes';
|
||||
import { EmbedOptions } from '../../../types/configTypes';
|
||||
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
module.exports = {
|
||||
isSystemCommand: true,
|
||||
isNew: false,
|
||||
isBeta: false,
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('shards')
|
||||
.setDescription('Show information about the running shards.')
|
||||
.setDMPermission(false)
|
||||
.setNSFW(false)
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('sort')
|
||||
.setDescription('If specified, what to sort the shards by.')
|
||||
.setRequired(false)
|
||||
.addChoices(
|
||||
{ name: 'None (Shard ID)', value: 'none' },
|
||||
{ name: 'Memory usage', value: 'memory' },
|
||||
{ name: 'Voice Connections', value: 'connections' },
|
||||
{ name: 'Tracks', value: 'tracks' },
|
||||
{ name: 'Listeners', value: 'listeners' },
|
||||
{ name: 'Guilds', value: 'guilds' },
|
||||
{ name: 'Members', value: 'members' }
|
||||
)
|
||||
)
|
||||
|
||||
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
|
||||
execute: async ({ interaction, client, executionId }: CommandParams) => {
|
||||
const logger = loggerModule.child({
|
||||
source: 'shards.js',
|
||||
module: 'slashCommand',
|
||||
name: '/shards',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
|
||||
if (await notValidGuildId({ interaction, executionId })) {
|
||||
return;
|
||||
}
|
||||
|
||||
let shardInfoList: ShardInfo[] = [];
|
||||
|
||||
if (!client || !client.shard) {
|
||||
logger.error('Client is undefined or does not have shard property.');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug('Fetching player statistics and client values from each shard.');
|
||||
try {
|
||||
await client.shard
|
||||
.broadcastEval((shardClient: ExtendedClient) => {
|
||||
if (!shardClient.shard) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* eslint-disable no-undef */
|
||||
const playerStats = player.generateStatistics();
|
||||
const nodeProcessMemUsageInMb = parseFloat(
|
||||
(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
|
||||
);
|
||||
|
||||
const shardInfo = {
|
||||
shardId: shardClient.shard.ids[0],
|
||||
memUsage: nodeProcessMemUsageInMb,
|
||||
guildCount: shardClient.guilds.cache.size,
|
||||
guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
|
||||
playerStatistics: {
|
||||
activeVoiceConnections: playerStats.queues.length,
|
||||
totalTracks: playerStats.queues.reduce((acc, queue) => acc + queue.tracksCount, 0),
|
||||
totalListeners: playerStats.queues.reduce((acc, queue) => acc + queue.listeners, 0)
|
||||
}
|
||||
};
|
||||
|
||||
return shardInfo;
|
||||
})
|
||||
.then((results) => {
|
||||
shardInfoList = results.filter(Boolean) as ShardInfo[];
|
||||
|
||||
switch (interaction.options.getString('sort')) {
|
||||
case 'memory':
|
||||
shardInfoList = shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
|
||||
break;
|
||||
case 'connections':
|
||||
shardInfoList = shardInfoList.sort(
|
||||
(a, b) =>
|
||||
b.playerStatistics.activeVoiceConnections -
|
||||
a.playerStatistics.activeVoiceConnections
|
||||
);
|
||||
break;
|
||||
case 'tracks':
|
||||
shardInfoList = shardInfoList.sort(
|
||||
(a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks
|
||||
);
|
||||
break;
|
||||
case 'listeners':
|
||||
shardInfoList = shardInfoList.sort(
|
||||
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
|
||||
);
|
||||
break;
|
||||
case 'guilds':
|
||||
shardInfoList = shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
|
||||
break;
|
||||
case 'members':
|
||||
shardInfoList = shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
|
||||
break;
|
||||
default:
|
||||
shardInfoList = shardInfoList.sort((a, b) => a.shardId - b.shardId);
|
||||
break;
|
||||
}
|
||||
|
||||
logger.debug('Successfully fetched player statistics and client values from shards.');
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error, 'Failed to fetch player statistics and client values from shards.');
|
||||
|
||||
logger.debug('Responding with error embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
|
||||
.setDescription(
|
||||
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.`
|
||||
)
|
||||
.setColor(embedOptions.colors.error)
|
||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
const shardCount = shardInfoList.length;
|
||||
const totalPages = Math.ceil(shardCount / 10) || 1;
|
||||
const pageIndex = (interaction.options.getNumber('page') || 1) - 1;
|
||||
|
||||
const currentPageShards = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10);
|
||||
|
||||
const evenShardIndexes = currentPageShards.filter((shard, index) => index % 2 === 0);
|
||||
const oddShardIndexes = currentPageShards.filter((shard, index) => index % 2 !== 0);
|
||||
|
||||
function shardInfoToString(shard: ShardInfo) {
|
||||
let string = '';
|
||||
string += `**Shard ${shard.shardId}** - Guilds: ${shard.guildCount.toLocaleString(
|
||||
'en-US'
|
||||
)} (${shard.guildMemberCount.toLocaleString('en-US')})\n`;
|
||||
string += `**Node.js memory:** ${shard.memUsage.toLocaleString('en-US')} MB\n`;
|
||||
string += `**┣** Connections: ${shard.playerStatistics.activeVoiceConnections.toLocaleString('en-US')}\n`;
|
||||
string += `**┣** Tracks: ${shard.playerStatistics.totalTracks.toLocaleString('en-US')}\n`;
|
||||
string += `**┗** Listeners: ${shard.playerStatistics.totalListeners.toLocaleString('en-US')}\n`;
|
||||
return string;
|
||||
}
|
||||
|
||||
const evenShardIndexesString = evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
|
||||
const oddShardIndexesString = oddShardIndexes.map(shardInfoToString).join('\n');
|
||||
|
||||
const embedFields = [];
|
||||
|
||||
if (currentPageShards.length === 1) {
|
||||
embedFields.push({
|
||||
name: ' ',
|
||||
value: currentPageShards.map(shardInfoToString).join('\n'),
|
||||
inline: false
|
||||
});
|
||||
} else {
|
||||
embedFields.push(
|
||||
{
|
||||
name: ' ',
|
||||
value: evenShardIndexesString,
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: ' ',
|
||||
value: oddShardIndexesString,
|
||||
inline: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
logger.debug('Successfully gathered and transformed shard information into embed fields.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(`**${embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`)
|
||||
.addFields(...embedFields)
|
||||
.setColor(embedOptions.colors.info)
|
||||
.setFooter({ text: `Shard id: ${client.shard.ids[0]}, page ${pageIndex + 1} of ${totalPages}` })
|
||||
]
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
import config from 'config';
|
||||
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
|
||||
import osu from 'node-os-utils';
|
||||
|
||||
// @ts-ignore
|
||||
import { dependencies, version } from '../../../../package.json';
|
||||
import loggerModule from '../../../services/logger';
|
||||
import { CommandParams } from '../../../types/commandTypes';
|
||||
import { EmbedOptions } from '../../../types/configTypes';
|
||||
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
|
||||
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
|
||||
module.exports = {
|
||||
isSystemCommand: true,
|
||||
isNew: false,
|
||||
isBeta: false,
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('systemstatus')
|
||||
.setDescription('Show the bot and system status.')
|
||||
.setDMPermission(false)
|
||||
.setNSFW(false),
|
||||
execute: async ({ interaction, client, executionId }: CommandParams) => {
|
||||
const logger = loggerModule.child({
|
||||
source: 'systemstatus.js',
|
||||
module: 'slashCommand',
|
||||
name: '/systemstatus',
|
||||
executionId: executionId,
|
||||
shardId: interaction.guild?.shardId,
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
|
||||
if (await notValidGuildId({ interaction, executionId })) {
|
||||
return;
|
||||
}
|
||||
|
||||
// from normal /status command
|
||||
const uptimeString = await getUptimeFormatted({ executionId });
|
||||
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
|
||||
const cpuUsage = await osu.cpu.usage();
|
||||
const releaseVersion = version;
|
||||
let guildCount = 0;
|
||||
let memberCount = 0;
|
||||
let activeVoiceConnections = 0;
|
||||
let totalTracks = 0;
|
||||
let totalListeners = 0;
|
||||
|
||||
// specific to /systemstatus command
|
||||
const totalMemoryInMb = Math.ceil((await osu.mem.info()).totalMemMb).toLocaleString('en-US');
|
||||
const cpuCores = await osu.cpu.count();
|
||||
const platform = await osu.os.platform();
|
||||
const discordJsVersion = dependencies['discord.js'];
|
||||
const opusVersion = dependencies['@discord-player/opus'];
|
||||
const restVersion = dependencies['@discordjs/rest'];
|
||||
const voiceVersion = dependencies['discord-voip'];
|
||||
const discordPlayerVersion = dependencies['discord-player'];
|
||||
const extractorVersion = dependencies['@discord-player/extractor'];
|
||||
const mediaplexVersion = dependencies['mediaplex'];
|
||||
const distubeYtdlVersion = dependencies['@distube/ytdl-core'];
|
||||
|
||||
logger.debug('Fetching player statistics from all shards.');
|
||||
|
||||
if (!client || !client.shard) {
|
||||
logger.error('Client is undefined or does not have shard property.');
|
||||
return;
|
||||
}
|
||||
|
||||
await client.shard
|
||||
.broadcastEval(() => {
|
||||
/* eslint-disable no-undef */
|
||||
return player.generateStatistics();
|
||||
})
|
||||
.then((results) => {
|
||||
const queueCountList: number[] = [];
|
||||
const trackCountList: number[] = [];
|
||||
const listenerCountList: number[] = [];
|
||||
results.map((result) => {
|
||||
queueCountList.push(result.queues.length);
|
||||
if (result.queues.length > 0) {
|
||||
result.queues.map((queue) => {
|
||||
trackCountList.push(queue.status.playing ? queue.tracksCount + 1 : queue.tracksCount);
|
||||
listenerCountList.push(queue.listeners);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
|
||||
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
|
||||
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
|
||||
|
||||
logger.debug('Successfully fetched player statistics from shards.');
|
||||
});
|
||||
|
||||
logger.debug('Fetching client values from all shards.');
|
||||
await client.shard
|
||||
.fetchClientValues('guilds.cache')
|
||||
.then((results) => {
|
||||
const guildCaches = results as Guild[][];
|
||||
guildCaches.map((guildCache: Guild[]) => {
|
||||
if (guildCache) {
|
||||
guildCount += guildCache.length;
|
||||
memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0);
|
||||
}
|
||||
});
|
||||
logger.debug('Successfully fetched client values from shards.');
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error(error, 'Failed to fetch client values from shards.');
|
||||
});
|
||||
|
||||
const botStatusString =
|
||||
`**${guildCount.toLocaleString('en-US')}** Joined servers\n` +
|
||||
`**${memberCount.toLocaleString('en-US')}** Total members\n` +
|
||||
`**v${releaseVersion}** Release version`;
|
||||
|
||||
const queueStatusString =
|
||||
`**${activeVoiceConnections.toLocaleString('en-US')}** Voice connections\n` +
|
||||
`**${totalTracks.toLocaleString('en-US')}** Tracks in queues\n` +
|
||||
`**${totalListeners.toLocaleString('en-US')}** Users listening`;
|
||||
|
||||
const systemStatusString =
|
||||
`**${platform}** Platform\n` +
|
||||
`**${uptimeString}** Uptime\n` +
|
||||
`**${cpuUsage}% @ ${cpuCores} cores** CPU usage\n` +
|
||||
`**${usedMemoryInMB} / ${totalMemoryInMb} MB** Memory usage`;
|
||||
|
||||
const dependenciesString =
|
||||
`**${discordJsVersion}** discord.js\n` +
|
||||
`**┗ ${restVersion}** @discordjs/rest\n` +
|
||||
`**${discordPlayerVersion}** discord-player\n` +
|
||||
`**┗ ${opusVersion}** @discord-player/opus\n` +
|
||||
`**┗ ${extractorVersion}** @discord-player/extractor\n` +
|
||||
`**${voiceVersion}** discord-voip\n` +
|
||||
`**${mediaplexVersion}** mediaplex\n` +
|
||||
`**${distubeYtdlVersion}** @distube/ytdl-core`;
|
||||
|
||||
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
|
||||
|
||||
logger.debug('Transformed system status into embed description.');
|
||||
|
||||
logger.debug('Responding with info embed.');
|
||||
return await interaction.editReply({
|
||||
embeds: [
|
||||
new EmbedBuilder()
|
||||
.setDescription(`**${embedOptions.icons.bot} Bot status**\n` + botStatusString)
|
||||
.addFields(
|
||||
{
|
||||
name: `**${embedOptions.icons.queue} Queue status**`,
|
||||
value: queueStatusString,
|
||||
inline: false
|
||||
},
|
||||
{
|
||||
name: `**${embedOptions.icons.server} System status**`,
|
||||
value: systemStatusString,
|
||||
inline: false
|
||||
},
|
||||
{
|
||||
name: `**${embedOptions.icons.discord} Discord status**`,
|
||||
value: discordStatusString,
|
||||
inline: false
|
||||
},
|
||||
{
|
||||
name: `**${embedOptions.icons.bot} Dependencies**`,
|
||||
value: dependenciesString,
|
||||
inline: false
|
||||
}
|
||||
)
|
||||
.setColor(embedOptions.colors.info)
|
||||
]
|
||||
});
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user