Discord not loading slash commands - javascript

I am trying to make a slash command system for my discord.js bot, but it does not show up in the app
Here is the code I am using
const {
Client,
Collection,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const fs = require('fs');
const {
Routes
} = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const commands = [];
// Creating a collection for commands in client
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.on('ready', () => {
console.log(`Ready! Logged in as ${client.user.tag}`)
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
console.log(`Loaded slash command /${command.data.name}.`)
}
const CLIENT_ID = client.user.id;
const rest = new REST({
version: '9'
}).setToken("myToken");
(async () => {
try {
await rest.put(
Routes.applicationCommands(CLIENT_ID), {
body: commands
},
);
console.log('Successfully registered all application commands globally');
} catch (error) {
if (error) console.error(error);
}
})();
})
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
const { options } = interaction
try {
await command.execute(interaction, options, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `ERROR: There was a problem executing the **${command.name}** command. Please try again later.`,
ephemeral: true
});
}
});
client.login("myToken")
This is my command file (My ping.js file)
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Ping Pong!"),
async execute(interaction, options, client) {
interaction.reply("Pong!")
}
}
Whenever I launch my bot, no slash commands appear. All the strings are logged to the console though.
I have given the bot application.commands scope.

Related

Error In My Discord Bot: Cannot read properties of undefined (reading 'get')

I've been getting this error recently and I don't really know how I'm supposed to fix this;
TypeError: Cannot read properties of undefined (reading 'get')
This is the line of code it refers to:
const command1 = interaction.client.commands.get(interaction.commandName);
It was working earlier, but I tried adding the command refresh thingy and it's not working anymore.
Here's my full code:
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const { clientId, guildId, token } = require('./config.json');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
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());
}
client.once('ready', () => {
console.log('Ready!');
});
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command1 = interaction.client.commands.get(interaction.commandName);
if (!command1) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command1.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
hey try adding this code
const channel = await client.channels.fetch('<channel-id>')

DiscordJs & distube - Why can't I do anything after I play music?

I am using DiscordJs and distube to create a bot for my discord server. I am using slash commands. The problem is that I can't execute any command (so I cannot even execute /stop or play another song) after I play a song. This is my code:
const {SlashCommandBuilder} = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Play a song.")
.addStringOption(option => option.setName("song").setDescription("The song link or name.").setRequired(true)),
async execute(interaction) {
interaction.reply({content: 'Music started.', ephemeral: true});
const {member, channel, client} = interaction;
await client.distube.play(member.voice.channel, interaction.options.get("song").value, {textChannel: channel, member: member});
}
}
My command handler:
const fs = require("fs");
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const clientId = '12345678';
const guildId = '12345678';
module.exports = (client) => {
client.handleCommands = async (commandsFolder, path) => {
client.commandArray = [];
for (const folder of commandsFolder) {
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
await client.commands.set(command.data.name, command);
client.commandArray.push(command.data.toJSON());
}
}
const rest = new REST({ version: '9' }).setToken("sometextthatidontwanttoshow");
await (async () => {
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);
}
})();
}
}
And this is the function that "creates" the commands:
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
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
})
}
}
}
And this is my index file
const {Client, Intents, Collection} = require("discord.js");
const fs = require("fs");
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES]});
client.commands = new Collection();
const {DisTube} = require("distube");
client.distube = new DisTube(client, {
emitNewSongOnly: true,
leaveOnFinish: false,
emitAddSongWhenCreatingQueue: false
});
module.exports = client;
const functions = fs.readdirSync("./src/functions").filter(file => file.endsWith(".js"));
const eventFiles = fs.readdirSync("./src/events").filter(file => file.endsWith(".js"));
const commandsFolders = fs.readdirSync("./src/commands");
(async () => {
for (const file of functions) {
require(`./src/functions/${file}`)(client);
}
client.handleEvents(eventFiles, "./src/events");
client.handleCommands(commandsFolders, "./src/commands");
await client.login('mybeautifultoken')
})();
Any help is highly appreciated. Thanks in advance.
Okay, I believe the issue lies in the fact that you're awaiting your command.execute(). I believe behind the scenes what this is doing is that its creating a promise that resolves once your discord bot's music finishes playing.
While its correct to use these functions asynchronously, when you call it like this it actually blocks all the other similar asynchronous functions (slash commands) from occurring until this one resolves. Let me know if this fixes it.
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
command.execute(interaction); //removed await
} catch (error) {
console.error(error);
await interaction.reply({
content: "There was an error while executing this command.",
ephemeral: true
})
}
}
}
index edits
await client.handleEvents(eventFiles, "./src/events");
await client.handleCommands(commandsFolders, "./src/commands");

TypeError: Cannot read properties of undefined (reading 'destroy')

I get this error:
TypeError: Cannot read properties of undefined (reading 'destroy')
When running this code:
const { SlashCommandBuilder } = require("#discordjs/builders");
require('dotenv').config()
module.exports = {
data: new SlashCommandBuilder()
.setName("restart")
.setDescription("Restarts the bot."),
async execute(interaction, args, client) {
let isBotOwner = interaction.user.id == '847213179142799452';
if (isBotOwner) {
interaction.reply('Restarting...').then(m => {
client.destroy().then(() => {
client.login(process.env.TOKEN);
});
});
} else {
interaction.reply('You cannot run this command unless you are the developer of me.')
}
}
}
The error is on client.destroy().
I've been looking in the docs and guides and on google but can't find anything on how to get it to work.
Could it be because I'm trying to destroy the client through a slash command?
Here is the command/interaction handler:
const {
Client,
Collection,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const fs = require('fs');
require('dotenv').config()
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
}
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
});
}
});

ReferenceError: client is not defined Discord.js

I cannot figure out why its saying this error here, its telling me that client isnt defined when it is defined right here though im also unsure of anything else that im missing because all of my code so far has been from the offical documentation of discord.js
(The guild and client id's have been removed for privacy reasons)
Code:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token } = require('./config.json');
const fs = require('fs');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Place your client and guild ids here
const clientId = '';
const guildId = '';
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.applicationCommands(clientId),
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log(`${client.user.tag}`)
});
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
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 });
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (commandName === 'user') {
await interaction.reply(`Your tag: ${interaction.user.tag}\nYour id: ${interaction.user.id}`);
}
});
client.on('interactionCreate', interaction => {
if (!interaction.isCommand()) return;
console.log(interaction);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login(token);
You need to instantiate a Discord.Client in order to get access to discord.js apis.
const {Client, Intents} = require('discord.js')
const client = new Client({intents: [/* Your intents here */]})
client.login(/* your token */)
client.on('ready', function () {
/* client is ready */
}
Since discord.js v12, intents were introduced, so you will also need to use them.
More about intents: https://discordjs.guide/popular-topics/intents.html#error-disallowed-intents

Discord slash command interactions failing despite event handler logging the interactions correctly

Following along with discordjs.guide/creating-your-bot
I've made an event handler that's working correctly and returning the expected terminal logs.
However, none of the commands that were previously working are working. I've had this happen before and I had to restart the bot and the commands started functioning correctly again.
The bit I can't figure out is the interaction are being logged in my terminal successful yet they're showing up as failed interactions in the discord.
My command handler;
const fs = require('fs');
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 {
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully registered application commands.');
} catch (error) {
console.error(error);
}
})();
my event handler;
const fs = require('fs');
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Ping command:
const { SlashCommandBuilder } = require('#discordjs/builders'); module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
},
};
interactionCreate event listener:
module.exports = { name: 'interactionCreate', execute(interaction) { console.log(${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.); }, }; This is triggering correctly at least, I'm getting an output in my log that's expected.
And my interactionCreate although this lives in with my command handling folder/code. I'll post the folder structure below as well.
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 });
}
});

Categories