Discord.js command handling. Command handling dont work - node.js

I copied the code exactly from the official Discord.JS Guide. But the bot does not respond to the command in any way. How to solve it?
index.js:
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();
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);
}
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) 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 });
}
});
client.login(token);
config.json:
{
"clientId": "my id",
"guildId": "my id",
"token": "my token"
}
ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
return interaction.reply('Pong!');
},
};
I searched on the Internet, and even found something, but in an attempt to repeat this, the bot did not respond to commands, although it turned on calmly.

Related

Discord JS SlashCommandBuilder

I'm Currently trying to implement SlashCommandBuilder into my Discord Bot.
The bot is currently using prefix '!' and I want to remake it to work with the SlashCommandBuilder, The following code is what i have used and tested, as it pretty much works fine or looks like it's working fine I'm still having an issue caused when someone uses '/hello' It will give him Error 'The application did not respond'.
I did double check the API, Token and such using a Prefix as a check.
The Code does actually add the command to the discord and it looks in the lists of commands.
I'm also splitting the commands inside 'commands' folder.
index.js :
const Discord = require('discord.js');
const fs = require('fs');
const { Client, Collection } = require('discord.js');
const { REST } = require('#discordjs/rest');
const config = require('./config.json');
const { Routes } = require('discord-api-types/v9');
const client = new Client();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
client.commands = new Collection();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Bot is ready!');
const rest = new REST({ version: '9' }).setToken(config.token);
rest.put(
Routes.applicationCommands(client.user.id),
{ body: client.commands },
)
.then(() => console.log('Successfully registered commands'))
.catch(error => console.error(error));
});
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);
interaction.reply({ content: 'Error executing command', ephemeral: true });
}
});
client.login(config.token)
commands/hello.js
module.exports = {
name: 'hello',
description: 'Replys with Hi',
execute(interaction) {
interaction.reply({ content: 'Hi!' });
},
};
Please if anyone has information on why this was caused, i would love to listen.
Thank you for reading and appreciate any help or hints.

Command.execute is not a function

The error I get:
TypeError: command.execute is not a function
at Object.execute (C:\Users\lachl\Desktop\Coding\Discord Bot\src\events\client\interactionCreate.js:11:25)
at Client.<anonymous> (C:\Users\lachl\Desktop\Coding\Discord Bot\src\functions\handlers\handleEvents.js:15:63)
at Client.emit (node:events:513:28)
handleEvents.js file:
const fs = require("fs");
module.exports = (client) => {
client.handleEvents = async () => {
const eventFolders = fs.readdirSync(`./src/events`);
for (const folder of eventFolders) {
const eventFiles = fs
.readdirSync(`./src/events/${folder}`)
.filter((file) => file.endsWith(".js"));
switch (folder) {
case 'client':
for (const file of eventFiles) {
const event = require(`../../events/${folder}/${file}`);
if (event.once) client.once(event.name, (...args) => event.execute(...args, client));
else client.on(event.name, (...args) => event.execute(...args, client));
}
break;
default:
break;
}
}
};
};
interactionCreate.js file:
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
if (interaction.isChatInputCommand()) {
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 while executing this command...`,
ephemeral: true,
});
}
}
},
};
handleCommands.js file:
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");
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}`);
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
console.log(
`Command ${command.data.name} has passed through the handler`
);
}
}
const clientId = "1050985494537834606";
const guildId = "1041260203112411197";
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);
}
};
};
ping.js file:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription("Ping Command!"),
async exectute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true
});
const newMessage = `API LATENCY: ${client.ws.ping}\nClient Ping: ${message.createdTimeStamp - interaction.createdTimeStamp}`
await interaction.editReply({
content: newMessage
});
}
}
When I run the code, the bot goes online but when I try to run a command, it doesn't work
You misspelled execute in ping.js.

Discord.js cooldown not working, what should I do?

I want to create a cooldown for my team, but when using the command multiple times, the cooldown doesn't appear.
My code:
const fs = require('fs');
const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');
const Discord = require('discord.js');
const { Client, GatewayIntentBits, Collection} = require('discord.js');
const Timeout = new Discord.Collection();
const client = new Client({
intents: [
GatewayIntentBits['Guilds'],
GatewayIntentBits['GuildMessages'],
GatewayIntentBits['MessageContent']
]
});
const { prefix, token } = require('./config.json');
client.commands = new Discord.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);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
if (command) {
if(command.timeout) {
if(Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Осталось ждать \`${ms(Timeout.get(`${command.name}${message.author.id}`) - Date.now(), {long : true})}\`секунд!`)
command.run(client, message, args)
Timeout.set(`${command.name}${message.author.id}`, Date.now() + command.timeout)
setTimeout(() => {
Timeout.delete(`${command.name}${message.author.id}`)
}, command.timeout)
}
}
try {
client.commands.get(command).execute(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
And this is the command
const UnbelievaBoat = require('unb-api');
const unb = new UnbelievaBoat.Client('token');
const { EmbedBuilder} = require('discord.js');
module.exports = {
name: 'ферма1',
timeout: 15,
execute(client, message, args) {
...
I searched on this topic but I've still not found a way to make the cooldown work

How to move members between channels in Discord.js V 14

I need my Bot to move members between Channels. I recently upgraded to Discord.js Version 14 from Version 12.
My discord.js Version: 14.7.1
My node.js Version: 18.12.1
My main.js
const { Client, Events, GatewayIntentBits, Collection, ActivityType } = require("discord.js");
const fs = require("node:fs");
const path = require("node:path");
const { token } = require("./config.json");
const botIntents = [
GatewayIntentBits.Guilds,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildVoiceStates
];
const client = new Client({ intents: botIntents, partials: ["CHANNEL"] });
client.commands = new Collection();
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);
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
// Bot ready event
client.once(Events.ClientReady, (c) => {
console.log(`Logged in as ${c.user.tag}`);
c.user.setActivity("/help", { type: ActivityType.Watching });
});
// Message input to command
client.on(Events.InteractionCreate, async (interaction) => {
if (!(interaction.isChatInputCommand())) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!(command)) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
// ephemeral: true / private message, only visible to message sender (user)
await interaction.reply({ content: "There was an error while executing this command!", ephemeral: true });
}
});
client.login(token);
My working Code in Version 12.
module.exports = {
name: "my_name",
description: "my_description",
execute(message, args) {
const member = message.mentions.members.first();
if (!(args[1])) {
const embed = new Discord.MessageEmbed()
.setTitle("my_command")
.setColor(0x992d22)
.setDescription("my_description")
.setFooter(`Requested by ${message.author.tag}.`, message.author.displayAvatarURL);
message.channel.send(embed);
}
if (!member) return message.reply("enter a member name.")
if (!member.voice.channel) return message.reply("the member is not in a voice channel.");
if (!message.member.voice.channel) return message.reply("you need to join a voice channel first.");
message.channel.send("my_message");
member.voice.setChannel("my_channel_id");
}
}
I tried to get it to work in Version 14 like so.
module.exports = {
data: new SlashCommandBuilder()
.setName("my_name")
.setDescription("my_description")
.addUserOption((option) =>
option
.setName("member")
.setDescription("my_description")
.setRequired(true)
)
.setDMPermission(false),
async execute(interaction) {
const master = interaction.user.username;
const target = interaction.options.getUser("member");
const cageId = "my_channel_id";
if (!(interaction.member.voice.channel)) {
return await interaction.reply({ content: "You need to join a Voice-Channel first.", ephemeral: true });
}
if (!(target.voice.channelId)) {
return await interaction.reply({ content: "The Member is currently not in a Voice-Channel.", ephemeral: true });
}
await target.voice.setChannel(cageId);
const embed = new EmbedBuilder()
.setColor(0x992d22)
.setTitle("my_title")
.setDescription("my_description")
.setFooter({ text: `Requested by ${master}` })
.setTimestamp();
return await interaction.reply({ embeds: [embed] });
},
}
Problem
TypeError: Cannot read properties of undefined (reading 'setChannel')
TypeError: Cannot read properties of undefined (reading 'channelId')
I tried to Google it for quite some time, but i was not able to find a fitting solution.
Just a couple of little tweaks and you should have what you're looking for.
First, make sure that when you're starting your bot you are requesting the needed Intent GatewayIntentBits.GuildVoiceStates. Gateway Intents Documentation
Make certain that the option collected is the GuildMember:
const target = interaction.options.getUser("member");
to
const target = interaction.options.getMember("member");
Then when you are referencing the guild member, you need to specify that you're talking about the VoiceState:
if (!(target.channelId)) {
becomes
if (!(target.voice.channelId)) {
and
await target.setChannel(cageId);
becomes
await target.voice.setChannel(cageId);

Discordjs: How to fix execute is not defined?

I started making a music bot for my discord server when i input command for playing song it returns that execute is not defined i tried to fix but i had no success. That's why I am asking here.
Note: I made event and command handler but that is not the problem since it was also not working before implementing it.
Here is my code from event that happens on message aka starting command:
module.exports = (client, Discord, message)=>{
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split('/ +/');
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
//const ChannelName = message.channel.name;
try{
command.execute(args, cmd, client, Discord, message);
} catch(err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
And here is my code for play command:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
cooldown: 0,
description: 'Advanced music bot',
async execute(args, cmd, client, Discord, message){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`👍 **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}
I think that problem is in main part of code but I cant seem to find problem.
Here is code for command handling
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`../commands/${file}`);
if(command.name){
client.commands.set(command.name, command);
} else{
continue;
}
}
}
And here is my main file of the bot with commands collection
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
client.user.setStatus('online')
console.log('Bot is online!');
client.user.setActivity('Youtube',{
type:"LISTENING"
})
console.log('Servers:')
client.guilds.cache.forEach((guild) => {
console.log('-' + guild.name)
})
});
const fs = require('fs');
const message = require('./events/guild/message');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})

Resources