TypeError: command.execute is not a function when catching an error. Also, cooldown doesn't work. On Discord.js - javascript

I've been working on a Discord bot for a while and have implemented a cooldown command for a while too. It never works, and today i decided that i will try to fix it.
At first, it kept sending me an error message saying TypeError: command.execute is not a function and an error message on the channel, so i just removed catch (err) so it wont send that annoying message. But of course, doing that is perhaps the equivalent of removing a scratched limb.
Now that more people uses my bot, i was trying to rework on the cooldown feature, which is located on ../events/guild/message.js and it goes like this:
require('dotenv').config();
const Discord = require('discord.js');
const cooldowns = new Map();
module.exports = async (Discord, client, message) => {
if (message.author.bot) return;
const prefix = message.content.includes("nabe ") ? "nabe " : "n!"
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cmd = client.commands.get(command) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(message.channel.type === "dm")return message.channel.send("you can't use commands on dm")
if(cmd){
cmd.execute(client, message, args, Discord);
}else return
if(!cooldowns.has(command.name)){
cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = (command.cooldown) * 1000;
if(time_stamps.has(message.author.id)){
const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
if(current_time < expiration_time){
const time_left = (expiration_time - current_time) / 1000;
return message.reply(`wait **${time_left.toFixed(1)}** more seconds to do ${command.name} again.`).then(msg => { msg.delete({ timeout: 7000 }) });
}
}
time_stamps.set(message.author.id, current_time);
setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
try{
command.execute(message, args, cmd, client, Discord);
} catch (err){
message.reply("There was an error trying to execute this command.");
console.log(err);
}
}
How it was implemented on each command files:
module.exports = {
info: {
name: "command name",
description: "command description",
cooldown: 30,
},
async execute(client, message, args, Discord) {
/*code here*/
}
By the way, i got most of this code from CodeLyon on youtube, and here's the sourcebin.
Everytime i executed a command it will return the TypeError: command.execute is not a function error and an error message on the channel. I am aware that some people said that command.execute does not exist, but it works on the tutorial video, and i don't know any alternatives. And it probably won't even fix the cooldown anyway.
I will definitely really appreciate it if anybody can find a solution.
NodeJS 16.13.0, NPM 8.1.0, DiscordJS 12.5.3, Heroku server.

I am aware that some people said that command.execute does not exist
And they would be right. As you can see in your defined command:
module.exports = {
info: {
name: "command name",
description: "command description",
cooldown: 30,
},
You did not appear to specify an execute function in the command body. If you want to run the command, you need to do that:
module.exports = {
info: {
name: "command name",
description: "command description",
cooldown: 30,
execute: (client, message, args, Discord) => {
// command logic goes here
}
},
P.S I believe the sourcebin tutorial that you linked also included an execute function:

Related

Discord bot failing to call username of person who calls it

I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.

how to add aliases to a command handler in discord.js

I have found on other stack overflow questions that to add aliases you just have to add
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
but this doesn't work. What I don't understand is what cmd is because it is not defined anywhere else in my code although it is passed in through the arrow function anyway. When using this I can still use the commands but when I use the aliases nothing happens, no message or error in the console. Could anyone assist me on this, Thanks for any help. Here is my code for the command handler:
client.on('messageCreate', message => {
if (message.author.bot) return;
if (!message.content.startsWith(process.env.PREFIX)) return;
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!client.commands.has(commandName)) return;
if (message.channel.name == 'general') return message.reply('smh no bot commands in general :raised_hand:');
if (!message.guild.me.permissions.has('SEND_MESSAGES')) return message.member.send(`I need the 'SEND_MESSAGES' permission to be able to reply to commands in the server: ${message.guild.name}`);
try {
command.execute(message, args, distube);
} catch(error) {
console.error(error);
message.reply('Uh oh! It looks like you have encountered a glitch up in the system, please try again later! || <#498615291908194324> fix yo dead bot ||')
}
});
And the command file:
name: 'ping',
description: 'Ping Command',
aliases: ['pg'],
execute(message, args) {
let ping = new Date().getTime() - message.createdTimestamp
message.reply(`pong (${ping}ms)`);
}
This line is the problem
if (!client.commands.has(commandName)) return;
You map the collection in a <string, Object> format but the string is the command name, not the alias. The better way is replacing the above line of code with this:
if (!command) return;
This will return early if command is falsey (it was not found) but it will work with aliases.

discord bot not processing the command

I was adding some new commands to my discord v12 bot. But it's not responding to the code I typed. Any help is appreciated.
This section is inside index.js
client.admins = new discord.Collection();
const admins = fs.readdirSync('./custom/admin').filter(file => file.endsWith('.js'));
for (const file of admins) {
const admin = require(`./custom/admin/${file}`);
client.admins.set(admin.name.toLowerCase(), admin);
};
This is the code to process the above lines
if (message.author.bot || message.channel.type === 'dm') return;
const prefix = client.config.discord.prefix;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const admin = args.shift().toLowerCase();
const adm = client.admins.get(admin) || client.admins.find(adm => adm.aliases && adm.aliases.includes(admin));
if (adm) adm.execute(client, message, args);
And the function which I am trying the bot to do is named delete.js
module.exports = {
name: 'snap' ,
aliases: [],
category: 'admin',
utilisation: '{prefix}snap [number]',
execute(message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")
if (message.member.hasPermission('ADMINISTRATOR') ){
const {MessageAttachment} = require('discord.js');
const snaping = new MessageAttachment('./snap.gif')
message.channel.send(snaping)
setTimeout(snapCommand , 9000 ,args, message)
}
else
{
message.channel.send("-_- you are not an admin,Then why are you trying to use admin commands");
}
function snapCommand(args, message){
var del= args ;
del = parseInt(del , 10)
message.channel.bulkDelete(del+2);
}
}
}
when I launch the bot it shows no error msg, So that's a good sign I think, but when I use !snap 5
'!' which is my prefix. The bot does nothing. No error in the console also. Does anyone have any idea to solve this?
Never mind, I fixed it by adding client to the delete.js code
execute(client, message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")

Why does the purge command not work? (no errors) discord.js

Bot #1 (Eulogist Official Bot)
Bot #2 (Prosser Recoveries)
So here we have two of my bots. the purge command is:
const { MessageEmbed } = require("discord.js");
const config = require("../../config.json");
module.exports = {
config: {
name: "purge",
description: "Purges messages",
usage: " ",
category: "moderation",
accessableby: "Moderators",
aliases: ["clear", "prune"],
},
run: async (prosser, message, args) => {
message.delete();
let hrps = new MessageEmbed()
.setTitle(`**Command:** ${config["Bot_Info"].prefix}purge`)
.setDescription(
`**Aliases:** /prune, /clear\n**Description:** Delete a number of messages from a channel. (limit 100)\n**Usage:**\n${config["Bot_Info"].prefix}purge 20\n${config["Bot_Info"].prefix}bc`
)
.setColor();
let done = new MessageEmbed()
.setDescription(`Purged \`${args[0]}\` message(s). ✅`)
.setColor(`${config["Embed_Defaults"].EmbedColour}`);
if (!message.member.hasPermission("MANAGE_MESSAGES"))
return message.reply("Doesn't look like you can do that");
if (!args[0]) return message.channel.send(hrps);
message.channel.bulkDelete(args[0]).then(() => {
message.channel
.send(done)
.then((msg) => msg.delete({ timeout: 1000 }));
});
},
};
These two bots have the same purge command but only one of the bots command works. (i've checked perms & invited to different servers).
Has anyone got a solution for this?
Fixed! All i done was moved the js file to a different command folder and it suddenly worked.

Cannot read property 'xy' of undefined in Discord.js

My lock command is not working for some reason. It was working before and recently it has been annoying me. A terminal picture is below.
My code was working a month ago and now recently it has been acting up every time I add new code. I have compared my code from a month ago, only new code that I wrote was added.
const Discord = module.require("discord.js");
const fs =require("fs");
module.exports = {
name: "Timed Lockdown",
description: "Start a timed lockdown in a channel.",
run: async(client, message, args) => {
const time = args.join(" ");
if (!time) {
return message.channel.send("Enter a valid time period in `Seconds`, `Minutes` or `Hours`")
}
if (!message.member.hasPermission("MANAGE_SERVER", "MANAGE_CHANNELS")) {
return message.channel.send(`You don't have enough Permisions`)
}
message.channel.overwritePermissions([
{
id: message.guild.id,
deny : ['SEND_MESSAGES'],
},
],);
const embed = new Discord.MessageEmbed()
.setTitle("Channel Updates")
.setDescription(`${message.channel} has been locked for **${time}**`)
.setColor("RANDOM");
message.channel.send(embed)
let time1 = (`${time}`)
setTimeout(function(){
message.channel.overwritePermissions([
{
id: message.guild.id,
null: ['SEND_MESSAGES'],
},
],);
const embed2 = new Discord.MessageEmbed()
.setTitle("Channel Updates")
.setDescription(`Locked has been lifted in ${message.channel}`)
.setColor("RANDOM");
message.channel.send(embed2);
}, ms(time1));
message.delete();
}
}
You only have a run method in the object you're exporting from lock.js and you're calling execute in main.js.
You either need to update the method name in lock.js like this (and leave main.js as is:
module.exports = {
name: "Timed Lockdown",
description: "Start a timed lockdown in a channel.",
execute: async(client, message, args) => {
const time = args.join(" ");
// ... rest of code
Or call the run method in main.js like this:
if (command === "lock") {
client.commands.get("lock").run(message, args);
}

Categories

Resources