Discord.js Ban command - javascript

I am trying to get a ban command but keep getting errors and I don't know why my code is not working. I am using discord.js v12
bot.on('message', message =>{
if(message.content.startsWith(`${prefix}ban`)){
const args = message.content.trim().split(/ +/g);
const bUser = message.guild.member(message.mentions.users.first())
if(!message.guild.member(message.author).hasPermission("ADMINISTRATOR")) {return message.reply("You do not have enough permission for this command!")};
if(!message.guild.member(bot.user).hasPermission("ADMINISTRATOR")) {return message.reply("The bot does not have enough permissions for this commands")};
if(message.mentions.users.size === 0) {return message.reply("You need to ping a user!")};
if (!message.guild) return;
let banReason = args.join(" ").slice(27);
const banembed = {
color: "RANDOM",
title: `Ban`,
description: `${bUser} has been banned by ${message.author}`,
fields: [{
name: "Ban Reason",
value: `${banReason}`,
}],
}
bUser.send({ embed: banembed }).
then(
bUser.ban({ reason: banReason })
(message.channel.send({ embed: banembed })
)
)
};
});
Thank you for taking time to read this!

For bUser.ban({ reason: banReason }) :
The correct syntax is:
bUser.ban(banReason);

the correct syntax is:
message.guild.members.ban(user,{reason: "your reason"});
i also suggest doing this asynchronious with an await for example
(in an async)
try{
await message.guild.members.ban(user,{reason: ReasonString});
}catch (error){
console.log(error);
}

Related

How do I check if a user has their DM's open? | discord.js v 14

I am making a bot that can dm a user. If the dm's of the user are off it says the message is successfully sent but in the console it returns an error.
So, what can I do to check if a user's dm is open?
The code I'm trying to run:
const rec = interaction.options.getUser('user')
const user = interaction.user.id
try {
rec.send({ embeds:[ new EmbedBuilder().setDescription(`<#${user}> says to you: ${message} `).setColor("#f05c51")
.then(interaction.reply(({ content: 'Successfully sent', ephemeral: true })))
] })
} catch (error) {
interaction.reply(({ content: `Could not send message, maybe dm's off? -> ${error}`, ephemeral: true }))
}
You can't. You need to use .catch()
rec.send({ embeds: [YOUREMBED] })
.then(message => console.log(`Sent message: ${message.content}`))
.catch(console.error);
I used unhandledRejection to know if my bot can't send a message to a specific user, also can use it all of unhandledRejection errors
process.on('unhandledRejection', async(error) => {
const admin = client.channels.cache.get('-----')
const embed = new MessageEmbed()
.setDescription(`\`\`\`\j\s\n${error.message || error.name || error }\n\`\`\``)
.setColor('RANDOM')
.setTimestamp()
admin.send({embeds: [embed]})
console.log(error)
});
You can also try it on your code.

can't dm mentioned user javascript

i'm trying to make a ban command, but it keep saying that mentionedUser.send is not a function?[console image][1]
i'm not exactly sure what to do here. i read a bit and saw something about a "cache" system, but i have completely no idea how to use it.
can anyone help?
my code:
const { multiGetLatestMessages } = require("noblox.js");
const Discord = require('discord.js');
module.exports = {
name: 'ban',
description: 'ban user',
cooldown: 5,
permissions: 'BAN_MEMBERS',
aliases: ['banlands', "getbannednoob"],
async execute(message, args) {
let reason = args.slice(1).join(" ");
let mentionedMember = message.mentions.members.first
if (!reason) reason = "No reason given";
if (!args[0]) return message.channel.send("at least tell me who to ban noob");
if (!mentionedMember) return message.channel.send("couldn't find that noob");
//if (!mentionedMember.bannable) return message.channel.send("i can't ban that user you noob");
const banEmbed = new Discord.MessageEmbed()
.setTitle(`you got banned from ${message.guild.name}`)
.setDescription(`reason for ur disposal: ${reason}`)
.setColor("#FF0000")
.setTimestamp()
await mentionedMember.send(banEmbed).catch(err => message.channel.send(err));
await mentionedMember.ban({
reason: reason
}).catch(err => message.channel.send(err)).then(() => message.channel.send("u banned " + mentionedMember.user.tag))
}
}```
[1]: https://i.stack.imgur.com/HEaRz.png
i figured it out, i forgot the () after "first" in let mentionedMember = message.mentions.members.first, silly me

Send user that got kicked the reason why they got kick

The only code I have is this:
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("User has been kicked");
} else {
message.channel.send(`You coudn't kick that member!`);
}
},
};
Good Morning. So I'm trying to get it to message the person that got kicked the reason why they got kicked. (!kick user reason) I want it so the bot DMs the person what the reason was but I don't know how to do that.
You would only need to add the following:
const reason = args.splice(1).join(` `) || 'Not specified';
memberTarget.send(`You have been kicked: \nReason: ${reason}`)
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
const reason = args.splice(1).join(` `) || 'Not specified';
memberTarget.kick();
message.channel.send("User has been kicked");
memberTarget.send(`You have been kicked: \nReason: ${reason}`)
} else {
message.channel.send(`You coudn't kick that member!`);
}
},
};
The const reason = args.splice(1).join( ) || 'Not specified'; defines the 'reason' property, if there isn't a reason, it defaults to 'Not specified'.
memberTarget.send(You have been kicked: \nReason: ${reason})
Just sends the message to the targeted member.
Right off the bat, I see that you are getting the target using message.mentions.users and getting the memberTarget from the guild's cache. You should avoid this and use message.mentions.members.
You'll have to use the send method of GuildMember, but since it returns a Promise, you'll have to catch any errors. (e.g: the bot cannot DM the member)
// You should do some sanity checks in case you haven't. You don't want everyone to be able to kick members using the bot.
// Getting the first member in message.mentions.members.
const target = message.mentions.members.first();
// Making sure that target is defined.
if (!target) return message.channel.send('Please mention a member to kick.');
// Making sure a reason is provided. (args[0] is the mention)
if (!args[1]) return message.channel.send('Please provide a reason.');
// Making sure the bot can kick the target.
if (!target.kickable) return message.channel.send('Couldn\'t kick the target.');
// Trying to send a message to the target, notifying them that they got kicked, and catching any errors.
target.send(`You have been kicked from ${message.guild.name} for ${args.slice(1, 2000).join(' ')}`).catch(console.error).finally(() => {
// After the message was sent successfully or failed to be sent, we kick the target and catch any errors.
target.kick(`Kicked by ${message.author.tag} for ${args.slice(1, 2000).join(' ')}}.`).then(() => {
message.channel.send(`${target.user.tag} has been kicked for ${args.slice(1, 2000).join(' ')}.`);
}).catch(error => {
console.error(error)
message.channel.send(`Something went wrong...`);
});
});
This is working kick command with reason made by me (you can try it):-
It has every validation you should have in a kick command
const Discord = require('discord.js')
exports.kick = async(message , prefix , client) => {
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send('Missing Permission! You need to have `KICK_MEMBERS` permissions in order kick this member.')
if(!message.guild.me.hasPermission("KICK_MEMBERS")) return message.channel.send('Missing Permission! I need to have `KICK_MEMBERS` permissions to kick this member.')
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
let member = message.mentions.members.first();
if(!member){
let err = "```css\n[ Agrument Error : You Have not mentioned the user on first args. ]\n```\n\n"
let embed = new Discord.MessageEmbed()
.setAuthor(`${client.user.username} Help Manual` , client.user.displayAvatarURL({format : "png"}))
.setTitle(`${message.guild.name}`)
.setDescription(err)
.addField('Help Command:' , `\`\`\`\n${prefix}kick #user#0001 Reason\n\`\`\``)
.setTimestamp()
.setColor('RED')
return message.channel.send(embed)
}
if(args[0] != `<#!${member.id}>`){
let err = "```css\n[ Agrument Error : You Have not mentioned the user on first args. ]\n```"
let embed = new Discord.MessageEmbed()
.setAuthor(`${client.user.username} Help Manual` , client.user.displayAvatarURL({format : "png"}))
.setTitle(`${message.guild.name}`)
.setDescription(err)
.addField('Help Command:' , `\`\`\`\n${prefix}kick #user#0001 Reason\n\`\`\``)
.setTimestamp()
.setColor('RED')
return message.channel.send(embed)
}
if(member.id === message.author.id) return message.channel.send(`Why? No Just Say Why Do you want to kick yourself?`)
let reason = args.slice(1).join(' ');
if(!reason || reason.length <= 1){
reason = "No Reason Was Provided."
}
if(!member.kickable){
return message.channel.send(`I Don't Have Permissions to Kick ${member.user.username}`)
}
member.kick().then(() => {
return message.channel.send(`Successfully Kicked ${member.user.username} for Reason ==> \`${reason}\``)
}).catch(() => {
return message.channel.send(`I Don't Have Permissions to Kick ${member.user.username}`)
})
}

Ban module, Discord bot error.. discord.js

1 day ago i publish an issue with for a discord bot that said that my id was not a property of null. Now its works. But it still not able to ban, and it gives me the error marked on the code: message.reply("I was unable to ban the member :(");
This is the code:
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'ban',
description: "ban peoples ;D",
execute(message, args, client) {
if (!message.member.hasPermission("BAN_MEMBERS") ||
!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You don't have a permissions to do this, maybe later ;) ");
const user = message.mentions.users.first();
const member = message.guild.member(user);
if (!user) return message.channel.send("Please mention the user to make this action");
if (user.id === message.author.id) return message.channel.send("You can't ban yourself, I tried :(");
member.ban(() => {
message.channel.send('Successfully banned **${user.tag}**');
}).catch(err => {
message.reply("I was unable to ban the member :(");
})
}
}
i checked to see if the bot needs permissions, i gave it him but it still not working.
The issue is here
member.ban(() => {
message.channel.send('Successfully banned **${user.tag}**');
}).catch(err => {
message.reply("I was unable to ban the member :(");
})
You are passing an entire function into the ban method
Really you should be calling the function then using .then(() => {}) to handle the promise
It should look like this
member.ban()
.then(() => {
message.channel.send('Successfully banned **${user.tag}**');
})
.catch((err) => {
message.reply("I was unable to ban the member :(");
console.error(err);
});

Discord.js: message.guild.channels.forEach is not a function

I'm creating a Discord Bot using Discord.js
I'm creating a mute command but when I want to disable speaking permission for the Mute role for each channel, I get this error:
TypeError: message.guild.channels.forEach is not a function
I have V12.
And I looked at some other options but I couldn't find any working options.
if(!toMute) return message.reply('It looks like you didnt specify the user!');
if(toMute.hasPermission('MANAGE_MESSAGES')) return message.reply("can't mute them");
let muterole = message.guild.roles.cache.find(r => r.name === 'muted');
if(!muterole){
try{
muterole = await message.guild.roles.create({
name: "muted",
color: "#000000",
permissions: []
})
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermission(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
}catch(e){
console.log(e.stack);
}
} return message.channel.send('Cant')
let mutetime = args[1];
if(!mutetime) return message.reply('You didnt specify the time');
await(toMute.addRole(muterole.id));
message.reply(`Successfully muted <#${toMute.id}> for ${ms(mutetime)}`);
setTimeout(function(){
toMute.removeRole(muterole.id);
message.channel.send(`<#${toMute.id}> has been unmuted!`);
}, ms(mutetime));
}
Please try
message.guild.channels.cache.forEach((channel)=>{
...
})
Reference: https://discord.js.org/#/docs/main/stable/class/GuildChannelManager?scrollTo=cache
It's like the error says. message.guild.channels.forEach is not a function!
You're probably using discord.js v12.
In this version, message.guild.channels doesn't return a collection, it returns the ChannelManager. To get a collection of all channels, you use message.guild.channels.cache.
And now you can use .forEach():
message.guild.channels.cache.forEach((channel) => {
// your code here
});

Categories