'Discord.js/javascript issue with a error. if (command ==='clear'). ReferenceError: command not defined
Every time an error pops up saying if(command==='clear') referencerError: command is not defined, although bot is going online but not responding to any instruction in discord bot. Thanks for help, in advance! i tried deleting if(command==='clear') whole section but then it showed the same error in the next play command which is one of the main command for music bot. i have also linked the youtube video which i was using as a reference for this code and i tried to do exactly what he said to do to code my discord bot. https://www.youtube.com/watch?v=3wJJDM7jUsk&list=RDCMUC08G-UJT58SbkdmcOYyOQVw&index=2
const Discord = require('discord.js');
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.once('ready',() =>{
console.log('Tihadi.io is online!');
} );
client.on('guildMemberAdd', guildMember => {
let welcomeRole = guildMember.guild.roles.cache.find(role => role.name ==='member');
guildMember.roles.add(welcomeRole);
guildMember.guild.channels.cache.get('783308287571132417').send(`Welcome <@$<{guildMember.user.id}> malik, To our server!`)
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commands = args.shift().toLowerCase();
if (command === 'clear') {
client.commands.get('clear').execute(message ,args);
}else if (command==='play') {
client.commands.get('play').execute(message ,args);
}else if (command==='leave') {
client.command.get('leave').execute(messsage ,args);
}
});
client.login('token');
Solution 1:[1]
In your code you define commands as a variable, but then you try and check command against some strings. You are also missing an s on one of your client.commands.get().
To fix this error you can do:
if (commands == 'clear') {
client.commands.get('clear').execute(message ,args);
}else if (commands == 'play') {
client.commands.get('play').execute(message ,args);
}else if (commands == 'leave') {
client.commands.get('leave').execute(messsage ,args);
}
Solution 2:[2]
this might help you!
client.commands = new Collection()
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
for(const file of commandFiles){
const commands = require(`./commands/${file}`)
client.commands.set(commands.name, commands)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pentium1080Ti |
| Solution 2 | Serg |
