Question about slash commands in discord.js - javascript

I want to make a Discord bot that can react to the slash commands and "type" commands. To prevent naming collisions, I renamed the command variable into scommand. However, when I do this, the code of slash command doesn't work. How can I fix it?
discord.js version: 12.5.3
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const {Collection} = require("discord.js")
const scommands = [];
const scommandFiles = fs.readdirSync('./slash.commands').filter(file => file.endsWith('.js'));
client.scommands = new Collection();
const clientId = process.env["clientId"]
for (const file of scommandFiles) {
try {
const scommand = require(`./slash.commands/${file}`);
scommands.push(scommand.data.toJSON());
client.scommands.set(scommand.data.name, scommand)
} catch (err) {console.log(err)}
}
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
{ body: scommands },
);
console.log('Successfully reloaded application (/) commands.');
})();
client.ws.on('INTERACTION_CREATE', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.scommands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
This is the code of the file in the ./slash.commands folder:
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('pong'),
async execute(interaction){
interaction.reply("pong")
}
Is it ok to use scommand and how should I fix it?

It seems to me, you declared a scommands field in client, but when executing, you refer to it as commands...
Try:
const command = client.scommands.get(interaction.commandName);

Related

Javascript Discord bot not running correct function

Im trying to create a discord bot, theres one command that returns the ping when /ping is typed, and another one im trying to add that restarts the bot when /restart is typed. But when I type /restart, it functions like I typed /ping and replied with the ping. I cannot find a solution to my problem so any help is appreciated. If you need more information on this please reply to me.
Here is a file called "handleCommands" with its code:
const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`./src/commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync('./src/commands');
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
if (command.data.name !== 'restart') {
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
} else {
commands.set(restartCommand.data.name, restartCommand);
commandArray.push(restartCommand.data.toJSON());
}
}
}
const clientId = '(BotsClientIdWentHere)';
const guildId = '(ServersClientIdWentHere';
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log('Successfully reloaded application (/) commands.')
} catch (error) {
console.error(error);
}
};
};
Here is code from restart.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('restart')
.setDescription('Restarts the bot (Debug)'),
async execute(interaction, client) {
// Shut down the bot
await client.destroy();
// Log the bot back in to Discord
await client.login(MyBotsTokenWentHere);
// Send a message to confirm that the bot has been restarted
await interaction.editReply({
content: 'Bot restarted successfully'
});
}
}
A file called "interactionCreate":
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
console.log("Received interaction event:", interaction);
if (interaction.isChatInputCommand()) {
console.log("Received chat input command:", interaction.commandName);
const { commands } = client;
const { commandName } = interaction;
const command = commands.get(commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `Something went wrong.. Please try again later. If this issue persists, please message my creator.`,
ephermeral: true,
});
}
}
},
};
And bot.js:
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];
const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync (`./src/functions/${folder}`)
.filter((file) => file.endsWith('.js'));
for (const file of functionFiles)
require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);
Here is also the ping file code:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Returns the bots ping (Debug)'),
async execute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true
});
const currentTime = Date.now();
const responseTime = currentTime - interaction.createdTimestamp;
const responseTimeSeconds = responseTime / 1000; // convert to seconds
const newMessage = `API Latency: ${client.ws.ping}\nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}\nTime: ${responseTimeSeconds} seconds`
await interaction.editReply({
content: newMessage
});
}
}
And here I attacked a picture of the file heirarchy.
enter image description here
I tried to add functions that were supposed to add the function to table and add logs to the console to try to see what its printing but in the end the last error was "ReferenceError: (MyBotsTokenWentHere) is not defined". Any help appreciated.
Edit: Problem solved. Here is the updated restart.js and handleCommands files:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('restart')
.setDescription('Restarts the bot (Debug)'),
async execute(interaction, client) {
// Send a reply to the command message
await interaction.deferReply({
content: 'Restarting the bot...'
});
// Shut down the bot
await client.destroy();
// Log the bot back in to Discord
await client.login(MyBotsTokenWentHere);
// Edit the reply to confirm that the bot has been restarted
await interaction.editReply({
content: 'Bot restarted successfully'
});
}
}
handleCommands:
const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`../../commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync('./src/commands');
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
//console.log(`loading ${command.data.name} from commands/${folder}/${file}`)
if (command.data.name !== 'restart') {
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
} else {
commands.set(restartCommand.data.name, restartCommand);
commandArray.push(restartCommand.data.toJSON());
}
}
}
const clientId = '(ClientIdWentHere)';
const guildId = '(GuildIdWentHere)';
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log('Successfully reloaded application (/) commands.')
} catch (error) {
console.error(error);
}
};
};

how do I Build a discord button that replies with a new set of button

I want it to be where you type in your slashcommand example:"/bank" and it'll show 2 different buttons "offense" "defense" then when you click one of those buttons it'll pop up another set up buttons to click from. Right now it works to where I do /bank and it'll reply with the two buttons offense and defense and it'll reply with you clicked which ever button was clicked. But I want to to reply with another set up buttons.
// this is my button command
bank.js
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('bank')
.setDescription('Replies with some buttons!'),
async execute(interaction) {
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('offense')
.setLabel('Offense')
.setStyle('SUCCESS'),
new MessageButton()
.setCustomId(' defense')
.setLabel('Defense')
.setStyle('DANGER'),
);
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Map: BANK ')
.setURL('https://discord.js.org')
.setImage('https://i.imgur.com/s54Riow.jpeg')
.setDescription('Choose your team shitter');
await interaction.reply({ ephemeral: true, embeds: [embed], components: [row] });
},
};
this is my
interactionCreate.js
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if(interaction.isButton())
interaction.reply("you clicked" + interaction.customId);
console.log(interaction);
if (!interaction.isCommand()) return;
if (!interaction.isButton()) return;
const command = client.command.get(interaction.commandName);
if(!command) return;
try{
await command.execute(interaction);
}catch(error){
console.error(error);
await interaction.reply({content : "There was an error while executing action"})
}
console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
},
};
this is my index.js
// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.commands = new Collection();
// command files
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
// event files
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// When the client is ready, run this code (only once)
client.once('ready', c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// When any message is sent in any channel it'll all be logged into the terminal
client.on('message', async msg => {
if(!msg.content.startsWith(config.prefix)) return;
var command = msg.content.substring(1);
if(!client.commands.has(command)) return;
try{
await client.commands.get(command).execute(msg);
} catch(error) {
console.error(error);
await msg.reply({content: "there was an error", epthemeral: true})
}
});
// interaction files
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
// Login to Discord with your client's token
client.login(token);
this is my deploy-commands.js
const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
We will be working inside of your interactionCreate.js where you collect the buttons.
We will need to update the interaction with the new message. docs
I am noticing duplicate code in your index.js and interactionCreate.js. This is where you run the slash commands. As a recommendation, you may want to remove the if (!interaction.isCommand()) return; in the interactionCreate.js and remove the index.js listener. Just to have one file handing the interactionCreate event. I'll be doing this in the example.
Also you may find a problem in the future since in blank.js there is a space inside of the interaction customId.
Example with one Listener
const { MessageButton, MessageActionRow } = require('discord.js');
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (interaction.isCommand()) { // Checks if the interaction is a command and runs the `
const command = client.command.get(interaction.commandName);
if(!command) return;
try{
await command.execute(interaction);
}catch(error){
console.error(error);
await interaction.reply({content : "There was an error while executing action"})
}
console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
return;
} else if (interaction.isButton()) { // Checks if the interaction is a button
interaction.reply("you clicked" + interaction.customId);
console.log(interaction);
if (interaction.customId === 'offense') { // Check for the customId of the button
console.log(`${interaction.user.tag} in #${interaction.channel.name} clicked the offense button.`);
const ActionRow = new MessageActionRow().setComponents(new MessageButton() // Create the button inside of an action Row
.setCustomId('CustomId')
.setLabel('Label')
.setStyle('PRIMARY'));
return interaction.update({ // update the interaction with the new action row
content: 'Hey',
components: [ActionRow],
ephemeral: true
});
}
}
},
};
With the original example
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if(interaction.isButton()) {
interaction.reply("you clicked" + interaction.customId);
console.log(interaction);
if (interaction.customId === 'offense') { // Check for the customId of the button
console.log(`${interaction.user.tag} in #${interaction.channel.name} clicked the offense button.`);
const ActionRow = new MessageActionRow().setComponents(new MessageButton() // Create the button inside of an action Row
.setCustomId('CustomId')
.setLabel('Label')
.setStyle('PRIMARY'));
return interaction.update({ // update the interaction with the new action row
content: 'Hey',
components: [ActionRow],
ephemeral: true
});
}
return;
}
if (!interaction.isCommand()) return;
if (!interaction.isButton()) return;
const command = client.command.get(interaction.commandName);
if(!command) return;
try{
await command.execute(interaction);
}catch(error){
console.error(error);
await interaction.reply({content : "There was an error while executing action"})
}
console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);
},
};
If you need to get the embed that was sent in the original message, you can use <interaction>.embeds to get the embed and then edit it to your liking.
Now if you don't want to edit the interaction and reply with a new message remember that if your original message is an ephemeral you can't delete it. You can use replying methods.
Explanation
We are checking for the customId that was used when building the button. After we create an action row and add the new message button. Then we are updating the original message content with different components.
Feel free to leave a comment if you run into any problems

Allow users to send suggestion for the bot to create and send an embed with two emojis to vote

I'm trying to create a discord bot that will where someone can enter the slash command /suggestion and the bot will take that suggestion and turn it into an embed and send it into a specific suggestions channel with two emojis, an X and Checkmark.
After getting it all written and doing node deploy-commands.js and getting no errors, I inputted node . with also no errors in the terminal.
But when I went into the discord and enter the /suggestions command, I get an error in the terminal which is:
TypeError: Cannot read properties of undefined (reading 'join')
and I have no idea how to follow the error to see where it's originating from.
Does anyone have any thoughts on this?
I'll leave my index.js, suggestions.js, and deploy-commands.js below.
index.js
// Require the necessary discord.js classes
const fs = require('fs');
const { Client, Collection, Intents, } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
});
client.commands = new Collection();
client.events = new Collection();
const commandFiles = fs
.readdirSync('./commands')
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log("You are now connected to Boombap Suggestions!");
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true,
});
}
});
// Login to Discord with your client's token
client.login(token);
suggestions.js
module.exports = {
name: 'suggestions',
aliases: ['suggest', 'suggestion'],
permissions: [],
description: 'creates a suggestion!',
execute(message, args, cmd, client, discord) {
const channel = message.guild.channels.cache.find(c => c.name === 'suggestions');
if (!channel) return message.channel.send('suggestions channel does not exist!');
let messageArgs = args.join(' ');
const embed = new discord.MessageEmbed()
.setColor('5104DB')
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
.setDescription(messageArgs);
channel.send(embed).then((msg) => {
msg.react('❌');
msg.react('βœ…');
message.delete();
}).catch((err) => {
throw err;
});
}
}
deploy-commands.js
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('suggestions').setDescription('Submit A Suggestion!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
You're only passing the interaction at command.execute(interaction) yet you're expecting message, args, etc at execute(message, args, cmd, client, discord). As args is undefined you receive "TypeError: Cannot read properties of undefined (reading 'join')" .
Another problem is that you're using v13 of discord.js and still having some v12 syntax, just like in your previous post.
As you are using slash commands, you will have no args, you could add a string option in your deploy-commands.js file using the addStringOption() method. You should also mark this command option as required by using the setRequired() method.
Update commands in deploy-commands.js:
const commands = [
new SlashCommandBuilder()
.setName('suggest')
.setDescription('Submit a suggestion!')
.addStringOption((option) =>
option
.setName('suggestion')
.setDescription('Enter your suggestion')
.setRequired(true),
),
].map((command) => command.toJSON());
In your suggestions.js file, you can get this option from the CommandInteractionOptionResolver using interaction.options.getString('suggestion').
There are some changes to how setAuthor() works in v13. It now accepts an EmbedAuthorData object that has a name and an iconURL property.
Replace your suggestions.js with the following:
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'suggest',
aliases: ['suggest', 'suggestion'],
permissions: [],
description: 'creates a suggestion!',
async execute(interaction) {
let channel = interaction.guild.channels.cache.find((c) => c.name === 'suggestions');
if (!channel) {
await interaction.reply('`suggestions` channel does not exist!');
return;
}
let suggestion = interaction.options.getString('suggestion');
let embed = new MessageEmbed()
.setColor('5104DB')
.setAuthor({
name: interaction.member.user.tag,
iconURL: interaction.member.displayAvatarURL({ dynamic: true }),
})
.setDescription(suggestion);
let sentEmbed = await channel.send({ embeds: [embed] });
await interaction.reply({
content: 'πŸŽ‰ Thanks, we have received your suggestion',
ephemeral: true,
});
sentEmbed.react('❌');
sentEmbed.react('βœ…');
},
};

Discord.js v13 (intermediate value).setToken(...) is not a function

Im new to Discod.js v13. I get this error
(async () => {
^
TypeError: (intermediate value) is not a function
This is the code i think its the problem
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
If you need the full code:
const { Client, Intents, Collection } = require("discord.js")
const fs = require("fs")
const {REST} = require("#discordjs/rest");
const {Routes} = require("discord-api-types/v9");
const client = new Client({
intents:[
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const BotName = "TestBot"
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
const commands = []
client.commands = new Collection()
for(const file of commandFiles){
const command = require("./commands/"+file)
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command)
}
client.once("ready", applicationId =>{
console.log(`${BotName} is now online`)
const CLIENT_ID = client.user.id
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
try{
if(process.env.ENV === "production"){
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
})
console.log("Success command register globally")
}else{
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID), {
body: commands
})
console.log("Success command register locally")
}
}catch(err){
console.log(err)
}
})();
})
client.on("interaction", async interaction =>{
if(!interaction.isCommand()) return
const command = client.commands.get(interaction.commandName)
if(!command) return
try{
await command.execute(interaction);
}catch(err){
console.log(err)
await interaction.reply({
content: "ERROR" + err,
ephemeral:true
})
}
})
client.login("MyToken")
As said in my comment, this is a ASI (automatic semicolon insertion) related error. I checked it, and after putting a semicolon after }).setToken("MyToken"); it worked fine.
Always use semicolons to avoid these mistakes.

Discord slash command "interaction failed" V13

Discord added these slash commands in v13, I have followed the discordjs.guide website on how to do it.
My code is:
//packages
const { Client, Collection, Intents } = require("discord.js");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const disbut = require("discord-buttons");
client.commands = new Collection();
const moment = require("moment");
const { MessageEmbed } = require("discord.js");
const AntiSpam = require("discord-anti-spam");
const ms = require("ms");
const { Slash } = require("discord-slash-commands");
const slash = new Slash(client);
const rtkn = ">r";
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, owner, bowner, clientid, guildid, prefix } = require("./config.json");
const fs = require("fs");
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
const commands = [];
const cmds = [];
disbut(client);
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const commands = [];
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: "There was an error while executing this command!", ephemeral: true });
}
});
const rest = new REST({ version: "9" }).setToken(token);
(async () => {
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands });
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
})();
const clean = (text) => {
if (typeof text === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/#/g, "#" + String.fromCharCode(8203));
else return text;
};
client.on("message", (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(prefix + "eval")) {
if (message.author.id !== owner) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), { code: "xl" });
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
client.on("message", (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(prefix + "eval")) {
if (message.author.id !== bowner) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), { code: "xl" });
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
client.on("warn", (err) => console.warn("[WARNING]", err));
client.on("error", (err) => console.error("[ERROR]", err));
client.on("disconnect", () => {
console.warn("Disconnected!");
process.exit(0);
});
process.on("unhandledRejection", (reason, promise) => {
console.log("[FATAL] Possibly Unhandled Rejection at: Promise ", promise, " reason: ", reason.message);
});
client.login(token);
//ping.js contents below.
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
async execute(interaction) {
await interaction.reply("Pong!");
},
};
My ping.js file is:
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
async execute(interaction) {
return interaction.reply("Pong!");
},
};
When I run the code, it registers the slash commands fine, but when I run it, it says "interaction failed." Please help.
Your code is not well structured. You have a lot of deprecated modules and you declared commands twice. The problem however, is that you never call client.commands.set. In your for...of loop, you called commands.push instead of client.commands.set.
I don’t know how the SlashCommandBuilder function works, but I suspect the toJSON method would return something that looks like this:
{
name: 'commandName',
description: 'description',
options: []
}
You have to change your loop to look like this:
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
const data = command.data.toJSON()
client.commands.set(data.name, data);
}

Categories

Resources