Applications commands are registered throug rest api but not working

Hello, I am having a bit of a problem.. I a file named command.handler.ts. This file is responsible for loading commands and registration of them through the rest api. This works fine and my test command is also available in my server. However, when I execute the command nothing happens. I am not also not getting any output when I try to console.log(). The event for INTERACTION_CREATE is also being registered.. so I am not getting why it does not work
6 Replies
d.js toolkit
d.js toolkit12mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Post the full error stack trace, not just the top part! - Show your code! - Explain what exactly your issue is. - Not a discord.js issue? Check out #useful-servers. - Issue solved? Press the button!
darby
darby12mo ago
DiscordJS Version: discord.js@14.11.0 NodeJS Version: v16.14.2 command.handler.ts:
import {Client, REST, Routes, CommandInteraction, Collection} from 'discord.js';
import logger from '../utilities/logger.util';
import {Discord} from '../../types/discord';
import {readdir} from 'fs/promises';
import {join} from 'path';
import 'dotenv/config';

const COMMAND_FILES_PATH = join(__dirname, '../commands');
const COMMAND_FILES_EXTENSION = '.command.ts';

export default class CommandHandler {
private _commandFiles: string[];
private _commands: Collection<string, Discord.Command>;

private constructor(commandFiles: string[]) {
this._commandFiles = commandFiles;
this._commands = new Collection();
}

public static async create(commandFiles: string[]): Promise<CommandHandler> {
return new CommandHandler(commandFiles);
}

public async doRegisterCommands(clientInstance: Client): Promise<void> {
try {
for (const file of this._commandFiles) {
const commandModule = await import(join(COMMAND_FILES_PATH, file));
const command: Discord.Command = commandModule.default;

this._commands.set(command.data.name, command);

logger.info(`Registered slash command '${command.data.name}'`);
}

// Register slash commands through the Discord REST API
await this.registerCommandsThroughAPI(clientInstance);
} catch (error) {
logger.error(`Error while registering command! Error: ${error}`);
}
}

private async registerCommandsThroughAPI(
clientInstance: Client
): Promise<void> {
const rest = new REST({version: '10'}).setToken(process.env.BOT_TOKEN!);

try {
// Fetch the globally registered commands
const commands = this._commands.map(command => command.data.toJSON());

// Register the commands globally
await rest.put(
Routes.applicationCommands(clientInstance.application!.id),
{
body: commands,
}
);

logger.info('Registered slash commands through REST API');
} catch (error) {
logger.error(
`Error while registering slash commands through REST API! Error: ${error}`
);
}
}

public async handleInteraction(
interaction: CommandInteraction
): Promise<void> {
console.log('hitted handleInteraction');
if (!interaction.isChatInputCommand()) return;

const command = this._commands.get(interaction.commandName);
if (!command) return;

try {
await command.onExecution(interaction);
} catch (error) {
logger.error(
`Error while executing command '${command.data.name}'! Error: ${error}`
);
}
}

private static async getCommandFiles(): Promise<string[]> {
try {
const files = await readdir(COMMAND_FILES_PATH);
return files.filter(file => file.endsWith(COMMAND_FILES_EXTENSION));
} catch (error) {
logger.error(`Error while reading command files! Error: ${error}`);
return [];
}
}

public static async load(): Promise<CommandHandler> {
const commandFiles = await this.getCommandFiles();
return this.create(commandFiles);
}
}
import {Client, REST, Routes, CommandInteraction, Collection} from 'discord.js';
import logger from '../utilities/logger.util';
import {Discord} from '../../types/discord';
import {readdir} from 'fs/promises';
import {join} from 'path';
import 'dotenv/config';

const COMMAND_FILES_PATH = join(__dirname, '../commands');
const COMMAND_FILES_EXTENSION = '.command.ts';

export default class CommandHandler {
private _commandFiles: string[];
private _commands: Collection<string, Discord.Command>;

private constructor(commandFiles: string[]) {
this._commandFiles = commandFiles;
this._commands = new Collection();
}

public static async create(commandFiles: string[]): Promise<CommandHandler> {
return new CommandHandler(commandFiles);
}

public async doRegisterCommands(clientInstance: Client): Promise<void> {
try {
for (const file of this._commandFiles) {
const commandModule = await import(join(COMMAND_FILES_PATH, file));
const command: Discord.Command = commandModule.default;

this._commands.set(command.data.name, command);

logger.info(`Registered slash command '${command.data.name}'`);
}

// Register slash commands through the Discord REST API
await this.registerCommandsThroughAPI(clientInstance);
} catch (error) {
logger.error(`Error while registering command! Error: ${error}`);
}
}

private async registerCommandsThroughAPI(
clientInstance: Client
): Promise<void> {
const rest = new REST({version: '10'}).setToken(process.env.BOT_TOKEN!);

try {
// Fetch the globally registered commands
const commands = this._commands.map(command => command.data.toJSON());

// Register the commands globally
await rest.put(
Routes.applicationCommands(clientInstance.application!.id),
{
body: commands,
}
);

logger.info('Registered slash commands through REST API');
} catch (error) {
logger.error(
`Error while registering slash commands through REST API! Error: ${error}`
);
}
}

public async handleInteraction(
interaction: CommandInteraction
): Promise<void> {
console.log('hitted handleInteraction');
if (!interaction.isChatInputCommand()) return;

const command = this._commands.get(interaction.commandName);
if (!command) return;

try {
await command.onExecution(interaction);
} catch (error) {
logger.error(
`Error while executing command '${command.data.name}'! Error: ${error}`
);
}
}

private static async getCommandFiles(): Promise<string[]> {
try {
const files = await readdir(COMMAND_FILES_PATH);
return files.filter(file => file.endsWith(COMMAND_FILES_EXTENSION));
} catch (error) {
logger.error(`Error while reading command files! Error: ${error}`);
return [];
}
}

public static async load(): Promise<CommandHandler> {
const commandFiles = await this.getCommandFiles();
return this.create(commandFiles);
}
}
ping.command.ts:
import {CommandInteraction, SlashCommandBuilder} from 'discord.js';
import {Discord} from '../../types/discord';

async function processPingCommand(
interaction: CommandInteraction
): Promise<void> {
console.log('hitted ping execution');
await interaction.reply('Pong!');
}

const pingCommand: Discord.Command = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Returns pong'),
onExecution: processPingCommand,
};

export default pingCommand;
import {CommandInteraction, SlashCommandBuilder} from 'discord.js';
import {Discord} from '../../types/discord';

async function processPingCommand(
interaction: CommandInteraction
): Promise<void> {
console.log('hitted ping execution');
await interaction.reply('Pong!');
}

const pingCommand: Discord.Command = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Returns pong'),
onExecution: processPingCommand,
};

export default pingCommand;
interactionCreate.event.ts:
import CommandHandler from '../handlers/command.handler';
import {CommandInteraction} from 'discord.js';
import logger from '../utilities/logger.util';
import {Discord} from '../../types/discord';

async function handleInteractionCreateEvent(
interactionData: CommandInteraction
): Promise<void> {
try {
// Create an instance of the CommandHandler
const commandHandler = await CommandHandler.load();
console.log(interactionData.commandName);
// Call the 'handleInteraction' method of the CommandHandler instance
await commandHandler.handleInteraction(interactionData);
} catch (error) {
logger.error(`Error while handling interaction! Error: ${error}`);
}
}

const interactionCreateEvent: Discord.Event = {
name: 'INTERACTION_CREATE',
once: false,
onEmit: handleInteractionCreateEvent,
};

export default interactionCreateEvent;
import CommandHandler from '../handlers/command.handler';
import {CommandInteraction} from 'discord.js';
import logger from '../utilities/logger.util';
import {Discord} from '../../types/discord';

async function handleInteractionCreateEvent(
interactionData: CommandInteraction
): Promise<void> {
try {
// Create an instance of the CommandHandler
const commandHandler = await CommandHandler.load();
console.log(interactionData.commandName);
// Call the 'handleInteraction' method of the CommandHandler instance
await commandHandler.handleInteraction(interactionData);
} catch (error) {
logger.error(`Error while handling interaction! Error: ${error}`);
}
}

const interactionCreateEvent: Discord.Event = {
name: 'INTERACTION_CREATE',
once: false,
onEmit: handleInteractionCreateEvent,
};

export default interactionCreateEvent;
ready.event.ts:
import CommandHandler from '../handlers/command.handler';
import logger from '../utilities/logger.util';
import {Discord} from '../../types/discord';
import {Client} from 'discord.js';

async function handleReadyEvent(clientInstance: Client): Promise<void> {
await doRegisterCommands(clientInstance);
const username = clientInstance.user?.username;
logger.info(`Bot logged in as '${username}'`);
}

async function doRegisterCommands(clientInstance: Client): Promise<void> {
const commandHandler = await CommandHandler.load();
commandHandler.doRegisterCommands(clientInstance);
}

const readyEvent: Discord.Event = {
name: 'ready',
once: true,
onEmit: handleReadyEvent,
};

export default readyEvent;
import CommandHandler from '../handlers/command.handler';
import logger from '../utilities/logger.util';
import {Discord} from '../../types/discord';
import {Client} from 'discord.js';

async function handleReadyEvent(clientInstance: Client): Promise<void> {
await doRegisterCommands(clientInstance);
const username = clientInstance.user?.username;
logger.info(`Bot logged in as '${username}'`);
}

async function doRegisterCommands(clientInstance: Client): Promise<void> {
const commandHandler = await CommandHandler.load();
commandHandler.doRegisterCommands(clientInstance);
}

const readyEvent: Discord.Event = {
name: 'ready',
once: true,
onEmit: handleReadyEvent,
};

export default readyEvent;
Inside the ready event I am registering the application commands. I am also getting the success message of the ready event so the events are working as intended. I do not get any errors logged just the discord message "The application did not respond" So I assume it handles the command somewhere but console.log() in different places does not log anything
treble/luna
treble/luna12mo ago
the name is interactionCreate Or use the Events enum as alternative
darby
darby12mo ago
Huh.. okay when I logged GatewayDispatchEvents it logged "INTERACTION_CREATE" that's wyh I thought its named like that Okay, so I get the logging now when it hits the handleInteraction. But now is a point where I don't know anymore.. I am using the CommandInteraction type which does have the function isChatInputCommand But now I just get the error
error: Error while handling interaction! Error: TypeError: interaction.isChatInputCommand is not a function
error: Error while handling interaction! Error: TypeError: interaction.isChatInputCommand is not a function
No stack trace whatsoever just this message
Youssef
Youssef12mo ago
I think you should use BaseInteraction instead of ComamndInteraction
darby
darby12mo ago
But BaseInteraction does not have the .reply function I have in my ping command to test if it's working Also I am getting the same error that isChatInputCommand() is not a function :/ Okay, so I tried to log the commandName but it's undefined somehow Hitted handleInteraction()! undefined - undefined It ain't adding up tho lmao