Registered command not responding.

I have an command which is registered and is being added to client.commands, but for some reason whenever I execute it on discord it's not even called. I made action of the command simply console.log() to verify it.
8 Replies
d.js toolkit
d.js toolkit14mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button! - Marked as resolved by OP
gio735
gio735OP14mo ago
let fileReader = require("..\\..\\utils\\FileReader.js");
const { SlashCommandBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder, CommandInteraction, EmbedBuilder } = require('discord.js');
const words = __dirname.split('\\');
const size = words.length - 1;
let description = fileReader.Read(__dirname + "\\description.txt");

module.exports = {

data: new SlashCommandBuilder()
.setName(words[size].toLowerCase())
.setDescription(description)
.addStringOption(option =>
option.setName('token')
.setRequired(true)
.setDescription('Put verification code from your mail here.')),
/**
* @param {CommandInteraction} interaction
*/
async execute(interaction) {
console.log("At least I'm in bruh");
try {

const tkn = interaction.options.get('token') ?? '';
console.log(token);
} catch (err) { console.log(err); }

}
};
let fileReader = require("..\\..\\utils\\FileReader.js");
const { SlashCommandBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder, CommandInteraction, EmbedBuilder } = require('discord.js');
const words = __dirname.split('\\');
const size = words.length - 1;
let description = fileReader.Read(__dirname + "\\description.txt");

module.exports = {

data: new SlashCommandBuilder()
.setName(words[size].toLowerCase())
.setDescription(description)
.addStringOption(option =>
option.setName('token')
.setRequired(true)
.setDescription('Put verification code from your mail here.')),
/**
* @param {CommandInteraction} interaction
*/
async execute(interaction) {
console.log("At least I'm in bruh");
try {

const tkn = interaction.options.get('token') ?? '';
console.log(token);
} catch (err) { console.log(err); }

}
};
Command
require('dotenv').config();
const fs = require('node:fs');
const path = require('node:path');
const { Client, ButtonBuilder, ActionRowBuilder, EmbedBuilder, ButtonStyle, Collection, Events, GatewayIntentBits, IntentsBitField, CommandInteraction, ModalBuilder, TextInputBuilder, TextInputStyle, } = require('discord.js');
const crypto = require("crypto");
const mailSender = require("..\\src\\utils\\MailSender.js");

const client = new Client( {
intents: [
GatewayIntentBits.Guilds,
IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMembers,
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent,
],
} );


verifications = [];
function FindVerification(predicate) {
let result = null;
console.log("at begining!");
verifications.forEach(element => {
console.log(element);
if (predicate(element)) {
console.log("Found: " + element);
result = element;
}
});
console.log("Result is: " + result);
return result;
}
function removeExpiredVerifications() {
const currentTime = new Date();

for (let i = verifications.length - 1; i >= 0; i--) {
const verification = verifications[i];
const creationTime = new Date(verification.creationDate);
const timeDifferenceInMinutes = Math.floor((currentTime - creationTime) / 60000);

if (timeDifferenceInMinutes > 5) {
verifications.splice(i, 1);
}
}
}
setInterval(removeExpiredVerifications, 20000);

// Setting up command files from subdirectories of the command directory
const foldersPath = path.join(__dirname, 'commands');
client.commands = new Collection();
const commandFolders = fs.readdirSync(foldersPath);

for(const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
console.log(commandsPath);
require('dotenv').config();
const fs = require('node:fs');
const path = require('node:path');
const { Client, ButtonBuilder, ActionRowBuilder, EmbedBuilder, ButtonStyle, Collection, Events, GatewayIntentBits, IntentsBitField, CommandInteraction, ModalBuilder, TextInputBuilder, TextInputStyle, } = require('discord.js');
const crypto = require("crypto");
const mailSender = require("..\\src\\utils\\MailSender.js");

const client = new Client( {
intents: [
GatewayIntentBits.Guilds,
IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMembers,
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent,
],
} );


verifications = [];
function FindVerification(predicate) {
let result = null;
console.log("at begining!");
verifications.forEach(element => {
console.log(element);
if (predicate(element)) {
console.log("Found: " + element);
result = element;
}
});
console.log("Result is: " + result);
return result;
}
function removeExpiredVerifications() {
const currentTime = new Date();

for (let i = verifications.length - 1; i >= 0; i--) {
const verification = verifications[i];
const creationTime = new Date(verification.creationDate);
const timeDifferenceInMinutes = Math.floor((currentTime - creationTime) / 60000);

if (timeDifferenceInMinutes > 5) {
verifications.splice(i, 1);
}
}
}
setInterval(removeExpiredVerifications, 20000);

// Setting up command files from subdirectories of the command directory
const foldersPath = path.join(__dirname, 'commands');
client.commands = new Collection();
const commandFolders = fs.readdirSync(foldersPath);

for(const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
console.log(commandsPath);
const commandFiles = fs.readdirSync(commandsPath).filter( file => file.endsWith('slash.js') );
console.log(commandFiles);
for(const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
console.log(command);
if ('data' in command && 'execute' in command) {
console.log(command.data.name);
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
console.log(client.commands);

client.on('messageCreate', message => {
if(message.author.bot){
return;
}

if(message.content === 'koba'){
message.reply('შმობა');
}
})


// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
try {
throw "already sent";
console.log("in try");
let channel = client.channels.cache.get("1157723850386198629");
const verify = new ButtonBuilder()
.setCustomId('verify')
.setLabel('Verify!')
.setStyle(ButtonStyle.Primary);
const commandFiles = fs.readdirSync(commandsPath).filter( file => file.endsWith('slash.js') );
console.log(commandFiles);
for(const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
console.log(command);
if ('data' in command && 'execute' in command) {
console.log(command.data.name);
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
console.log(client.commands);

client.on('messageCreate', message => {
if(message.author.bot){
return;
}

if(message.content === 'koba'){
message.reply('შმობა');
}
})


// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
try {
throw "already sent";
console.log("in try");
let channel = client.channels.cache.get("1157723850386198629");
const verify = new ButtonBuilder()
.setCustomId('verify')
.setLabel('Verify!')
.setStyle(ButtonStyle.Primary);
const guest = new ButtonBuilder()
.setCustomId('guest')
.setLabel('Guest!')
.setStyle(ButtonStyle.Secondary);
const row = new ActionRowBuilder()
.addComponents(verify, guest);

const verificationEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('Verify')
.setAuthor({ name: 'Orthodox Botto', iconURL: "https://reitingi.ambebi.ge/pictures/image11/224dbdde2f7bde6aeacd55a1217d648a.jpg?width=500" })
.addFields(
{ name: 'Student:', value: 'Submit your info and verify yourself using \"/verify\" command to be approved as student.' },
{ name: 'Guest:', value: 'Enter the server as guest.'},
);

channel.send({
embeds: [verificationEmbed],
components: [row],
});
}
catch (err) { console.log(err); }

})


client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
if (interaction.customId == 'verify') {

const modal = new ModalBuilder()
.setCustomId('registration')
.setTitle('რეგისტრაცია');

const nameInput = new TextInputBuilder()
.setCustomId('name')
.setLabel("რა არის თქვენი სახელი?")
.setStyle(TextInputStyle.Short);


const lastnameInput = new TextInputBuilder()
.setCustomId('lastname')
.setLabel("ჩაწერეთ თქვენი გვარი")
.setStyle(TextInputStyle.Short);
const guest = new ButtonBuilder()
.setCustomId('guest')
.setLabel('Guest!')
.setStyle(ButtonStyle.Secondary);
const row = new ActionRowBuilder()
.addComponents(verify, guest);

const verificationEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('Verify')
.setAuthor({ name: 'Orthodox Botto', iconURL: "https://reitingi.ambebi.ge/pictures/image11/224dbdde2f7bde6aeacd55a1217d648a.jpg?width=500" })
.addFields(
{ name: 'Student:', value: 'Submit your info and verify yourself using \"/verify\" command to be approved as student.' },
{ name: 'Guest:', value: 'Enter the server as guest.'},
);

channel.send({
embeds: [verificationEmbed],
components: [row],
});
}
catch (err) { console.log(err); }

})


client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
if (interaction.customId == 'verify') {

const modal = new ModalBuilder()
.setCustomId('registration')
.setTitle('რეგისტრაცია');

const nameInput = new TextInputBuilder()
.setCustomId('name')
.setLabel("რა არის თქვენი სახელი?")
.setStyle(TextInputStyle.Short);


const lastnameInput = new TextInputBuilder()
.setCustomId('lastname')
.setLabel("ჩაწერეთ თქვენი გვარი")
.setStyle(TextInputStyle.Short);
const emailInput = new TextInputBuilder()
.setCustomId('email')
.setLabel("ჩაწერეთ თქვენი მეილი. [email protected])")
.setStyle(TextInputStyle.Short);

const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
const secondActionRow = new ActionRowBuilder().addComponents(lastnameInput);
const emailInput = new TextInputBuilder()
.setCustomId('email')
.setLabel("ჩაწერეთ თქვენი მეილი. [email protected])")
.setStyle(TextInputStyle.Short);

const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
const secondActionRow = new ActionRowBuilder().addComponents(lastnameInput);
const thirdActionRow = new ActionRowBuilder().addComponents(emailInput);

modal.addComponents(firstActionRow, secondActionRow, thirdActionRow);
await interaction.showModal(modal);
}
else if (interaction.customId == 'guest') {

const modal = new ModalBuilder()
.setCustomId('guestNaming')
.setTitle('რეგისტრაცია');

const nameInput = new TextInputBuilder()
.setCustomId('name')
.setLabel("რა არის თქვენი სახელი?")
.setStyle(TextInputStyle.Short);

const lastnameInput = new TextInputBuilder()
.setCustomId('lastname')
.setLabel("ჩაწერეთ თქვენი გვარი")
.setStyle(TextInputStyle.Short);

const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
const secondActionRow = new ActionRowBuilder().addComponents(lastnameInput);

modal.addComponents(firstActionRow, secondActionRow);
await interaction.showModal(modal);
}
}
});

client.on('interactionCreate', async interaction => {
if (interaction.isModalSubmit()) {
if (interaction.customId == 'registration') {
const name = interaction.fields.getTextInputValue('name');
const lastname = interaction.fields.getTextInputValue('lastname');
const email = interaction.fields.getTextInputValue('email');
console.log(name + " " + lastname + " " + email);

if (interaction.member.roles.cache.some(role => role.name === 'nub')) {
const thirdActionRow = new ActionRowBuilder().addComponents(emailInput);

modal.addComponents(firstActionRow, secondActionRow, thirdActionRow);
await interaction.showModal(modal);
}
else if (interaction.customId == 'guest') {

const modal = new ModalBuilder()
.setCustomId('guestNaming')
.setTitle('რეგისტრაცია');

const nameInput = new TextInputBuilder()
.setCustomId('name')
.setLabel("რა არის თქვენი სახელი?")
.setStyle(TextInputStyle.Short);

const lastnameInput = new TextInputBuilder()
.setCustomId('lastname')
.setLabel("ჩაწერეთ თქვენი გვარი")
.setStyle(TextInputStyle.Short);

const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
const secondActionRow = new ActionRowBuilder().addComponents(lastnameInput);

modal.addComponents(firstActionRow, secondActionRow);
await interaction.showModal(modal);
}
}
});

client.on('interactionCreate', async interaction => {
if (interaction.isModalSubmit()) {
if (interaction.customId == 'registration') {
const name = interaction.fields.getTextInputValue('name');
const lastname = interaction.fields.getTextInputValue('lastname');
const email = interaction.fields.getTextInputValue('email');
console.log(name + " " + lastname + " " + email);

if (interaction.member.roles.cache.some(role => role.name === 'nub')) {
let role = interaction.guild.roles.cache.find(role => role.name === "nub");
await interaction.member.roles.remove(role);
}
console.log("removed 1 role");
if (interaction.member.roles.cache.some(role => role.name === 'stud')) {
await interaction.reply({ content: "Already verified!", ephemeral: true });
return 0;
}
let role = null;

if (!email.endsWith("@sangu.edu.ge")) {
await interaction.reply({ content: "Invalid mail for verification. (must be @sangu.edu.ge)", ephemeral: true })
return 0;
}

let tkn = crypto.randomBytes(16).toString("hex");
const verification = {
userID: interaction.member.id,
token: tkn,
creationDate: new Date()
}
let oldToken = FindVerification(v => v.userID == interaction.member.id)
if (oldToken) {
console.log("deleting old.");
let index = verifications.indexOf(oldToken);
verifications.splice(index, 1);
}
verifications.push(verification);
mailSender.SendMail(email, "ვერიფიკაცია სანგუში", "სტუდენტად ვერიფიკაციისათვის შეიყვანეთ შემდეგი კოდი: " + tkn);
await interaction.reply({ content: "Verification token sent to your mail. please check it and use \"/Verify\" command.", ephemeral: true });
return 0;
}
}
});

process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
client.login(process.env.DISCORD_TOKEN);
let role = interaction.guild.roles.cache.find(role => role.name === "nub");
await interaction.member.roles.remove(role);
}
console.log("removed 1 role");
if (interaction.member.roles.cache.some(role => role.name === 'stud')) {
await interaction.reply({ content: "Already verified!", ephemeral: true });
return 0;
}
let role = null;

if (!email.endsWith("@sangu.edu.ge")) {
await interaction.reply({ content: "Invalid mail for verification. (must be @sangu.edu.ge)", ephemeral: true })
return 0;
}

let tkn = crypto.randomBytes(16).toString("hex");
const verification = {
userID: interaction.member.id,
token: tkn,
creationDate: new Date()
}
let oldToken = FindVerification(v => v.userID == interaction.member.id)
if (oldToken) {
console.log("deleting old.");
let index = verifications.indexOf(oldToken);
verifications.splice(index, 1);
}
verifications.push(verification);
mailSender.SendMail(email, "ვერიფიკაცია სანგუში", "სტუდენტად ვერიფიკაციისათვის შეიყვანეთ შემდეგი კოდი: " + tkn);
await interaction.reply({ content: "Verification token sent to your mail. please check it and use \"/Verify\" command.", ephemeral: true });
return 0;
}
}
});

process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
client.login(process.env.DISCORD_TOKEN);
Index.js
d.js docs
d.js docs14mo ago
To share long code snippets, use a service like gist, sourcebin, starbin, or similar instead of posting them as large code blocks or files.
gio735
gio735OP14mo ago
Should I upload it there and resend or?
treble/luna
treble/luna14mo ago
also you return every interaction that isnt a button No nvm Send it in a pastebin
gio735
gio735OP14mo ago
https://starb.in/raw/UwvkWg Command one is kinda short welp
treble/luna
treble/luna14mo ago
I dont see you handling any command interactions there There also is no need for 2 listeners
gio735
gio735OP14mo ago
I know but did split them cus one is button other is modal. They are there temporarily anyways and gonna move them away later. For command handling I need to make something like client.on("slashCommandUsed" ...) Something similar?
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;

const command = client.commands.get(interaction.commandName);

//If the command doesn't exist, it will return undefined, so exit early with return.
if (!command) return;

//If it does exist, call the command's .execute() method, and pass in the interaction variable as its argument.
try {
await command.execute(interaction);
//In case something goes wrong, log the error and report back to the member to let them know.
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;

const command = client.commands.get(interaction.commandName);

//If the command doesn't exist, it will return undefined, so exit early with return.
if (!command) return;

//If it does exist, call the command's .execute() method, and pass in the interaction variable as its argument.
try {
await command.execute(interaction);
//In case something goes wrong, log the error and report back to the member to let them know.
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
This is what I lack I guess Thank you
Want results from more Discord servers?
Add your server