TypeError: Cannot read properties of undefined (reading 'execute') - discord.js

I have an error
CODE:
const prefix = '-';
import fs from 'fs'
client.commands = new DiscordJS.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.cjs'));
for(const file of commandFiles){
const command = import(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('messageCreate', (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 === `test`){
client.commands.get('test').execute(message, args);
}
});
My test.cjs CODE:
module.exports = {
name: 'test',
description: "This is a test",
execute(message, args){
message.channel.send('Test is working');
}
}
Does any1 know how to help??
The Console Error Message is
If any1 can help that would be amazing!
Have a good day!
https://i.stack.imgur.com/G6mOV.png

.cjs is CommonJS file, but your code can run on JavaScript.
Try changing your extension to .js.

Related

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

ReferenceError: message is not defined, how to solve?

I'm learning to code on discord.js so i may have gotten some things wrong, feel free to correct me if you find any issues. Right now this is the error I'm facing : ReferenceError: message is not defined
Here is the code :
const Discord = require('discord.js');
const client = new Discord.Client({
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES
]
});
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('This bot is online!');
});
client.on('message', message =>{
if (!message.content.startsWith(prefix) || message.author.client) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping'){
message.channel.send('pong!');
} else if (command == 'joe'){
message.channel.send('mama ;)');
} else if (command == 'deez'){
message.channel.send('NUTS!!');
} else if (command == 'ur'){
message.channel.send('mama');
} else if (command === 'kick'){
client.commands.get('kick').execute(message, args);
} else if (command === 'ban'){
client.commands.get('ban').execute(message, args);
}
});
client.login('token')
Everything works for me when I run your code. The reason you get the error might be the fact that message is deprecated in Discord v13 as seen here Updating from v12 to v13. But that wouldn't raise an error and would just show that (node:30426) DeprecationWarning: The message event is deprecated. Use messageCreate instead
Change your event in client.on('message') to client.on('messageCreate') and see if it works. It would help a lot more if you could post the whole error message here

Error: Cannot find module './commandsping.js'

I created a folder and added my ping.js file, now I am receiving this error. This is probably the easiest thing but I am completely stuck is there something I am doing wrong? Here is a image of how my folder looks, code is below.
Index.js file
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.commands = new Collection();
client.aliases = new Collection();
['command', 'event'].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
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);
}
});
for (const file of commandFiles) {
const command = require(`./commands${file}`);
client.commands.set(command.name, command);
}
you have made a mistake here. Change ./commands${file} to ./commands/${file}
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}

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)

Getting error 'commandFiles' has already been declared

I'm making an image bot for Discord servers but there's another problem:
'commandFiles' has already been declared.
Someone from here fixed it but not fully because a new problem came out. That's all of the script that is used for the image command, all the other stuff are just commands that have nothing to do with this and don't use 'commandFiles' in them.
Here's all of the script:
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.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);
}
if (command == 'youtube'){
client.commands.get('youtube').execute(message, args);
}
if (command == 'instagram'){
client.commands.get('instagram').execute(message, args);
}
});
client.commands = new Discord.Collection();
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'image':
image(message);
break;
}
});
function image(message){
var options = {
url: "http://results.dogpile.com/serp?qc=images&q=" + "cursed images",
method: "GET",
headers: {
"Accept": "text/html",
"User-Agent": "Chrome"
}
}};
client.on('ready', () =>{
console.log('This bot is online!');
})
request(options, function(error, response, responseBody){
if (error){
return;
}
$ = cheerio.load(responseBody);
var links = $(".image a.link");
var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href"));
console.log(urls);
if (!urls.length) {
return;
}
// Send result
message.channel.send( urls[Math.floor(Math.random() * urls.length)]);
});
Error screenshot:
All this error means is that the variable commandFiles has already been defined somewhere else in your code.
For example:
const commandFiles = 'foo';
const commandFiles = 'bar';
console.log(commandFiles);
JavaScript doesn't know which to use. I suggest searching for commandFiles and checking if there are more than one definition in your code.

Resources