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

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);
}

Related

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

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:

Can I use an if statement inside a try-catch method?

I'm using the guild.fetchVanityData() method to get a guild's vanity data in my Discord bot using the Discord.js library.
My invite.js command throws an error saying This guild does not have the VANITY_URL feature enabled.
I know that the guild does not have it enabled, and am sending a custom message to the user telling them that. Hence, I do not want it to throw an error. I'm using an if check in my message.js event file to swallow the error if the command executed is the invite command (The command throwing the error), using a return method. This does not seem to work as it still throws an error.
The only file in my entire bot in which I am using a try-catch is at the end of message.js.
My code is below, please help me out.
Message.js event file
module.exports = {
name: 'message',
execute(message, client) {
const prefixes = ['!1','833376214609690674', "<#!833376214609690674>","<#833376214609690674>"]
const prefix = prefixes.find(p => message.content.startsWith(p));
if (!prefix || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (message.content === "<#833376214609690674>" || message.content === "<#!833376214609690674>" || message.content === "833376214609690674" || message.content === "!1") {
const mCommand = client.commands.get('help')
mCommand.execute(message, args)
}
if (!client.commands.has(commandName)) return message.channel.send("Please provide a valid command.")
const command = client.commands.get(commandName);
try {
command.execute(message, args, client);
}
catch (error) {
if(command.name === "invite") {
return
}
else {
console.log(error)
}
}
},
};
Invite.js command file
const Discord = require('discord.js')
module.exports = {
name: 'invite',
category: "utility",
description: 'Get the bot invite or server invite info.',
execute: async (message, args) => {
if (args[0] === 'bot') {
const embed = new Discord.MessageEmbed()
.setTitle('Bot Invite')
.setDescription("Returns the bot's invite link.")
.addFields({
name: 'Invite',
value: "[Click here](https://discord.com/api/oauth2/authorize?client_id=833376214609690674&permissions=4294442710&scope=bot%20applications.commands) to invite the bot to your server."
})
message.channel.send(embed)
}
else if (args[0] === 'server') {
message.guild.fetchVanityData()
if (!message.guild.vanityURLCode) {
const embed = new Discord.MessageEmbed()
.setTitle('Server Invite')
.setDescription("Returns the server's Vanity URL if it has one.")
.addFields({
name: 'Vanity URL',
value: 'This server does not have a Vanity URL.',
inline: true
},
{
name: 'Uses',
value: 'Not Applicable',
inline: true
})
.setTimestamp()
return message.channel.send(embed)
}
const embed = new Discord.MessageEmbed()
.setTitle('Server Invite')
.setDescription("Returns the server's Vanity URL if it has one.")
.addFields({
name: 'Vanity URL',
value: `https://discord.gg/${message.guild.vanityURLCode}`,
inline: true
},
{
name: 'Uses',
value: `${message.guild.vanityURLUses}`,
inline: true
})
message.channel.send(embed)
}
}
}
I think this is all the code that is required, but if you wish to see my other commands, files, etc., you can go to this repl: https://replit.com/#smsvra6/MultiBot
According to discord.js documentation, <Guild>.fetchVanityData returns a Promise. Therefore, you can use <Promise>.then and <Promise>.catch syntax.
i.e.:
message.guild.fetchVanityData()
.then(data => {
// success, the server has a vanity url ;
})
.catch(error => {
// error, the server does not have a vanity url.
});
There is no need for an if statement.

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.

I'm trying to create a channel named like user args. [DISCORD.JS V12]

It just gives me an error that the function message.guild.channels.create does not work because it's not a correct name.
My intention is to create a command where you will be asked how the channel you want to create be named. So it's ask you this. After this you send the wanted name for the channel. Now from this the bot should name the channel.
(sorry for bad english and low coding skills, im a beginner)
module.exports = {
name: "setreport",
description: "a command to setup to send reports or bugs into a specific channel.",
execute(message, args) {
const Discord = require('discord.js')
const cantCreate = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`Can't create channel.`)
const hasPerm = message.member.hasPermission("ADMINISTRATOR");
const permFail = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`${message.author}, you don't have the permission to execute this command. Ask an Admin.`)
if (!hasPerm) {
message.channel.send(permFail);
}
else if (hasPerm) {
const askName = new Discord.MessageEmbed()
.setColor(' #4f6abf')
.setDescription(`How should the channel be called?`)
message.channel.send(askName);
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { max: 1, time: 10000 });
console.log(collector)
var array = message.content.split(' ');
array.shift();
let channelName = array.join(' ');
collector.on('collect', message => {
const created = new Discord.MessageEmbed()
.setColor('#16b47e')
.setDescription(`Channel has been created.`)
message.guild.channels.create(channelName, {
type: "text",
permissionOverwrites: [
{
id: message.guild.roles.everyone,
allow: ['VIEW_CHANNEL','READ_MESSAGE_HISTORY'],
deny: ['SEND_MESSAGES']
}
],
})
.catch(message.channel.send(cantCreate))
})
}
else {
message.channel.send(created)
}
}
}
The message object currently refers to the original message posted by the user. You're not declaring it otherwise, especially seeing as you're not waiting for a message to be collected before defining a new definition / variable for your new channel's name.
NOTE: In the following code I will be using awaitMessages() (Message Collector but promise dependent), as I see it more fitting for this case (Seeing as you're more than likely not hoping for it to be asynchronous) and could clean up the code a little bit.
const filter = m => m.author.id === message.author.id
let name // This variable will later be used to define our channel's name using the user's input.
// Starting our collector below:
try {
const collected = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
name = collected.first().content /* Getting the collected message and declaring it as the variable 'name' */
} catch (err) { console.error(err) }
await message.guild.channels.create(name, { ... })

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources