So I recently started developing a discord bot using discord.js, and when I'm trying to run this command, it is raising an error when I update the bot at the line where I execute the command (client.commands.get('kick').execute(message, args);).
The error is:
TypeError: Cannot read properties of undefined (reading 'get'
at Client.<anonymous> (C:\Users\Shushan\Desktop\discordbot\main.js:18:25)
at Client.emit (node:events:527:28) )
And here are my code files:
main.js
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '?';
client.once('ready', () => {
console.log("Shushbot is 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 === 'kick') {
client.commands.get('kick').execute(message, args);
}
})
client.login('SECURITY TOKEN');
kick.js
module.exports = {
name: 'kick',
description: 'This Command Kicks People!',
execute(message, args) {
const member = message.mentions.users.first();
if(member) {
const memberTarget = message.guild.members.cache.get(member.id);
memberTarget.kick();
message.channel.send("This User Has Been Kicked From The Server.");
} else {
message.channel.send("This User Couldn't Be Kicked.");
}
}
}
I think you should check that : https://discordjs.guide/creating-your-bot/command-handling.html#reading-command-files
So far, your bot (client) don't know the commands method, and even if he knows, get dosent exists at all.
You have to write some code to create and set these commands, exemple from doc :
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);
// 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);
}
You can do it that way or an other, but at this time your object is empty.
Even your client.commands is undefined !
Related
I'm working on discord.js bot V13 and I came across this error
Code:
client.commands = new Discord.Collection();
const cooldowns = 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.toLowerCase(), command);//Errors at command.name.toLowerCase()
}
Help With:
I just want to convert The string (command.name.toLowerCase()) but it sends an error i have also tried in VScode but it sends error there also error is same
Error:
TypeError: Cannot read property ‘toLowerCase’ of undefined
Any information please do not hesitate to ask.
Use .toLowerCase() in your event
Eg:
client.on("messageCreate", async message =>{
if(!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(' ')
const cmd = args[0].toLowerCase()
const command = client.commands.get(cmd)
if(!command) return;
try{
await command.execute(message, args)
} catch(e){
console.log(e)
}
})
My problem is the following: when compiling, I get the error that the property 'execute' is not defined. What I'm trying to do is open a file that is in another folder and dock it in the if, I was guided by the command handling documentation, I don't know if the error is in the other file which is called 'pong.js'. I recently started, so I don't fully understand it. The main code is as follows:
The Error error message
index.js file
const Discord = require('discord.js');
const client = new Discord.Client();
const keepAlive = require("./server")
const prefix = "!";
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./src').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./src/${file}`);
client.commands.set(command.name, command);
}
// ======== Ready Log ========
client.on ("ready", () => {
console.log('The Bot Is Ready!');
client.user.setPresence({
status: 'ONLINE', // Can Be ONLINE, DND, IDLE, INVISBLE
activity: {
name: '!tsc help',
type: 'PLAYING', // Can Be WHATCHING, LISTENING
}
})
});
client.on('message', async message => {
if(!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ");
let command = args.shift().toLowerCase()
if (command === "ping"){
client.commands.get('ping').execute(message, args)
}
})
const token = process.env.TOKEN;
keepAlive()
client.login(token);
pong.js file
module.exports.run = {
name: 'pong',
description: "pong cmd",
execute(message, args){
message.reply("pong!")
}
}
Hello I got an error with get command/definition cuz it's saying get command code is:
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});
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('Bot is 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 === 'embed'){
client.command.get('embed').execute(message, args, Discord)
}
}),
can someone help me with the undefined get command?
Ok I actually fix it changing command to commands but I got another error: Cannot read property 'execute' of undefined
As you already mentioned yourself you made a typo in the following line:
client.command.get('embed').execute(message, args, Discord)
Simply making it
client.commands.get('embed').execute(message, args, Discord)
should fix the error.
You later mentioned that an error saying 'Cannot read property 'execute' of undefined'
This simply means that the 'embed' command could not be found.
You set it to command.name earlier in the code, so check if the 'name' property in your embed command file is indeed set to 'embed'.
Providing additional code from the embed command file would be helpful if you can't fix this yourself.
here's my code:
//All of the constants
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./myconfig10.json');
const client = new Discord.Client();
const cheerio = require('cheerio');
const request = require('request');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
//Telling the bot where to look for the commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
let activities = [
'with ur dad',
'with ur mom',
]
const pickedActivity = Math.floor(Math.random() * (activities.length - 1) + 1)
//Once the bot is up and running, display 'Ready' in the console
client.once('ready', () => {
client.user.setPresence({
status: 'online',
activity: {
name: (pickedActivity),
type: 'STREAMING',
url: 'https://www.twitch.tv/monstercat'
}
})
console.log('Ready!');
//Seeing if the message starts with the prefix
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
//Telling the bot what arguments are
const args = message.content.slice(prefix.length).trim().split(/ +/)
const commandName = args.shift().toLowerCase();
//Checking to see if the command you sent is one of the commands in the commands folder
if (!client.commands.has(commandName)) return;
console.log(`Collected 1 Item, ${message}`)
const command = client.commands.get(commandName);
//Try to execute the command.
try {
command.execute(message, args);
//If there's an error, don't crash the bot.
} catch (error) {
console.error(error);
//Sends a message on discord telling you there was an error
message.reply('there was an error trying to execute that command!');
}})})
client.login(token);
but when i try this, i get the error:
UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied name is not a string.
I know this means that the name of the status needs to be a string, so how would I be able to make it a variable?
I'm pretty new to this so it would be appreciated if your answer was in simple enough terms.
Thanks!
I think this should do the trick. Replace:
const pickedActivity = Math.floor(Math.random() * (activities.length - 1) + 1)
with:
const pickedActivity = activities[Math.floor(Math.random() * activities.length)]
I'm Coding A Discord Bot In Javascript, For One of The Commands (!server, displays server name and total members), An error Keeps Popping up. my current Code Is ;
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('message', message =>{;
if(message.author.bot) return;
if (message.content.startsWith("!")){
const prefix = ("!")
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command == 'help'){
client.commands.get('!help').execute(message, args);
}
if(command == 'server'){
client.commands.get('!server').execute(message, args);
}
if(command == 'blacklist'){
client.commands.get('!blacklist').execute(message, args);
}
if(command == 'safe'){
client.commands.get('!safe').execute(message, args);
}
};
The Error Message is
client.commands.get('!server').execute(message, args);
^
TypeError: Cannot read property 'execute' of undefined
// !server.js File
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: '!server',
description: "!server",
execute(message, args){
message.react('💯')
const serverEmbed = new Discord.MessageEmbed()
serverEmbed.setTitle(`Server Stats`)
serverEmbed.addField("Server Name", message.guild.name);
serverEmbed.addField("Total Members", message.guild.memberCount);
serverEmbed.addField("Online Members", message.guild.members.cache.filter(member => member.presence.status !== "offline").size);
serverEmbed.addField("Offline Members", message.guild.members.cache.filter(member => member.presence.status == "offline").size);
message.channel.send(serverEmbed);
}
}
The Code Works For The Other 3 Commands Just Not !server. Any Help?