Add class for interactions

This commit is contained in:
Marius Begby committed 2023-08-31 17:36:16 +02:00
1 parent d0f1e940a5
commit b96a73df6f
37 files changed
+1038 -1012

No files matched your search

+22 -30
View File
@@ -1,31 +1,23 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import {
BaseSlashCommandInteraction,
BaseSlashCommandParams,
BaseSlashCommandReturnType
} from '../../../types/interactionTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
class GuildsCommand extends BaseSlashCommandInteraction {
constructor() {
const data = new SlashCommandBuilder()
.setName('guilds')
.setDescription('Show the top 25 guilds by member count.');
const isSystemCommand: boolean = true;
super(data, isSystemCommand);
}
const command: CustomSlashCommandInteraction = {
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 }) => {
const logger: Logger = loggerModule.child({
source: 'guilds.js',
module: 'slashCommand',
name: '/guilds',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
const { executionId, interaction, client } = params;
const logger = this.getLogger(this.name, executionId, interaction);
if (await notValidGuildId({ interaction, executionId })) {
return;
@@ -35,8 +27,8 @@ const command: CustomSlashCommandInteraction = {
let totalGuildCount: number = 0;
logger.debug('Fetching guilds from all shards.');
await client!.shard!
.broadcastEval((c) => {
await client!
.shard!.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
return guild;
});
@@ -64,7 +56,7 @@ const command: CustomSlashCommandInteraction = {
const totalMemberCount: number = shardGuilds.reduce((a, b) => a + b.memberCount, 0);
let embedDescription =
`**${embedOptions.icons.bot} ${
`**${this.embedOptions.icons.bot} ${
totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds'
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** **\`${totalMemberCount}\`**`;
@@ -78,9 +70,9 @@ const command: CustomSlashCommandInteraction = {
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)]
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(this.embedOptions.colors.info)]
});
}
};
}
export default command;
export default new GuildsCommand();
+36 -34
View File
@@ -1,32 +1,24 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { ApplicationCommandOption, ApplicationCommandOptionData, EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { ExtendedClient } from '../../../types/clientTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import {
BaseSlashCommandInteraction,
BaseSlashCommandParams,
BaseSlashCommandReturnType
} from '../../../types/interactionTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
class ReloadCommand extends BaseSlashCommandInteraction {
constructor() {
const data = new SlashCommandBuilder()
.setName('reload')
.setDescription('Reload all slash commands across shards.');
const isSystemCommand: boolean = true;
super(data, isSystemCommand);
}
const command: CustomSlashCommandInteraction = {
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 }) => {
const logger: Logger = loggerModule.child({
source: 'reload.js',
module: 'slashCommand',
name: '/reload',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
const { executionId, interaction, client } = params;
const logger = this.getLogger(this.name, executionId, interaction);
if (await notValidGuildId({ interaction, executionId })) {
return;
@@ -37,7 +29,7 @@ const command: CustomSlashCommandInteraction = {
await client!
.shard!.broadcastEval(
async (shardClient: ExtendedClient, { executionId }) => {
shardClient.registerClientCommands!({ client: shardClient, executionId });
shardClient.registerClientInteractions!({ client: shardClient, executionId });
},
{ context: { executionId: executionId } }
)
@@ -53,26 +45,36 @@ const command: CustomSlashCommandInteraction = {
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.`
`**${this.embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.`
)
.setColor(embedOptions.colors.error)
.setColor(this.embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
const commands: string[] | undefined = client!.commands?.map((command) => {
const params: string = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
const commands: string[] | undefined = client!.slashCommandInteractions?.map((command: BaseSlashCommandInteraction) => {
let params: string = '';
if (command.data.options && command.data.options.length > 1) {
const options = command.data.options as unknown as ApplicationCommandOptionData[];
options.map((option: ApplicationCommandOption) => {
params += `**\`${option.name}\`**` + ' ';
});
}
return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`;
});
const embedDescription: string = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n');
const embedDescription: string =
`**${this.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)]
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(this.embedOptions.colors.success)]
});
}
};
}
export default command;
export default new ReloadCommand();
+47 -50
View File
@@ -1,49 +1,43 @@
import config from 'config';
import { EmbedBuilder, EmbedField, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction, ShardInfo } from '../../../types/interactionTypes';
import {
BaseSlashCommandInteraction,
BaseSlashCommandParams,
BaseSlashCommandReturnType,
ShardInfo
} from '../../../types/interactionTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
class ShardsCommand extends BaseSlashCommandInteraction {
constructor() {
const data = new SlashCommandBuilder()
.setName('shards')
.setDescription('Show information about all connected shards.')
.addStringOption((option) =>
option
.setName('sort')
.setDescription('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 display for the shards').setMinValue(1)
);
const isSystemCommand: boolean = true;
super(data, isSystemCommand);
}
const command: CustomSlashCommandInteraction = {
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 }) => {
const logger: Logger = loggerModule.child({
source: 'shards.js',
module: 'slashCommand',
name: '/shards',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
const { executionId, interaction, client } = params;
const logger = this.getLogger(this.name, executionId, interaction);
if (await notValidGuildId({ interaction, executionId })) {
return;
@@ -122,17 +116,17 @@ const command: CustomSlashCommandInteraction = {
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.`
`**${this.embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.`
)
.setColor(embedOptions.colors.error)
.setColor(this.embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
const shardCount: number = shardInfoList.length;
const totalPages:number = Math.ceil(shardCount / 10) || 1;
const pageIndex:number = (interaction.options.getNumber('page') || 1) - 1;
const totalPages: number = Math.ceil(shardCount / 10) || 1;
const pageIndex: number = (interaction.options.getNumber('page') || 1) - 1;
const currentPageShards: ShardInfo[] = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10);
@@ -151,7 +145,8 @@ const command: CustomSlashCommandInteraction = {
return string;
}
const evenShardIndexesString: string = evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
const evenShardIndexesString: string =
evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
const oddShardIndexesString: string = oddShardIndexes.map(shardInfoToString).join('\n');
const embedFields: EmbedField[] = [];
@@ -183,13 +178,15 @@ const command: CustomSlashCommandInteraction = {
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(`**${embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`)
.setDescription(
`**${this.embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`
)
.addFields(...embedFields)
.setColor(embedOptions.colors.info)
.setColor(this.embedOptions.colors.info)
.setFooter({ text: `Shard id: ${client!.shard!.ids[0]}, page ${pageIndex + 1} of ${totalPages}` })
]
});
}
};
}
export default command;
export default new ShardsCommand();
@@ -1,35 +1,27 @@
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 { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import {
BaseSlashCommandInteraction,
BaseSlashCommandParams,
BaseSlashCommandReturnType
} from '../../../types/interactionTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
class SystemStatusCommand extends BaseSlashCommandInteraction {
constructor() {
const data = new SlashCommandBuilder()
.setName('systemstatus')
.setDescription('Show operational status of the bot with additional technical information.');
const isSystemCommand: boolean = true;
super(data, isSystemCommand);
}
const command: CustomSlashCommandInteraction = {
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 }) => {
const logger: Logger = loggerModule.child({
source: 'systemstatus.js',
module: 'slashCommand',
name: '/systemstatus',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
async execute(params: BaseSlashCommandParams): BaseSlashCommandReturnType {
const { executionId, interaction, client } = params;
const logger = this.getLogger(this.name, executionId, interaction);
if (await notValidGuildId({ interaction, executionId })) {
return;
@@ -132,33 +124,33 @@ const command: CustomSlashCommandInteraction = {
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(`**${embedOptions.icons.bot} Bot status**\n` + botStatusString)
.setDescription(`**${this.embedOptions.icons.bot} Bot status**\n` + botStatusString)
.addFields(
{
name: `**${embedOptions.icons.queue} Queue status**`,
name: `**${this.embedOptions.icons.queue} Queue status**`,
value: queueStatusString,
inline: false
},
{
name: `**${embedOptions.icons.server} System status**`,
name: `**${this.embedOptions.icons.server} System status**`,
value: systemStatusString,
inline: false
},
{
name: `**${embedOptions.icons.discord} Discord status**`,
name: `**${this.embedOptions.icons.discord} Discord status**`,
value: discordStatusString,
inline: false
},
{
name: `**${embedOptions.icons.bot} Dependencies**`,
name: `**${this.embedOptions.icons.bot} Dependencies**`,
value: dependenciesString,
inline: false
}
)
.setColor(embedOptions.colors.info)
.setColor(this.embedOptions.colors.info)
]
});
}
};
}
export default command;
export default new SystemStatusCommand();