mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-02 14:38:49 +00:00
Add registering of all interactions to client
This commit is contained in:
1 parent
ddeaf82c11
commit
475c5c58d6
13 files changed
+217
-97
No files matched your search
+5
-5
@@ -7,7 +7,7 @@ import loggerModule from './services/logger';
|
||||
import { ExtendedClient } from './types/clientTypes';
|
||||
import { createClient } from './utils/factory/createClient';
|
||||
import { createPlayer } from './utils/factory/createPlayer';
|
||||
import { registerClientCommands } from './utils/registerClientCommands';
|
||||
import { registerClientInteractions } from './utils/registerClientInteractions';
|
||||
import { registerEventListeners } from './utils/registerEventListeners';
|
||||
import { Player } from 'discord-player';
|
||||
import { Logger } from 'pino';
|
||||
@@ -25,14 +25,14 @@ const logger: Logger = loggerModule.child({
|
||||
try {
|
||||
const client: ExtendedClient = await createClient({ executionId });
|
||||
const player: Player = await createPlayer({ client, executionId });
|
||||
|
||||
|
||||
client.on('allShardsReady', async () => {
|
||||
client.registerClientCommands = registerClientCommands;
|
||||
client.registerClientInteractions = registerClientInteractions;
|
||||
await registerEventListeners({ client, player, executionId });
|
||||
await registerClientCommands({ client, executionId });
|
||||
await registerClientInteractions({ client, executionId });
|
||||
client.emit('ready', client as Client);
|
||||
});
|
||||
|
||||
|
||||
client.login(process.env.DISCORD_BOT_TOKEN);
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
|
||||
@@ -47,15 +47,30 @@ module.exports = {
|
||||
logger.debug('Started handling interaction.');
|
||||
switch (interaction.type) {
|
||||
case InteractionType.ApplicationCommand:
|
||||
await handleCommand(interaction as ChatInputCommandInteraction, client, executionId);
|
||||
await handleCommand(
|
||||
interaction as ChatInputCommandInteraction,
|
||||
client,
|
||||
executionId,
|
||||
interactionIdentifier
|
||||
);
|
||||
break;
|
||||
|
||||
case InteractionType.ApplicationCommandAutocomplete:
|
||||
await handleAutocomplete(interaction as AutocompleteInteraction, executionId);
|
||||
await handleAutocomplete(
|
||||
interaction as AutocompleteInteraction,
|
||||
client,
|
||||
executionId,
|
||||
interactionIdentifier
|
||||
);
|
||||
break;
|
||||
|
||||
case InteractionType.MessageComponent:
|
||||
await handleComponent(interaction as MessageComponentInteraction, executionId);
|
||||
await handleComponent(
|
||||
interaction as MessageComponentInteraction,
|
||||
client,
|
||||
executionId,
|
||||
interactionIdentifier
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -67,7 +82,7 @@ module.exports = {
|
||||
}
|
||||
} catch (error) {
|
||||
logger.debug('Error while handling received interaction.');
|
||||
await handleError(interaction, error as CustomError, interactionIdentifier, executionId);
|
||||
await handleError(interaction, error as CustomError, executionId, interactionIdentifier);
|
||||
}
|
||||
|
||||
const outputTime: number = new Date().getTime();
|
||||
|
||||
@@ -1,20 +1,31 @@
|
||||
import { AutocompleteInteraction } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { ExtendedClient } from '../types/clientTypes';
|
||||
import { BaseAutocompleteInteraction } from '../types/interactionTypes';
|
||||
|
||||
export const handleAutocomplete = async (interaction: AutocompleteInteraction, executionId: string) => {
|
||||
export const handleAutocomplete = async (
|
||||
interaction: AutocompleteInteraction,
|
||||
client: ExtendedClient,
|
||||
executionId: string,
|
||||
interactionIdentifier: string
|
||||
) => {
|
||||
// TODO: Define TS Type for handlers, and require logger constant?
|
||||
const logger: Logger = loggerModule.child({
|
||||
source: 'interactionCutocompleteHandler.ts',
|
||||
source: 'interactionAutocompleteHandler.ts',
|
||||
module: 'handler',
|
||||
name: 'interactionAutocompleteHandler',
|
||||
executionId: executionId
|
||||
});
|
||||
|
||||
// TODO: Create TS Type for autocompleteModule
|
||||
const autocompleteModule = await import(`../interactions/autocomplete/${interaction.commandName}.js`);
|
||||
const { default: autocomplete } = autocompleteModule;
|
||||
const autocomplete: BaseAutocompleteInteraction = client.autocompleteInteractions!.get(
|
||||
interactionIdentifier
|
||||
) as BaseAutocompleteInteraction;
|
||||
if (!autocomplete) {
|
||||
logger.warn(`Interaction created but autocomplete '${interactionIdentifier}' was not found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug('Executing autocomplete interaction.');
|
||||
logger.debug(`Executing autocomplete interaction '${interactionIdentifier}'.`);
|
||||
await autocomplete.execute({ interaction, executionId });
|
||||
};
|
||||
@@ -2,13 +2,14 @@ import { ChatInputCommandInteraction } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { ExtendedClient } from '../types/clientTypes';
|
||||
import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator';
|
||||
import { BaseSlashCommandInteraction } from '../types/interactionTypes';
|
||||
import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator';
|
||||
|
||||
export const handleCommand = async (
|
||||
interaction: ChatInputCommandInteraction,
|
||||
client: ExtendedClient,
|
||||
executionId: string
|
||||
executionId: string,
|
||||
interactionIdentifier: string
|
||||
) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
source: 'interactionCommandHandler.ts',
|
||||
@@ -20,19 +21,18 @@ export const handleCommand = async (
|
||||
await interaction.deferReply();
|
||||
logger.debug('Interaction deferred.');
|
||||
|
||||
// TODO: Update TS Type for command
|
||||
const command: BaseSlashCommandInteraction = client.commands!.get(
|
||||
interaction.commandName
|
||||
) as BaseSlashCommandInteraction;
|
||||
if (!command) {
|
||||
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (await cannotSendMessageInChannel({ interaction, executionId })) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug('Executing command interaction.');
|
||||
await command.execute({ interaction, client, executionId });
|
||||
const slashCommand: BaseSlashCommandInteraction = client.slashCommandInteractions!.get(
|
||||
interactionIdentifier
|
||||
) as BaseSlashCommandInteraction;
|
||||
if (!slashCommand) {
|
||||
logger.warn(`Interaction created but slash command '${interactionIdentifier}' was not found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug(`Executing slash command interaction '${interactionIdentifier}'.`);
|
||||
await slashCommand.execute({ interaction, client, executionId });
|
||||
};
|
||||
@@ -1,9 +1,16 @@
|
||||
import { MessageComponentInteraction } from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { ExtendedClient } from '../types/clientTypes';
|
||||
import { BaseComponentInteraction } from '../types/interactionTypes';
|
||||
import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator';
|
||||
|
||||
export const handleComponent = async (interaction: MessageComponentInteraction, executionId: string) => {
|
||||
export const handleComponent = async (
|
||||
interaction: MessageComponentInteraction,
|
||||
client: ExtendedClient,
|
||||
executionId: string,
|
||||
interactionIdentifier: string
|
||||
) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
source: 'interactionComponentHandler.js',
|
||||
module: 'handler',
|
||||
@@ -14,19 +21,23 @@ export const handleComponent = async (interaction: MessageComponentInteraction,
|
||||
await interaction.deferReply();
|
||||
logger.debug('Interaction deferred.');
|
||||
|
||||
const componentId: string = interaction.customId.split('_')[0];
|
||||
const referenceId: string = interaction.customId.split('_')[1];
|
||||
const componentId: string = interactionIdentifier.split('_')[0];
|
||||
const referenceId: string = interactionIdentifier.split('_')[1];
|
||||
|
||||
logger.debug(`Parsed componentId: ${componentId}`);
|
||||
logger.debug(`Parsed componentId '${componentId}' from identifier '${interactionIdentifier}'.`);
|
||||
|
||||
if (await cannotSendMessageInChannel({ interaction, executionId })) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: Create TS Type for component
|
||||
const componentModule = await import(`../interactions/components/${componentId}.js`);
|
||||
const { default: component } = componentModule;
|
||||
const component: BaseComponentInteraction = client.componentInteractions!.get(
|
||||
componentId
|
||||
) as BaseComponentInteraction;
|
||||
if (!component) {
|
||||
logger.warn(`Interaction created but component '${componentId}' was not found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.debug('Executing component interaction.');
|
||||
logger.debug(`Executing component interaction '${componentId}'.`);
|
||||
await component.execute({ interaction, referenceId, executionId });
|
||||
};
|
||||
@@ -1,5 +1,11 @@
|
||||
import config from 'config';
|
||||
import { ChatInputCommandInteraction, EmbedBuilder, Interaction, InteractionReplyOptions, MessageComponentInteraction } from 'discord.js';
|
||||
import {
|
||||
ChatInputCommandInteraction,
|
||||
EmbedBuilder,
|
||||
Interaction,
|
||||
InteractionReplyOptions,
|
||||
MessageComponentInteraction
|
||||
} from 'discord.js';
|
||||
import { Logger } from 'pino';
|
||||
import loggerModule from '../services/logger';
|
||||
import { BotOptions, EmbedOptions } from '../types/configTypes';
|
||||
@@ -12,8 +18,8 @@ const botOptions: BotOptions = config.get('botOptions');
|
||||
export const handleError = async (
|
||||
interaction: Interaction,
|
||||
error: CustomError,
|
||||
interactionIdentifier: string,
|
||||
executionId: string
|
||||
executionId: string,
|
||||
interactionIdentifier: string
|
||||
) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
source: 'interactionErrorHandler.ts',
|
||||
|
||||
@@ -18,7 +18,7 @@ class HelpCommand extends BaseSlashCommandInteraction {
|
||||
const logger = this.getLogger(this.name, executionId, interaction);
|
||||
|
||||
const commandList = client!
|
||||
.commands!.filter((command: BaseSlashCommandInteraction) => {
|
||||
.slashCommandInteractions!.filter((command: BaseSlashCommandInteraction) => {
|
||||
// don't include system commands
|
||||
if (command.isSystemCommand) {
|
||||
return false;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validat
|
||||
class SkipCommand extends BaseSlashCommandInteraction {
|
||||
constructor() {
|
||||
const data = new SlashCommandBuilder()
|
||||
.setName('test')
|
||||
.setName('skip')
|
||||
.setDescription('Skip track to next or specified position in queue.')
|
||||
.addNumberOption((option) =>
|
||||
option.setName('tracknumber').setDescription('The position in queue to skip to.').setMinValue(1)
|
||||
|
||||
@@ -29,7 +29,7 @@ class ReloadCommand extends BaseSlashCommandInteraction {
|
||||
await client!
|
||||
.shard!.broadcastEval(
|
||||
async (shardClient: ExtendedClient, { executionId }) => {
|
||||
shardClient.registerClientCommands!({ client: shardClient, executionId });
|
||||
shardClient.registerClientInteractions!({ client: shardClient, executionId });
|
||||
},
|
||||
{ context: { executionId: executionId } }
|
||||
)
|
||||
@@ -53,7 +53,7 @@ class ReloadCommand extends BaseSlashCommandInteraction {
|
||||
});
|
||||
}
|
||||
|
||||
const commands: string[] | undefined = client!.commands?.map((command: BaseSlashCommandInteraction) => {
|
||||
const commands: string[] | undefined = client!.slashCommandInteractions?.map((command: BaseSlashCommandInteraction) => {
|
||||
let params: string = '';
|
||||
|
||||
if (command.data.options && command.data.options.length > 1) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Client, Collection } from 'discord.js';
|
||||
import { BaseSlashCommandInteraction } from './interactionTypes';
|
||||
import { BaseAutocompleteInteraction, BaseComponentInteraction, BaseSlashCommandInteraction } from './interactionTypes';
|
||||
|
||||
type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void;
|
||||
type RegisterClientInteractionsFunction = (params: { client: Client; executionId: string }) => void;
|
||||
|
||||
export interface ExtendedClient extends Client {
|
||||
registerClientCommands?: RegisterClientCommandsFunction;
|
||||
commands?: Collection<string, BaseSlashCommandInteraction>;
|
||||
registerClientInteractions?: RegisterClientInteractionsFunction;
|
||||
slashCommandInteractions?: Collection<string, BaseSlashCommandInteraction>;
|
||||
autocompleteInteractions?: Collection<string, BaseAutocompleteInteraction>;
|
||||
componentInteractions?: Collection<string, BaseComponentInteraction>;
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export interface RegisterEventListenersParams {
|
||||
executionId: string;
|
||||
}
|
||||
|
||||
export interface RegisterClientCommandsParams {
|
||||
export interface RegisterClientInteractionsParams {
|
||||
client: ExtendedClient;
|
||||
executionId: string;
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { Collection } from 'discord.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import loggerModule from '../services/logger';
|
||||
import { RegisterClientCommandsParams } from '../types/utilTypes';
|
||||
import { Logger } from 'pino';
|
||||
|
||||
export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
source: 'registerClientCommands.js',
|
||||
module: 'register',
|
||||
name: 'registerClientCommands',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
logger.debug('Registering client commands...');
|
||||
client.commands = new Collection();
|
||||
|
||||
const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands'));
|
||||
for (const folder of commandFolders) {
|
||||
logger.trace(`Registering client commands for folder '${folder}'...`);
|
||||
|
||||
const commandFiles: string[] = fs
|
||||
.readdirSync(path.resolve(`./dist/interactions/commands/${folder}`))
|
||||
.filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of commandFiles) {
|
||||
try {
|
||||
// delete command from require cache
|
||||
delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)];
|
||||
|
||||
// load command and register it to client.commands collection
|
||||
const { default: command } = await import(`../interactions/commands/${folder}/${file}`);
|
||||
client.commands.delete(command.data.name);
|
||||
client.commands.set(command.data.name, command);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(`Error registering command ${folder}/${file}: ${error.message}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client commands complete.');
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
import { Collection } from 'discord.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import loggerModule from '../services/logger';
|
||||
import { RegisterClientInteractionsParams } from '../types/utilTypes';
|
||||
import { Logger } from 'pino';
|
||||
import { ExtendedClient } from '../types/clientTypes';
|
||||
|
||||
export const registerClientInteractions = async ({ client, executionId }: RegisterClientInteractionsParams) => {
|
||||
const logger: Logger = loggerModule.child({
|
||||
source: 'registerClientInteractions.js',
|
||||
module: 'register',
|
||||
name: 'registerClientInteractions',
|
||||
executionId: executionId,
|
||||
shardId: client.shard?.ids[0]
|
||||
});
|
||||
|
||||
await registerSlashCommandInteractions(logger, client);
|
||||
await registerAutocompleteInteractions(logger, client);
|
||||
await registerComponentInteractions(logger, client);
|
||||
|
||||
logger.debug('Registering all client interactions complete.');
|
||||
};
|
||||
|
||||
async function registerSlashCommandInteractions(logger: Logger, client: ExtendedClient) {
|
||||
logger.debug('Registering client slash command interactions...');
|
||||
client.slashCommandInteractions = new Collection();
|
||||
|
||||
const baseFolderPath = './dist/interactions/commands';
|
||||
const slashCommandInteractionFolders: string[] = fs.readdirSync(path.resolve(baseFolderPath));
|
||||
|
||||
for (const categoryFolder of slashCommandInteractionFolders) {
|
||||
logger.trace(`Registering client commands for folder '${categoryFolder}'...`);
|
||||
|
||||
const files: string[] = fs
|
||||
.readdirSync(path.resolve(`${baseFolderPath}/${categoryFolder}`))
|
||||
.filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filePath = path.resolve(`${baseFolderPath}/${categoryFolder}/${file}`);
|
||||
|
||||
// delete require cache for file
|
||||
delete require.cache[filePath];
|
||||
|
||||
// import and register to client collection
|
||||
const { default: slashCommandInteraction } = await import(filePath);
|
||||
client.slashCommandInteractions.delete(slashCommandInteraction.name);
|
||||
client.slashCommandInteractions.set(slashCommandInteraction.name, slashCommandInteraction);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(
|
||||
`Error registering slash command interaction '${categoryFolder}/${file}': ${error.message}`
|
||||
);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client slash command interactions complete.');
|
||||
}
|
||||
|
||||
async function registerAutocompleteInteractions(logger: Logger, client: ExtendedClient) {
|
||||
logger.debug('Registering client autocomplete interactions...');
|
||||
client.autocompleteInteractions = new Collection();
|
||||
|
||||
const baseFolderPath = './dist/interactions/autocomplete';
|
||||
const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filePath = path.resolve(`${baseFolderPath}/${file}`);
|
||||
|
||||
// delete require cache for file
|
||||
delete require.cache[filePath];
|
||||
|
||||
// import and register to client collection
|
||||
const { default: autocompleteInteraction } = await import(filePath);
|
||||
client.autocompleteInteractions.delete(autocompleteInteraction.name);
|
||||
client.autocompleteInteractions.set(autocompleteInteraction.name, autocompleteInteraction);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(`Error registering autocomplete interaction '${file}': ${error.message}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client autocomplete interactions complete.');
|
||||
}
|
||||
|
||||
async function registerComponentInteractions(logger: Logger, client: ExtendedClient) {
|
||||
logger.debug('Registering client component interactions...');
|
||||
client.componentInteractions = new Collection();
|
||||
|
||||
const baseFolderPath = './dist/interactions/components';
|
||||
const files: string[] = fs.readdirSync(path.resolve(`${baseFolderPath}`)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filePath = path.resolve(`${baseFolderPath}/${file}`);
|
||||
|
||||
// delete require cache for file
|
||||
delete require.cache[filePath];
|
||||
|
||||
// import and register to client collection
|
||||
const { default: componentInteraction } = await import(filePath);
|
||||
client.componentInteractions.delete(componentInteraction.name);
|
||||
client.componentInteractions.set(componentInteraction.name, componentInteraction);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(`Error registering component interaction '${file}': ${error.message}`);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.trace('Registering client component interactions complete.');
|
||||
}
|
||||
Reference in new issue
Block a user