Discord Js Prefix - discord.js

I use this command handler, and so far, the bot works great. But the problem is that it replies to every prefix. Like if my bot prefix is "!" then it responds to other prefixes too.
client.on("message", async message => {
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});

You need to check if the message starts with the prefix. Add this at the top of the .on(message) event:
if (!message.content.startsWith(prefix)) return;
Should look like so:
client.on("message", async message => {
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});

Related

My Discord Bot is online. My Prefix is "-". My -Ping Command is working but my -Discord command is not working. My Code is below. (Discord.js)

This is my Code ⬇️. My -Ping Command is working but my -Discord Command is not. My Bot is also online, Is there a problem?
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const prefix = '-'
client.once('ready', () => {
console.log('Super-Lame is Online!')
});
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 === 'ping'){
message.channel.send('pong!');
} else if (command === 'Discord'){
message.channel.send('LecTroLight#9823');
}
});
client.login('My Token Here')
With toLowerCase(), you converted command to lowercase, so it will never equal "Discord". You should match against "discord".
i noticed you are using
.toLowerCase() and then you are checking the conditions for Discord. That wont work unless you check for discord.

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

How to add role to user in discord?

How can I add role to user in this case? I don't want to do this with roles.find.
Thanks for help!
My script:
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$"`;
client.on('message', function (message) {
if (!message.content.startsWith(prefix)) return
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args[0].toLowerCase();
if (command === 'add') {
let member = message.member.guild.member(args[1])
client.cache.get(member.id).roles.add("roleid");
client.login('token');
You can do it like this:
use args.shift() to get a command, so then you can use args as command arguments
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '$';
client.on('message', function (message) {
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
let command = args.shift();
if (command === 'add') {
if (args.length === 0) return message.reply('pls mention a member or write a ID');
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!member) return message.reply(`can't get a member ${args[0]}`);
member.roles
.add('ROLE ID')
.then(() => {
message.channel.send(`successfully add role to member ${member.user}`);
})
.catch((err) => {
message.channel.send(`Failed to add role to member`);
});
}
});
client.login('token');

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.

How to make bot not stop after error? Discord.js

I have script which have to kick user with reason.
Syntax:
$kick #user Reason
but when I type:
$kick sometext nexttext
I got error in console:
TypeError: Cannot read property 'kick' of undefined
and bot stop...
How can I edit this script so that after entering an incorrect value, an error will not pop up turning off the bot and bot will send message to channel eg. "Incorrect value"?
Script:
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "kick") {
let member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
member.kick(reason);
message.delete();
client.channels.cache.get('737341022782357566').send("User <#" + member.id + "> with id " + member.id + " has been kicked by <#" + message.author.id + "> with reason " + reason)
}})
client.login('token');
in javascript to execute a code that have chances to chrash, you can use the statment
try {
//code to test
} catch(err) {
//code if it crash
}
add a if (member) to test if there was a mention.
In the else, you can send your "bad command" message
you should also only trigger the bot if the message starts with your prefix
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
if (!message.content.startsWith(prefix)) { return }
//this line prevents the bot to execute every message
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "kick") {
let member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (member) { // add this
member.kick(reason);
client.channels.cache.get('737341022782357566').send(`User ${member.user} with id: ${member.id} has been kicked by ${message.author} with reason: ${reason}`);
} else {
message.reply("invalid parameters for $kick")
}
message.delete();
}
})
client.login('token');

Resources