Discord.js command.name.toLowerCase() is not working - javascript

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)
}
})

Related

Cannot read properties of undefined (reading 'get') discord.js

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 !

Discord bot cannot send messages with slash commands

I am making a Discord bot using slash command, and i am stuck at this point. Here is the code of my index.js file
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);
}
})();
client.on('ready' , () => {
console.log('I am online')
client.user.setActivity('MUSIC 🎧', {type:'LISTENING'})
})
client.on('interactionCreate', async interaction => {
if(!interaction.isCommand())return
const command = interaction.commands.get(interaction.commandName);
if(!command)return
try {
await command.execute(interaction)
} catch (err) {
console.error(err)
await interaction.reply('There was an error trying to execute that command!')
}
})
And a ping.js file to send simple PING-PONG message.
const { SlashCommandBuilder } = require('#discordjs/builders')
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("PING-PONG"),
async execute (interaction) {
await interaction.reply("Pong!")
}
}
ERROR is:
const command = interaction.commands.get(interaction.commandName);
^
TypeError: Cannot read properties of undefined (reading 'get')
at Client.<anonymous> (C:\vs\Adele music bot\index.js:52:42)
at Client.emit (node:events:520:28)
Everything is fine, it registers slash commands but as soon as i use /ping it just shows the above error.
It seems like you have copied and pasted code from different places and just hoped it worked. The error means interaction.commands is undefined, which it is.
From what I can see, you wanted a Discord.Collection with all your interaction commands within. For the purposes of this, we will use client.commands.
Code sample
/* Create the collection */
client.commands = new Discord.Collection()
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());
/* Add data to the collection */
client.commands.set(command.name, command);
}
...
/* Get the command */
const command = client.commands.get(interaction.commandName);
const {Collection} = require('discord.js');
import the collection from discord package.
then after creating the client
client.commands = new Collection();
use the above snippet
then
const command = client.commands.get(interaction.commandName);
write this line where the error originates.
basically you first need to make a new collection of commands for the client.
then you need to add the data to add data to the collection but using below command.
client.commands.set();
then after this only you can use the get command
client.commands.set();

TypeError: cannot read property 'execute' of undefined discord.js

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!")
}
}

Undefined get discord.js node.js

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.

How to make the bot's status a variable

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)]

Categories

Resources