Discord.js ReferenceError: message is not defined - node.js

I am trying to make a command to clear messages in my discord and I receive the error message is not defined. Above the error inside of the terminal there is one specific portion under my return for the first line with it, there is an arrow pointing up to it.
Here is my code for the main portion
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('Codelyon 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);
}
else if(command == 'ouryoutube') {
client.commands.get('youtube').execute(message, args);
}
else if(command == 'clear') {
client.commands.get('clear').execute(message, args);
}
});
Here is my code for the command
module.exports = {
name: 'clear',
description: "Clear Messages",
execute(messages, args) {
if(!args[0]) return message.reply("You must enter the number of messages you want to clear");
if(isNaN(args[0])) return message.reply("Please Enter a Real Number.");
if(args[0] > 100) return message.reply("You can't delete more then 100 messages");
if(args[0] < 1) return message.reply("You must delete at least one message");
}
}
Thank you any help is appreciated! :)

You have a typo in execute(messages, args) {...}. The first argument should be message.
execute(message, args) {
// code
}

Related

awaitMessages from the user on discord.js

I am trying to make a system that makes a user enter a code(like a verification code sent to the dms) before doing the action. I am trying to understand how my code can wait for the code to be entered, and I came across the awaitMessages tag. I am trying to understand how I can use it properly in my code. Here is my code.
const Discord = require("discord.js");
const config = require("./config.json");
const { MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING"], partials: ['CHANNEL',] })
const RichEmbed = require("discord.js");
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "news") {
if (message.channel.type == "DM") {
message.author.send(" ");
}
}
if (command === "help") {
message.author.send("The help desk is avaliable at this website: https://example.com/");
}
});
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.channel.send(`Pong! This message had a latency of ${timeTaken}ms.`);
}
if (command === "delete all messages") {
const timeTaken = Date.now() - message.createdTimestamp;
const code = Math.random(1,1000)
message.channel.send(`Executing command. Verification Required.`);
message.author.send(`Your code is the number ${code}.`)
message.channel.send(`Please confirm your code. The code has been sent to your dms. Confirm it in here.`)
message.channel.awaitMessage(code) {
message.channel.send('confirmed. Doing the action.')
}
}
});
client.login(config.BOT_TOKEN)
To wait for a response from the user, you can use a collector.
You can create a filter to see if the user sending the code is the same as the one who executed the command and if the code sent is correct
const filter = (msg) => msg.author.id === message.author.id && msg.content === code;
const collector = message.channel.createMessageCollector({
filter,
time: 60000,
});
collector.on('collect', (collectedMessage) => {
collector.stop('success');
message.channel.send('confirmed. Doing the action.')
});
collector.on('end', (collected, reason) => {
if (reason === 'success') return;
else message.channel.send('Timeout or error');
});

Is it possible to disable people pinging #everyone and #here using "say" command on discord bot?

I've tried a few methods to stop people from pinging everyone but what i want is something where if the message has "#everyone" or "#here" i can make the bot reply a few different ways
here is my current code
const Discord = require ('discord.js');
const { FILE } = require('dns');
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('IM ONLINE GUYS!!!');
});
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);
} else if (command == 'pong'){
client.commands.get('pong').execute(message, args);
} else if (command == 'help'){
client.commands.get('help').execute(message, args, Discord);
} else if (command == 'kill'){
client.commands.get('kill').execute(message, args);
} else if (command == 'quote'){
client.commands.get('quote').execute(message, args);
} else if (command == 'kiss'){
client.commands.get('kiss').execute(message, args);
} else if (command == 'hug'){
client.commands.get('hug').execute(message, args);
} else if (command == 'pet'){
client.commands.get('pet').execute(message, args);
} else if (command === 'say'){
const sayMessage = message.content.split(' ').slice(1).join(' ');
message.channel.send(sayMessage);
} else if (command === 'music-h'){
client.commands.get('music-h').execute(message, args, Discord)
}
})
client.login('token')
and i am refering to the
} else if (command === 'say'){
const sayMessage = message.content.split(' ').slice(1).join(' ');
message.channel.send(sayMessage);
part
Im going to explain it better here: I am trying to make the bot respond with something else when someone pings #everyone or #here in their ".say" message
example:
".say #everyone"
"Nice try bub, its not gonna work with me"
and maybe a couple other responses along with that.
Yes of course!
if (message.content.includes('#everyone') || message.content.includes('#here')) {
message.channel.send('Nice try bub, its not gonna work with me')
Let me know if you need further help, cheers!

discord.js TypeError "Cannot read property 'execute' of undefined"

I get the "Cannot read property 'execute' of undefined"
this is the command in the index.js file
const Discord = require("discord.js")
const client = new Discord.Client()
const config = require("./config.json")
const fs = require("fs")
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./cmds/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./cmds/${file}`)
client.commands.set(command.name, command)
}
//client.on//
client.on('ready', () =>{
console.log("The client is ready!")
})
let prefix = config.prefix;
client.on("message", (message) => {
if(message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'pnig') {
client.commands.get('ping').execute(message, args);
}
});
client.login(config.token)
and this is the one on the ping.js one
const discord = require("discord.js")
module.exports = {
name: 'ping',
description: 'pong?',
execute(message, args) {
message.channel.send('pong!')
}
}
can you tell me whats wrong with my code?
The error to your code is actually the wrong spelling. You see, you put pnig instead of ping which makes the exception handling say that .execute isn't defined.
if(command === 'pnig') {
client.commands.get('ping').execute(message, args);
}
The simple fix to this is the following:
if(command === 'ping') {
client.commands.get('ping').execute(message, args);
}
Hope you enjoy!

How can you make a "say" command on discord.js?

I've been making a discord bot recently with a few features, this bot has an advanced command handler and i was wondering how to make a command where the bot says what you tell it to.
example:
".say (message)"
bot responds with "(message)"
this is my command handler
const Discord = require ('discord.js');
const { FILE } = require('dns');
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('alpha 0.2.9, IM 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);
} else if (command == 'pong'){
client.commands.get('pong').execute(message, args);
} else if (command == 'help'){
client.commands.get('help').execute(message, args, Discord);
} else if (command == 'kill'){
client.commands.get('kill').execute(message, args);
} else if (command == 'quote'){
client.commands.get('quote').execute(message, args);
} else if (command == 'kiss'){
client.commands.get('kiss').execute(message, args);
} else if (command == 'hug'){
client.commands.get('hug').execute(message, args);
} else if (command == 'pet'){
client.commands.get('pet').execute(message, args);
} else if (command == 'bruh'){
client.commands.get('bruh').execute(message, args);
}
})
client.login('no')
No tutorials exist on how to do this with an advanced command handler
right now the bot is for fun but i might make it into moderation.
Use a combination of String#split(), Array#slice() and Array#join()
else if (command === 'say') {
const sayMessage = message.content.split(' ').slice(1).join(' ');
message.channel.send(sayMessage);
}

I want to add PermLvl to my index.js -- DISCORD.JS

So, recently i started making my own bot, Im not the most experienced person too, but I know a bit of what im doing. I went off the basic Discord.js index provided on Discord.js Guide, and just added my own code to it, without actually touching the command handler.
For some commands I wanted to have a perm level that only with that perm level
permlvl 1 = Manage Message
^ not actual code just an example, That way only users with that perm level can use it.
Here is my index.js At the moment.:
const Discord = require('discord.js');
const config = require('./commands/config.json');
const fs = require('fs');
const { dir } = require('console');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const Fun = fs.readdirSync(`./commands/Fun/`).filter(file => file.endsWith('.js'));
for (const file of Fun) {
const command = require(`./commands/Fun/${file}`);
client.commands.set(command.name, command);
}
const General = fs.readdirSync(`./commands/General/`).filter(file => file.endsWith('.js'));
for (const file of General) {
const command = require(`./commands/General/${file}`);
client.commands.set(command.name, command);
}
const Information = fs.readdirSync(`./commands/Information/`).filter(file => file.endsWith('.js'));
for (const file of Information) {
const command = require(`./commands/Information/${file}`);
client.commands.set(command.name, command);
}
client.elevation = message => {
if (message.channel.type === 'dm') return;
let permlvl = 0;
if (message.member.hasPermission("MANAGE_MESSAGES")) permlvl = 1;
if (message.member.hasPermission("BAN_MEMBERS")) permlvl = 2;
if (message.member.hasPermission("MANAGE_GUILD")) permlvl = 3;
if (message.member.id === message.guild.ownerID) permlvl = 4;
if (message.author.id === config.devID) permlvl = 5;
return permlvl;
};
client.on("ready", () => {
console.log(`${client.user.tag} has started, with ${client.users.cache.size} users, in ${client.channels.cache.size} channels of ${client.guilds.cache.size} guilds.`);
client.user.setActivity(`Serving ${client.users.cache.size} users in ${client.guilds.cache.size} server.`, { url: 'https://www.twitch.tv/discordsstream', type: 'STREAMING' });
)};
client.on('message', message => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
const args = message.content.slice(config.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 (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${config.prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
with the exception of my other client.on and some of the main code in client.on and stuff at the bottom. This is everything having to do with the command handler in the index, Here is the config in the actual commands:
module.exports = {
name: 'ping',
description: 'See the bots response time!',
usage: '',
guildOnly: false,
permLevel: 0,
aliases: ['responsetime', 'pong'],
execute(message, args, async) {
}
The thing is, It works with 0 errors when the command is run, But the permlvl doesnt work,
I tried adding it the the "say" command as only permlvl 1 which is
if (message.member.hasPermission("MANAGE_MESSAGES")) permlvl = 1;
but members could still use it. -- They dont have the permissions on their roles either.
I tried a few things with the config, I tried replacing it with AwesomeCommandHandler, in which that code it didnt work, So i reverted back. I searched a few discord.js sites, And some Stack Questions, but no where could I find the answer, itd be great if someone could help me, Either in finding the answer or giving it, Either way.
You also need to check if the user permLevel is higher or equal to the command one:
const Discord = require('discord.js');
const config = require('./commands/config.json');
const fs = require('fs');
const { dir } = require('console');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const Fun = fs.readdirSync(`./commands/Fun/`).filter(file => file.endsWith('.js'));
for (const file of Fun) {
const command = require(`./commands/Fun/${file}`);
client.commands.set(command.name, command);
}
const General = fs.readdirSync(`./commands/General/`).filter(file => file.endsWith('.js'));
for (const file of General) {
const command = require(`./commands/General/${file}`);
client.commands.set(command.name, command);
}
const Information = fs.readdirSync(`./commands/Information/`).filter(file => file.endsWith('.js'));
for (const file of Information) {
const command = require(`./commands/Information/${file}`);
client.commands.set(command.name, command);
}
client.elevation = message => {
if (message.channel.type === 'dm') return;
let permlvl = 0;
if (message.member.hasPermission("MANAGE_MESSAGES")) permlvl = 1;
if (message.member.hasPermission("BAN_MEMBERS")) permlvl = 2;
if (message.member.hasPermission("MANAGE_GUILD")) permlvl = 3;
if (message.member.id === message.guild.ownerID) permlvl = 4;
if (message.author.id === config.devID) permlvl = 5;
return permlvl;
};
client.on("ready", () => {
console.log(`${client.user.tag} has started, with ${client.users.cache.size} users, in ${client.channels.cache.size} channels of ${client.guilds.cache.size} guilds.`);
client.user.setActivity(`Serving ${client.users.cache.size} users in ${client.guilds.cache.size} server.`, { url: 'https://www.twitch.tv/discordsstream', type: 'STREAMING' });
)};
client.on('message', message => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
const args = message.content.slice(config.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 (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${config.prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
const userPermLevel = client.elevation(message);
const commandPermLevel = command.permLevel;
if(commandPermLevel > userPermLevel){
return message.channel.send('You do not have required permissions');
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});

Resources