Discord.js Cannot Read property 'run' of undefined - javascript

Im created a bot for discord using Discord.js, and every time I try to run my Bal command through my command handler it rejects it with the error Cannot read property 'run' of undefined
here is my code for Index.js
const Discord = require('discord.js');
const db = require("#replit/database")
const client = new Discord.Client();
const token = process.env.TOKEN;
const keep_alive = require('./keep_alive.js')
const PREFIX = "orb ";
const fs = require('fs');
const activities_list = [
"orb help.",
`${client.guilds.cache.size} servers!`,
"n 3^o7 !"
];
client.commands = new Discord.Collection();
const ecocommandFiles = fs.readdirSync('./ecocommands/').filter(file => file.endsWith('.js'));
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log("Orbitus online");
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index], { type: 'WATCHING' });
}, 30000);
});
//Command Handler\\
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 === 'bal'){
client.commands.get('bal').run(message, args, Discord);
}
});
client.login(token);
And here is my code for Bal.js
module.exports.run = async (message, args, Discord) => {
if(!message.content.startsWith(PREFIX))return;
let user = message.mentions.members.first() || message.author;
let bal = db.fetch(`money_${message.guild.id}_${user.id}`)
if (bal === null) bal = 0;
let bank = await db.fetch(`bank_${message.guild.id}_${user.id}`)
if (bank === null) bank = 0;
let moneyEmbed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`**${user}'s Balance**\n\nPocket: ${bal}\nBank: ${bank}`);
message.channel.send(moneyEmbed)
};
I really need help because I want to continue development on my bot.
Thanks for your time

so uuh , i think you should follow the official guide:
https://discordjs.guide/command-handling/
your's seems bit similar but maybe got from yt (etc)
anyway the issue is
you dont export name from Bal.js only run (function)
module.exports.run = .....
and as name is undefined
your here setting undefined as the key with your run function to client.commands (collection)
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
^^^^^^^^
}
now only key in the client.commands collection is undefined
client.commands.get('bal') this will come undefined as there is not command called bal in your collection (only undefined)
what you could do is add
module.exports.name = 'bal' into bal.js
every command from now on should have this (if you decide to use this way)
Again I would suggest you read the discord.js official guide as it very beginner friendly and has a command handler and dynamic command handling tutorials with additional features, I will leave the links down below if you need them :)
Links
Official-docs: Click-here
official guide (this is the official guide for beginners with d.js): Click-here
Command-Handling (guide): Click-here
Dynamic-Command-Handling(guide) : Click-here
Additional-Features) (guide): Click-here
Other guides:
Event handling (from the same official guide): Click-here
An-idiots-Guide (use jointly with the official guide): Click-here

Related

discord.js "TypeError: Cannot read property 'execute' of undefined" with async function in command file

I'm trying to add a command code under the command file, but i'm unable to get it to work. The problem arises at this line => if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message).
Without that line, the code works fine with the other 2 commands. I think it has to do with the async function but I'm not sure how to solve this problem. I don't want to include the whole chunk of code in the main file either, as it gets very long and cluttered. I'm new to coding, so it might be something I can't understand yet - please help me!
bot.js (the main .js file)
const { token, prefix } = require('./config.json');
const fs = require('fs');
const db = require('quick.db');
const ms = require('parse-ms-2')
const { Client, Intents, Message, Collection } = require("discord.js");
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.commands = new Discord.Collection();
// filter commands
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once("ready", () => {
console.log("online.");
client.user.setPresence({ activties: [{ name: 'with commands' }] });
})
client.on('messageCreate', async message => {
// definite command components
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase()
if (command == 'help' || command == 'h') {
client.commands.get('help').execute(message)
}
if (command == 'bal') {
client.commands.get('bal').execute(message)
}
if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message)
}
})
client.login(token)
chk.js (where the command is)
const db = require('quick.db')
const nm = require('parse-ms-2')
module.exports = {
name: "check in",
descrption: "daily check in rewards.",
async execute(message) {
let user = message.mentions.users.first() || message.author;
let daily = await db.fetch(`daily_${message.author.id}`);
let money = db.fetch(`money_${user.id}`);
let cooldown = 1000*60*60*20
let amount = Math.floor(Math.random() * 500) + 250
if (daily != null && cooldown - (Date.now() - daily) > 0) {
let time = ms(cooldown - (Date.now() - daily));
message.channel.send(`You have already collected the daily check in reward, please check in again in **${time.hours}h ${time.minutes}m ${time.seconds}s**`)
} else {
let embed = new Discord.MessageEmbed()
.setTitle('Daily Check In')
.setDescription(`Here is the amount collected today: ${amount}`)
.setColor('#ffc300')
message.channel.send({embeds: [embed]})
db.add(`money_${message.author.id}`, amount)
db.add(`daily_${message.author.id}`, Date.now())
}
}}
Cannot read property 'execute' of undefined"
Means client.commands.get('chk') is returning undefined.
Presumably, this means the chk command can't be found.
So, let's look at where you're setting the commands:
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
And let's check your chk.js file which is being imported.
module.exports = {
name: "check in",
// ...
What I can see is, you're exporting the module and setting the command with the name "check in" but later in the script, you're asking for a command called "chk". The command can't be found, returns undefined, and kills your code as it isn't handled.
The solution in this case is to just change your name property to "chk", or request client.commands.get("check in") instead.

How do I schedule a message from a Discord bot to send every Friday?

I'm very very new to programming and I'm trying to set up a basic discord bot that sends a video every Friday. Currently I have:
Index.js which contains:
const Discord = require("discord.js");
const fs = require("fs");
require("dotenv").config()
const token = process.env.token;
const { prefix } = require("./config.js");
const client = new Discord.Client();
const commands = {};
// load commands
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands[command.name] = command;
}
// login bot
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`);
});
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();
let cmd = commands[command];
if(cmd)
cmd.execute(message, args)
});
client.login(token);
and a commands folder which contains beeame.js and that contains:
module.exports = {
name: "beeame",
description: "b",
execute: (message) => {
message.channel.send("It's Friday!", { files: ["./beeame.mp4"] });
}
}
I have heard about cron jobs and intervals but I'm not sure how to add these to the code I currently have.
Any help would be super appreciated!
Nate,
Here's some basics, to get you started. Your existing project you showed, sets up your bot to handle messages whenever they arrive. Everything there stays as is. You want to add a new section to deal with the timers.
First, here's a snippet of a utility file having to deal with Cron Jobs:
const CronJob = require('cron').CronJob;
const job = new CronJob('* * * * *', function() {
const d = new Date();
console.log('At each 1 Minute:', d);
});
job.start();
the thing to study and pay attention to is the ' * * * ' area. You will want to understand this, to set the timing correctly.
so replace the console logging with your messages, set your timing correctly and you should be good to go. The other thing to remember is that wherever your bot is running, the time zone might be different than where you (or others are)...so you might need to adjust for that if you have specific time of day needs.
Edit:
Based on subsequent questions....and note, I didn't set the time right. you need to really do more research to understand it.
const cron = require('cron').CronJob;
const sendMessageWeekly = new cron('* * * * *', async function() {
const guild = client.guilds.cache.get(server_id_number);
if (guild) {
const ch = guild.channels.cache.get(channel_id_number);
await ch.send({ content: 'This is friendly reminder it is Friday somewhere' })
.catch(err => {
console.error(err);
});
}
});
sendMessageWeekly.start();

How do i make my discord bot respond to a message with prefix?

What I'm trying to do is set up a discord autoresponse bot that responds if someone says match prefix + respondobject like "!ping". I don't know why it doesn't come up with any response in the dispute. I've attached a picture of what it does. I can't figure out why it's not showing up with any responses in discord.
const Discord = require('discord.js');
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = '!'
client.on('ready', () => {
let botStatus = [
'up!h or up!help',
`${client.users.cache.size} citizens!`,
`${client.guilds.cache.size} servers!`
]
setInterval(function(){
let status = botStatus[Math.floor(Math.random() * botStatus.length)]
client.user.setActivity(status, {type: 'WATCHING'})
}, 15000);
console.log(client.user.username);
});
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()
const responseObject = {
"ping": `🏓 Latency is ${msg.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`
};
if (responseObject[message.content]) {
message.channel.send('Loading data...').then (async (msg) =>{
msg.delete()
message.channel.send(responseObject[message.content]);
}).catch(err => console.log(err.message))
}
});
client.login(process.env.token);
Your main issue is that you're trying to check message.content against 'ping', but require a prefix. Your message.content will always have a prefix, so you could try if (responseObject[message.content.slice(prefix.length)]).
Other alternatives would be to add the prefix to the object ("!ping": "Latency is...")
Or, create a variable that tracks the command used.
let cmd = message.content.toLowerCase().slice(prefix.length).split(/\s+/gm)[0]
// then use it to check the object
if (responseObject[cmd]) {}

Discord move bot

I'm trying to make a boot that, after entering the command >summon #nick, starts moving the user from one rooom to another, here's the problem:
CODE:
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild(client, Object);
module.exports = {
name: 'summon',
description: "Vyvolá člověka",
execute(message, args) {
const times = 6;
let i = 0;
const member = message.mentions.members.first();
const channel1 = message.guild.members.cache.get("689511445519794177");
const channel2 = message.guild.members.cache.get("774780272738566194");
if(member == null){
message.channel.send("Nezadal jsi uživatele!");
console.log("Špatné použití příkazu.");
} else {
Discord.GuildMember.setVoiceChannel(channel1);
message.channel.send("debug1");
Discord.GuildMember.setVoiceChannel(channel2);
message.channel.send("debug2");
}}
};
ERROR IS:
PS C:\Users\-----\Desktop\------\----> node .
MilanCXL je online!
C:\Users\----\Desktop\-----\------\commands\summon.js:26
Discord.GuildMember.setVoiceChannel(channel1);
^
TypeError: Discord.GuildMember.setVoiceChannel is not a function
at Object.execute (C:\Users\----\Desktop\----\-----\commands\summon.js:26:33)
at Client.<anonymous> (C:\Users\---\Desktop\----\-----\main.js:39:39)
Thanks for respond,
ancle FIX
Presumably you want member.setVoiceChannel(channel1) and not Discord.GuildMember.setVoiceChannel(channel1);?

How can I make my bot find the last message that matches a criteria, e.x ("joe") and send who sent it?

I am using node.js for my bot, and I, like the question stated, need to find the last message in the channel that matches the criteria specified in the code. For example, the command would say, ?joe, and it would find the last message that has "joe" in it, and return the member that sent it. In the server I am going to use it in, the message is very frequent, so I don't think it will hit any message reading limitations.
I did the code in main.js and the commands in separate js files, like this,
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('AbidBot 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 === 'ping'){
client.commands.get('ping').execute(message, args);
}
});
client.login();
The ping command looks like this:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!')
}
}
Thanks for your help!
EDIT #1
Thanks, but it does not seem to be working for me #Lioness100. Can you take a look?
module.exports = {
name: 'joe',
description: "find joe",
execute(message, args){
message.channel.messages.fetch().then((messages) => {
// find the message that has 'joe' in it
const author = messages.find({ content } => content.includes(' joe ')).author.tag;
message.channel.send(author);
}
});
}
You can use MessageManager.fetch() and Collection.find()
// fetch the last 100 messages in the channel
message.channel.messages.fetch({ limit: 100 }).then((messages) => {
// find the message that has 'joe' in it
const msg = messages.find(({ content }) => content.includes(' joe '));
return msg
? message.channel.send(msg)
: message.channel.send('None of the last 100 messages include the word `joe`!');
});

Categories

Resources