There was a post for this but it didn't seem to fix my problem. I'm writing a simple discord.js program and when I created a new command called forceverify, it gave the error "Cannot read property 'run' of undefined"
main.js:
const Discord = require('discord.js');
const client = new Discord.Client();
let fetch = require('node-fetch');
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('Loaded');
})
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 === 'help') {
client.commands.get('help').execute(message, args, Discord);
} else if (command === 'verify') {
client.commands.get('verify').execute(message, args, Discord);
} else if (command === 'forceverify') {
client.commands.get('forceverify').run(message, args, Discord);
}
})
client.on('guildMemberAdd', member => {
const welcomeChannel = client.channels.cache.find(ch => ch.name === 'member-log');
if (!welcomeChannel) {
console.log('No channel was found');
}
welcomeChannel.send(`Welcome!`);
client.login('The token is there');
forceverify.js
const { DiscordAPIError } = require("discord.js");
const fetch = require("node-fetch");
const packageData = require("../package.json");
module.exports = {
name: 'verify',
description: "Verify yourself to get access to the server",
execute(message, args, Discord) {
if (message.member.roles.cache.has('805210755800367104')) {
const clientUser = client.users.fetch(args[1]);
let myRole = message.guild.roles.cache.get("805531649131151390");
fetch(`https://api.sk1er.club/player/${args[0]}`)
.then(res => res.json())
.then(({ player }) => {
clientUser.member.setNickname(player.displayname).catch(console.error);
})
.catch(err => console.log(err));
} else {
message.channel.reply("You don't have sufficient permissions.");
}
}
}
Every other command works properly but for some reason, this one simply doesn't work. I tried what the other question said to do (which is add .execute to module.exports or change .execute to .run) neither worked probably because it simply can't find the file (everything was spelled correctly)
The export from forceverify.js has the name verify but it should be forceverify. So, the forceverify command isn't registered and client.commands.get('forceverify') returns undefined.
// commands/forceverify.js
module.exports = {
name: 'forceverify',
description: 'Force verify yourself to get access to the server',
execute(message, args, Discord) {
// do stuff
}
}
And you should call the execute function when invoking the command.
client.commands.get('forceverify').execute(message, args, Discord)
You can refactor your code to simplify the command invocation code.
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 (!client.commands.has(command)) {
return
}
client.commands.get(command).execute(message, args, Discord)
})
Related
I have such a question because I no longer know what to do. I have a BOT on Suggestion to a certain channel. When I run the bot via Visual Studio Code, the bot runs and everything works. But as soon as I load a boot on heroku.com, the program suddenly writes an error:
files = files.filter(f => f.endsWith(".js"))
Someone could help me, I would be very happy. Have a nice day
Index.js is here:
client.once('ready', () => {
console.log('Tutorial Bot is online!');
});
client.commands = new Discord.Collection()
const fs = require("fs")
fs.readdir("./commands/", (error, files) => {
files = files.filter(f => f.endsWith(".js"))
files.forEach(f => {
const command = require(`./commands/${f}`)
client.commands.set(command.name, command)
console.log(`Command ${command.name} was loaded!`)
});
});
client.on("message", message => {
if (message.author.bot) return;
if (message.channel.type === "dm") return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).split(" ")
const command = args.shift()
const cmd = client.commands.get(command)
if (cmd) {
cmd.run(client, message, args)
} else return;
});
bot.login(config.token);
Suggest.js is here
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "suggest",
aliases: [],
description: "Make a suggestion and have the community vote",
category: "utility",
usage: "suggest <suggestion>",
run: async (client, message, args) => {
let suggestion = args.slice(0).join(" ");
let SuggestionChannel = message.guild.channels.cache.find(channel => channel.name === "suggestions");
if (!SuggestionChannel) return message.channel.send("Please create a channel named suggestions before using this command!");
const embed = new MessageEmbed()
.setTitle("New Suggestion")
.setDescription(suggestion)
.setColor("RANDOM")
.setFooter(`${message.author.tag} | ID: ${message.author.id}`)
.setTimestamp()
SuggestionChannel.send(embed).then(msg => {
msg.react("👍🏼")
msg.react("👎🏼")
message.channel.send("Your suggestion has been sent!");
});
}
}
You forgot to check for errors in your callback. In case of an error files will be undefined, thus resulting in the error you've observed. So you should do something like:
fs.readdir("./commands/", (error, files) => {
if(error) {
// handle error
} else {
files = files.filter(f => f.endsWith(".js"))
files.forEach(f => {
const command = require(`./commands/${f}`)
client.commands.set(command.name, command)
console.log(`Command ${command.name} was loaded!`)
});
}
});
When I try to use !rps, discord shows me that there is no command and I get somethink like that in the console
I don`t know do I need to change something in my index.js code or in my rps.js code
https://imgur.com/sGjGR4t
const Discord = require('discord.js');
const fs = require('fs');
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });
client.command = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}/`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.command.set(command.name, command);
}
}
const prefix = '!';
client.once('ready', () => {
console.log('Bot jest online');
client.user.setActivity('Minecraft')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.command.has(commandName)) return;
const command = client.command.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Nie ma takiej komendy!')
}
});
client.login("TOKEN");
And the rps.js code, I tried to move rps.js to other folder but it does not solve the problem
const Discord = require('discord.js')
module.exports = {
name: "rps",
description: "rock paper scissors command",
usage: "!rps",
async run(bot, message, args) {
let embed = new Discord.MessageEmbed()
.setTitle("RPS")
.setDescription("React to play!")
.setTimestamp()
let msg = await message.channel.send(embed)
await msg.react("🗻")
await msg.react("✂")
await msg.react("📝")
const filter = (reaction, user) => {
return ['🗻', '✂', '📝'].includes(reaction.emoji.name) && user.id === message.author.id;
}
const chices = ['🗻', '✂', '📝']
const me = choices[Math.floor(Math.random() * choices.lenght)]
msg.awaitReactions(filter, { max: 1, time: 60000, error: ["time"] }).then(async (collected) => {
const reaction = collected.first()
let result = new Discord.MessageEmbed()
.setTitle("Result")
.addFields("Your Choice", `${reaction.emoji.name}`)
.addField("Bots choice", `${me}`)
await msg.edit(result)
if ((me === "🗻" && reaction.emoji.name === "✂") ||
(me === "✂" && reaction.emoji.name === "📝") ||
(me === "📝" && reaction.emoji.name === "🗻")) {
message.reply('You lost!');
} else if (me === react.emoji.name) {
return message.reply(`It's a tie!`);
} else {
return message.reply('You won!');
}
})
.catch(collected => {
message.reply('Process has been canceled, you failed to respond in time!');
})
}
}
In your rps.js file, you are defining the function to be run as run but in your index.js file, you are using the execute function so you can either change how you run the command in your main file or you can change the function name in your command file. Another place where you could get an error is the arguments you pass. In your main file, you are passing two arguments to your command file, message and args while in your command file, you are expecting three, bot, message and args. So you can either change the order of the arguments you pass or you can just remove the bot parameter in the command file:
(novice in coding, i just follow tutorials and try to understand and learn at the same time)
I recently wanted to code my own Discord bot but i had an issue with the event handler part so i tried another method but now i have another issue.
Instead of responding "pong" to "p!ping", it says :
client.commands.get('ping').execute(message, args);
^
TypeError: Cannot read property 'get' of undefined
at Object.execute (.../events/message.js:18:23)
at Client.<anonymous (.../main.js:19:44)
I also tried to replace
client.commands.get('ping').execute(message, args); with
client.commands.cache.get('ping').execute(message, args); or even client.commands.find('ping').execute(message, args); but it says "TypeError: Cannot read property 'get' of undefined - Discord bot" or even
Main file :
const Discord = require('discord.js');
const config = require('./config.json');
const {prefix, token} = require('./config.json')
const client = new Discord.Client();
client.commands = new Discord.Collection();
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
};
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// 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.name, command);
};
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);
client.on("ready", () => {
client.user.setPresence({
activity: {
name: 'p!',
type: 'WATCHING'
},status: 'idle'
});
});
Message.js:
const client = new Discord.Client();
const prefix = 'p!';
module.exports = {
name: 'message',
execute(message) {
console.log(`${message.author.tag} in #${message.channel.name} sent: ${message.content}`);
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 === 'help'){
client.commands.get('trick').execute(message, args);
}
}
};
ping.js:
module.exports = {
name: 'ping',
description: 'Ping!',
execute(message, args) {
message.channel.send('pong');
},
};
I hope that the informations i provided were helpful. If it's a small mistake such as a missing ; i'm sorry for wasting your time. Thank you in advance
I changed the
if (command === 'ping'){ with
if (command === `${prefix}ping`){
and it works, i think i just have to do that with all the commands.
If you have an easier solution please feel free to share it or if you found the issue with the code please tell me. (because before it worked without this modification),
thank you
found an easier way like that theres no need to type a new line ( if (command === 'ping'){ client.commands.get('ping').execute(message, args);)
this is what my
Message.js file looks like now :
const client = new Discord.Client();
client.commands = new Discord.Collection();
module.exports = (Discord, client, message) => {
const {prefix} = require('../config.json');
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const cmd = args.shift().toLowerCase ();
const command = client.commands.get(cmd) || client.commands.find (a => a.aliases && a.aliases.includes(cmd));
if(command) command.execute(client, message, args, Discord);
};
I'm building a discord bot and I want to save information in bdays.json but this error pops up. All other commands are working just fine but I am getting this error:
TypeError: Cannot read property 'execute' of undefined
What should I do?
main.js
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('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 === 'jsidement') {
client.commands.get('ping').execute(message, args);
} else if (command === 'help') {
client.commands.get('help').execute(message, args, Discord);
} else if (command === 'mute') {
client.commands.get('mute').execute(message, args);
} else if (command === 'unmute') {
client.commands.get('unmute').execute(message, args);
} else if (command === 'remember') {
client.commands.get('remember').execute(message, args);
}
})
client.login('Token');
and remeber.js
module.exports = {
name: 'remeber',
description: 'this is a remember command!',
execute(message, args){
const fs = require('fs');
client.bdays = require ('./bdays.json');
client.bdays [message.author.username] = {
message: message.content
}
fs.writeFile('./bdays.json', JSON.stringify (client.bdays, null, 4), err => {
if(err) throw err;
message.channel.send('Saved!');
});
}
}
What should I do?
You have a typo in your code...
In remeber.js you give the command the name of remeber but then in your main.js file you use client.commands.get('remember').execute(message, args);
To fix it, use either:
// remember.js
module.exports = {
name: 'remember',
description: 'this is a remember command!',
execute(message, args){
const fs = require('fs');
client.bdays = require ('./bdays.json');
client.bdays [message.author.username] = {
message: message.content
}
fs.writeFile('./bdays.json', JSON.stringify (client.bdays, null, 4), err => {
if(err) throw err;
message.channel.send('Saved!');
});
}
}
Or replace the line with the typo with this instead:
client.commands.get('remeber').execute(message, args);
I am making a discord bot that has a command where it will tell you every bodies invites from greatest to least in the discord server. This is the code I have but I don't know why it isn't working.
module.exports = {
name: 'invites',
description: 'invite command',
callback: (message) => {
const { guild } = message;
guild.fetchInvites().then((invites) => {
const inviteCounter = {};
invites.forEach((Invite) => {
const { uses, inviter } = Invite;
const { username, discriminator } = inviter;
const name = `${username}#${discriminator}`;
inviteCounter[name] = (inviteCounter[name] || 0) + uses;
});
let replyText = 'invites:';
for (const invite in inviteCounter) {
const count = inviteCounter[invite];
replyText += `\n${invite} has invited ${count} member(s)!`;
}
message.reply(replyText);
});
},
};
This is my command handler, i have 2 other commands that i know work and I've been changing the invite command some cause I cant get it to work.
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('Baysides-utilities 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 === 'ticket'){
client.commands.get('ticket').execute(message, args, client, fs);
}
if(command === 'invites'){
client.commands.get('invites');
}
if(command === 'grow'){
client.commands.get('grow').execute(message, args, client, fs);
}
});
client.login('I have it in the code just not showing it here');