TypeError: Cannot read property 'execute' of undefined / Embeds - discord.js

When i'm doing a discord bot i have this problem client.commands.get('embed').execute(message, args, Discord);
^
TypeError: Cannot read property 'execute' of undefined
at Client. (C:\Users\anton\Desktop\Bot\index.js:29:37)
at Client.emit (node:events:376:20)
at MessageCreateAction.handle (C:\Users\anton\Desktop\Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\anton\Desktop\Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\anton\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\anton\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\anton\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\anton\Desktop\Bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:376:20)
at Receiver.receiverOnMessage (C:\Users\anton\Desktop\Bot\node_modules\ws\lib\websocket.js:825:20)
This is the code :
const client = new Discord.Client();
const prefix = ',';
const fs = require('fs');
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.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity('this awesome server', { type: 'WATCHING'}).catch(console.error);
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'embed'){
client.commands.get('embed').execute(message, args, Discord);
}
if(command === 'version'){
client.commands.get('version').execute(message, args);
}
});
client.login('My token');```
And the command code:
module.exports = {
name: 'version',
description: "this is the version command",
execute(message, args, Discord){
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#e62e1e')
.setTitle('Leon')
.setDescription('Almost Finished')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Something', value: 'Nothing', inline: true },
{ name: 'Something', value: 'Nothing', inline: true },
)
.setTimestamp()
.setFooter('See Leon');
message.channel.send(exampleEmbed)
}
}

It seems that you didn't import discord.js.
This is how to do it: place this at the very top:
const Discord = require('discord.js');

Related

TypeError: command.execute is not a function

I am aware that this problem has been discussed already, but I don't seem to fit the solutions found into my code. I've created some commands to this bot and they seem to work, although they are only basic slash commands (e.g. /ping). This problem came in when I try to run a moderation command or a play command.
This is the code with the error
const { Interaction } = require("discord.js");
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, client);
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
None of the fixes that I found seem to fit, at least to my rather unexperienced eye.
The command I try to run is this:
const { SlashCommandBuilder } = require("#discordjs/builders")
const { MessageEmbed } = require("discord.js")
const { QueryType } = require("discord-player")
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Asculta muzica")
.addSubcommand((subcommand)=>
subcommand
.setName("song")
.setDescription("Incarca o singura melodie printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul melodiei").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("playlist")
.setDescription("Incarca un playlist printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul playlist-ului").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("search")
.setDescription("Cauta o melodie pe baza cuvintelor-cheie")
.addStringOption((option) =>
option.setName("searchterms").setDescription("the search keywords").setRequired(true))),
run: async ({ client, interaction }) => {
if (interaction.member.voice.channel)
return interaction.editReply("Trebuie sa fii pe un voice channel pentru a folosi aceasta comanda!")
const queue = await client.player.createQueue(interaction.guild)
if (!queue.connection) await queue.connect(interaction.member.voice.channel)
let embed = new MessageEmbed()
if (interaction.options.getSubcommand() === "song"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_VIDEO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
} else if (interaction.options.getSubcommand() === "playlist"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_PLAYLIST
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const playlist = result.tracks
await queue.addTrack(result.tracks)
embed
.setDescription(`**${result.tracks.length} melodii din [${playlist.title}](${playlist.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${playlist.duration}`})
} else if (interaction.options.getSubcommand() === "search"){
let url = interaction.options.getString("seatchterms")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
}
if (!queue.playing) await queue.play()
await interaction.editReply({
embeds: [embed]
})
}
}
and the corresponding error:
TypeError: command.execute is not a function
at Object.execute (C:\Users\shelby\Bot\src\events\interactionCreate.js:15:27)
at Client.<anonymous> (C:\Users\shelby\Bot\src\functions\handelEvents.js:8:58)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\shelby\Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
at module.exports [as INTERACTION_CREATE] (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:489:22)
at WebSocketShard.onMessage (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:328:10)
at callListener (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:290:14)
at WebSocket.onMessage (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:209:9)
You should be using command.run() instead of command.execute(), as your exported Slash Command uses this property name to store the core function.
const { Interaction } = require("discord.js");
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.run({ interaction, client });
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
Additionally, you have to use an object that contains your interaction and client to run the function instead of using two arguments.

Discord.js V14 Bot Ping CMD

I am new to coding I was just making a simple ping command when I went to run it I got this error I have tried fixing it but I can't seem to find the problem please help me! I have been following this video (https://www.youtube.com/watch?v=6IgOXmQMT68&list=PLv0io0WjFNn9LDsv1W4fOWygNFzY342Jm&index=1).
ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Return my ping!'),
async execute(interaction, client) {
const messsage = await interaction.deferReply({
fetchReply: true
});
const newMessage = `API Latency: ${client.ws.ping}\nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}`
await interaction.editReply({
content: newMessage
});
}
}
handleEvents.js:
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:
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,
});
}
}
},
};
Error:
TypeError: command.execute is not a function
at Object.execute (C:\Users\mikay\OneDrive\Desktop\v14 Bot\src\events\client\interactionCreate.js:11:23)
at Client.<anonymous> (C:\Users\mikay\OneDrive\Desktop\v14 Bot\src\functions\handlers\handleEvents.js:20:23)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:81:12)
at Object.module.exports [as INTERACTION_CREATE] (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:480:22)
at WebSocketShard.onMessage (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:320:10)
at WebSocket.onMessage (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:513:28)
Remove await on 11
commands.set(command.data.name, commands);
remove s from the last command

discord js v13 message reply don't work (prefix)

I was making discord bot that reply the user word with prefix.
example the user said !Hello the bot will reply with Hello
The error was
(node:11208) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use node --trace-deprecation ... to show where the warning was created)
So I changed the code message to messageCreate but the bot didn't reply either and have no error in the console log what should I change the code of my script?
this is the source code
prefix is ! (It is in the config.json)
index.js
const {Client,Intents,Collection} = require("discord.js");
const client = new Client ({intents:[Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES,Intents.FLAGS.GUILD_MEMBERS]})
const fs = require("fs");
const { token, prefix } = require("./config.json");
client.commands = new Collection();
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
var data = []
for(const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
data.push({name:command.name,description:command.description,options:command.options});
}
client.once('ready', async () =>{
console.log(`Logged in as ${client.user.tag}`)
// await client.guilds.cache.get('874178319434801192')?.commands.set(data)
setInterval(() => {
const statuses = [
'mimc!',
'wtf',
'prefix = !'
]
const status = statuses[Math.floor(Math.random()*statuses.length)]
client.user.setActivity(status, {type: "PLAYING"})
}, 10000)
});
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();
if(!client.commands.has(command)) return;
try{
client.commands.get(command).execute(message, args);
}
catch(error){
console.error(error);
}
});
client.login(token)
Hello.js (in the folder of commands)
module.exports = {
name: "Hello",
description: "Say Hi",
execute(message) {
return message.channel.send(`${message.author}, Hello.`)
},
};
The code of index.js (or main file) goes by:
const {Client, Intents, MessageEmbed, Presence, Collection, Interaction}= require ('discord.js')
const client = new Client({intents:[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]})
const TOKEN = ''// get your TOKEN!
const PREFIX = '!'
const fs = require('fs')
client.commands = 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);
}
client.on('ready', ()=> {
console.log('🕐 I am online!!')
client.user.setActivity('A GAME ', {type: ('PLAYING')})
client.user.setPresence({
status: 'Online'
})
})
client.on('message', message => {
if(!message.content.startsWith(PREFIX)|| message.author.bot) return
const arg = message.content.slice(PREFIX.length).split(/ +/)
const command= arg.shift().toLowerCase()
if (command === 'ping'){
client.commands.get('ping').execute(message,arg)
}
})
client.login(TOKEN)
After making a folder commands, add a new .js file, and name it as ping.js
The code for ping.js goes by -
module.exports={
name:'ping',
execute(message, arg){
message.reply('hello!!')
}
}

Discord.js - Discord bot stopped responding to commands

I was trying to add some new features to my bot, and it didn't end up working. So I removed the new code, and now it won't respond to any commands. It's still online but as I said earlier, it's completely unresponsive. I've looked through the code and I can't find the issue. I'm still new to coding bots so I'm probably missing something.
Here's my main code file:
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
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('message', message => {
console.log(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;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
And here's a command file:
function pickOneFrom(array) {
function pickOneFrom(array) {
return array[Math.floor(Math.random() * array.length)];
}
module.exports = {
name: 'throw',
description: 'this is a throw command!',
execute(message, args) {
const responses = ['a apple', 'a melon', 'a potato', 'a snowball', 'a spanner', 'a computer'];
message.channel.send(
`${message.author} threw ${pickOneFrom(responses)} at ${
message.mentions.users.first() ?? 'everyone'
}!`,
);
},
};```
After looking your code I see that you didn't import fs file system to reading commands files to import so you should add it into your code
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
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('message', 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;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
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('message', 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;
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);
You forgot to add client at client.commands.get(command).execute(message , args)

discord.js embeds not working through a command handler

So im new to coding a discord bot and have been watching CodeLyons tutorials.
Im quite Confused As My Embeds Wont Work Through The Command Handler, Someone Help Please.
My embed is pretty simple and is shown working through the command handler in the tutorials
my command prompt error is shown here:
TypeError: Cannot read property 'execute' of undefined
at Client.<anonymous> (J:\J_Desktop\discord\DiscordBot\main.js:32:37)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (J:\J_Desktop\discord\DiscordBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (J:\J_Desktop\discord\DiscordBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (J:\J_Desktop\discord\DiscordBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (J:\J_Desktop\discord\DiscordBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (J:\J_Desktop\discord\DiscordBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (J:\J_Desktop\discord\DiscordBot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (J:\J_Desktop\discord\DiscordBot\node_modules\ws\lib\websocket.js:797:20)
Bot File:
const Discord = require('discord.js');
const Client = new Discord.Client();
const token = ''
const prefix = '¬';
const fs = require('fs');
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('Online');
});
Client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
Client.commands.get('ping').execute(message, args);
} else if (command == 'rick') {
Client.commands.get('rickroll').execute(message, args);
} else if (command == 'embed') {
Client.commands.get('embed').execute(message, args, Discord);
}
});
Client.login(token);
Command File
module.exports = {
name: 'Embedded Rickroll',
description: 'Nil',
execute(message, args, Discord) {
const newEmbed = new Discord.messageEmbed()
.setColor('#00CED1')
.setTitle('You Know The Rules, And So Do I!')
.setURL('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
.setDescription('Were No Strangers To Love')
.addImage('https://i.imgur.com/dVz9Iuc.png')
.setFooter('Im So Sorry');
message.channel.send(newEmbed);
}
}

Resources