user.ban is Not a function? - discord.js

I was trying to make a ban command where you can ban a user with a reason.
Turns out user.ban is not a function in Discord.js V12 even though it should be.
Here is my code.
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Bans a user.',
category: 'Moderation',
usage: '^ban <user> <reason>',
run: async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) {
return message.channel.send('You do not have permission to do this! ❌');
}
if (!message.guild.me.hasPermission('BAN_MEMBERS')) {
return message.channel.send('I do not have permission to do this! ❌');
}
const user = message.mentions.users.first();
if (!user) {
return message.channel.send('User was not specified. ❌');
}
if (user.id === message.author.id) {
return message.channel.send('You cannot ban yourself! ❌');
}
let reason = message.content
.split(' ')
.slice(2)
.join(' ');
if (!reason) {
reason = 'No reason provided.';
}
let Embed = new MessageEmbed()
.setTitle(`Justice! | Ban Action`)
.setDescription(`Banned \`${user}\` - Tag: \`${user.discriminator}\``)
.setColor('ORANGE')
.setThumbnail(user.avatarURL)
.addField('Banned by', `\`${message.author.username}\``)
.addField(`Reason?`, `\`${reason}\``)
.setTimestamp();
message.channel.send(Embed);
user.ban(reason);
},
};
Is there a way to fix this?

You're getting a User instead of a GuildMember. A User represents a person on discord, while a GuildMember represents a member of a server. You can get a GuildMember instead of a User by using mentions.members instead of mentions.users ex:
const user = message.mentions.members.first()

Related

my prevention to stop people muting someone twice doesnt work

when i try to unmute someone is allready muted i still get that user is muted even though i have this code.if anyone could help it would very helpfull thank you>
if(user.roles.cache.has(muterole)) {
return message.channel.send("Given User do not have mute role so what i am suppose to take")
}
module.exports = {
name: 'unmute',
description: "This unmutes a member",
execute(message, args, Discord){
if (!message.member.hasPermission("MANAGE_ROLES")) {
return message.channel.send(
"Sorry but you do not have permission to unmute anyone"
);
}
if (!message.guild.me.hasPermission("MANAGE_ROLES")) {
return message.channel.send("I do not have permission to manage roles.");
}
const user = message.mentions.members.first();
if (!user) {
return message.channel.send(
"Please mention the member to who you want to unmute"
);
}
let muterole = message.guild.roles.cache.find(x => x.name === "Muted")
let mainrole = message.guild.roles.cache.find(x => x.name === "Verified")
if(user.roles.cache.has(muterole)) {
return message.channel.send("Given User do not have mute role so what i am suppose to take")
}
user.roles.remove(muterole)
user.roles.add(mainrole)
message.channel.send(`**${message.mentions.users.first().username}** is unmuted`)
user.send(`You are now unmuted from **${message.guild.name}**`)
const MuteEmbed = new Discord.MessageEmbed()
.setColor('#1ABC9C')
.setDescription(`${message.mentions.users.first().username} has now been unmuted `)
.addField('Moderator',`<#${message.author.id}>`)
.addField('member',`${message.mentions.users.first().username}`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
const channel = message.guild.channels.cache.find(ch => ch.name === 'logs' );channel.send(MuteEmbed)
}
}

I want users not to be able to hand out higher privileges than they have themselves

A moderator who has manage_roles permissions can even give the owner role to anyone. Is there a way that it can give out no higher role than to his own role?
So if he is admin, he can give at most admin, so not everyone can give random roles to anyone.
const { MessageEmbed } = require('discord.js');
const config = require('../../configs/config.json');
module.exports = {
config: {
name: "give-roles",
},
run: async (client, message, args) => {
message.delete();
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send({
embed: {
title: `You dont have permission to use this command`
}
})
if (!args[0] || !args[1]) return message.channel.send({
embed: {
title: "Incorrect usage, It's `<username || user id> <role name || id>"
}
})
try {
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
const alreadyHasRole = member._roles.includes(roleName.id);
if (alreadyHasRole) return message.channel.send({
embed: {
title: "User already has the role defined"
}
})
const embed = new MessageEmbed()
.setTitle(`Role Name: ${roleName.name}`)
.setDescription(`${message.author} has successfully given the role ${roleName} to ${member.user}`)
.setColor('f3f3f3')
.setThumbnail(member.user.displayAvatarURL({ dynamic: true }))
.setFooter(new Date().toLocaleString())
return member.roles.add(roleName).then(() => message.channel.send(embed));
} catch (e) {
return message.channel.send({
embed: {
title: "Try to give a role that exists next time"
}
})
}
}
}
You're able to use roles.highest.position:
let taggedMember = ... //(guildMember)
if (message.member.roles.highest.position < taggedMember.roles.highest.position) {
//code...
}
Docs: https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=highest

Discord bot role command stopped working for unknown reasons

I have a command which worked, but at some point stopped, returning to the chat message that the role does not exist. An error "(node:12228) DeprecationWarning: Collection#find: pass a function instead" is sent to the console every time I use a command, but I always had it
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply();
let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if(!rMember) return message.reply("nope.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("nope!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("role does not exist.");
const allowed = ['some id'];
if (!allowed.includes(gRole.id)) return;
if(rMember.roles.has(gRole.id)) return message.reply("nope.");
await(rMember.removeRoles(['some id']));
await(rMember.addRole(gRole.id));
if(gRole.id == 'id') rMember.addRole('id') && rMember.removeRoles(['some id']);;
try{
await rMember.send(`you got ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
So I need the command to work.
In order of appearance, I see these mistakes in your code...
You're not catching any rejected promises.
MANAGE_MEMBERS is not a valid permission flag.
You should pass a function into Collection.find().
No idea what you're trying to do with the declaration of role.
Your use of the && logical operator in your if statement is incorrect. Use a block statement instead.
Your catch block in the try...catch statement has been left empty.
Combining the answers provided to your other questions about this code, this is a correct, much cleaner rewrite...
const getMention = require('discord-mentions'); // Don't forget to install.
module.exports.run = async (bot, message, args) => {
if (!message.guild) return;
try {
if (!message.member.hasPermission('MANAGE_ROLES')) return;
if (!args[1]) return await message.reply('Please provide a user.');
if (!args[2]) return await message.reply('Please provide a role.');
if (args[3]) return await message.reply('Too many arguments provided.');
let member;
if (getMention(args[1])) member = getMention(args[1], message.guild).member;
else member = message.guild.members.find(m => m.user.tag === args[1] || m.id === args[1]);
if (!member) return await message.reply('Invalid user provided.');
let role;
if (getMention(args[2])) role = getMention(args[2], message.guild).role;
else role = message.guild.roles.find(r => r.name === args[2] || r.id === args[2]);
if (!role) return await message.reply('Invalid role provided.');
const allowed = ['role1ID', 'role2ID', 'role3ID'];
if (!allowed.includes(role.id)) return await message.reply('That role is not allowed.');
if (member.roles.has(role.id)) return await message.reply('That user already has that role.');
await member.removeRoles(['someID', 'someOtherID']);
await member.addRole(role.id);
if (role.id === 'anAlternateRoleID') {
await member.removeRoles(['someID', 'someOtherID']);
await member.addRole('otherRoleID');
}
await member.send(`You got the ${role.name} role.`)
.catch(() => console.log(`Couldn't send message to ${member.user.tag}.`));
} catch(err) {
console.error(err);
}
};
module.exports.help = {
name: 'role'
};
Keep in mind, if you're removing just one role from a member, you should use the singular version of the method, GuildMember.removeRole().

I need to add # to a role in the command

If I use a command like this, then it will not work:
!role #Nick#0000 #role
How can I fix it?
I tried to use
message.mentions.members.first()
,but i think i was doing it wrong
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply();
let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if(!rMember) return message.reply("nope.");
let role = args.join(" #").slice(22);
if(!role) return message.reply("nope!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("nope.");
if(rMember.roles.has(gRole.id)) return message.reply("nope.");
await(rMember.removeRoles(['id', 'id']));
await(rMember.addRole(gRole.id));
try{
await rMember.send(`nope ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
So I don't have any result now.
Disclaimer: I am the author of the npm package used in this answer. I've included it to present the simplest and easiest solution I see. This answer does not intend to promote the package itself in any way.
To check if a certain argument or string is a mention and extract the member/role/channel, you can use discord-mentions.
const getMention = require('discord-mentions');
try {
if (!args[1]) return await message.reply('Please provide a user.');
if (!args[2]) return await message.reply('Please provide a role.');
let member;
if (getMention(args[1])) member = getMention(args[1], message.guild).member;
else member = message.guild.members.find(m => m.user.tag === args[1]);
if (!member) return await message.reply('Invalid user.');
let role;
if (getMention(args[2])) role = getMention(args[2], message.guild).role;
else role = message.guild.roles.find(r => r.name === args[2]);
if (!role) return await message.reply('Invalid role.');
// Continue on... 'member' is a GuildMember, 'role' is a Role.
} catch(err) {
console.error(err);
}

How to fix overwritePermissions to user not working

I want the bot to change member permissions and set "send messages" to false if someone uses $done #user.
client.on('message', async message => {
if (message.author.bot) return;
if (message.content === prefix + "done") {
var user = message.guild.member(message.mentions.users.first());
message.channel.overwritePermissions(user, {
SEND_MESSAGES: false
});
}
});
You should either use:
const user = message.mentions.users.first();
or
const user = message.mentions.members.first();
and then add a
if(!user) return messsage.channel.send('You need to mention a user!'); below the `const user` line.

Resources