recently i build discord bot, the main problem is, i dont know how to set the permission, so every member of my server can kick and ban others - javascript

module.exports = {
name: 'ban',
description: "This command bans a member!",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.members.cache.get(member.id)
memberTarget.ban();
message.channel.send("User has been banned");
}else{
message.channel.send('you couldnt ban that member');
}
}
}
module.exports = {
name: 'kick',
description: "This command kicks a member!",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.members.cache.get(member.id)
memberTarget.kick();
message.channel.send("User has been kicked");
}else{
message.channel.send('you couldnt kick that member');
}
}
}

We could simply check for a user's permission using the .hasPermission() function of the GuildMember object. We could simply integrate it with a simple if statement, that would include the permissions you want to check for:
if (!message.member.hasPermission('BAN_MEMBERS') return; // Would return if the message author does not have permission to Ban Members
if (!message.member.hasPermission('KICK_MEMBERS') return; // Same thing for the Kick Members permission.

Related

Discord.js kick command permissions problem

So the last question I asked, I tried to use the sample code in MrMythical answer. This time, I encountered another problem:
if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)){
^
ReferenceError: Permissions is not defined
The code:
module.exports = new Command({
name: "kick",
description: "kick",
async run(message, args, client) {
if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)) {
if (message.mentions.members) {
try {
message.mentions.kick();
} catch {
message.reply("I don't have permission to ban " + message.mentions.members.first());
}
} else {
message.reply("You cannot ban " + message.member.mentions.first());
}
}
}
});
Let's say I deleted the if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)), the message the returned when executing the command was I don't have permission to ban <insert_user_id>.
I'm kinda stuck here for a while, if you can help me, thank you so much.
Edit: I forgot to import the Permissions, so there's just "Don't have permissions to kick" now
You will need to import Permissions from discord.js. You can import it at the top of the page, like this:
const { Permissions } = require('discord.js');
Also, message.mentions returns an object and it includes the mentioned members, channels, and roles. It won't have a kick() method and if you try to call it, it will throw an error. As you don't log the error in your catch block, you will have no idea what the error is; it will just send a reply saying "You cannot ban undefined".
You will need to check if there are mentioned members by checking message.mentions.members. It returns a collection; you can grab the first member by using first().
You can kick the first mentioned member like this:
const { Permissions } = require('discord.js');
module.exports = new Command({
name: 'kick',
description: 'kick',
async run(message, args, client) {
if (!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS))
return message.reply('You have no permission to ban members');
if (!message.mentions.members)
return message.reply('You need to mention a member to ban');
let mentionedMember = message.mentions.members.first();
try {
mentionedMember.kick();
} catch (err) {
console.log(err);
message.reply(`Oops, there was an error banning ${mentionedMember}`);
}
},
});

discord.js the bot crash when there's no mention in my unmute command

so i made a mute and unmute command, the mute one works pretty well and i just gotta add some things, the unmute one also works well but when there's no mentioned person (for example q!unmute and not q!unmute [user]) the bot crashes, i tried catch and that stuff but i really don't understand how they work, i'm pretty new to js, this is the string that should send the "you have to mention a user" error:
if (!member) return message.channel.send("You have to mention a valid member");
this is the rest of the code:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
if (!member) return message.channel.send("You have to mention a valid member");
}
}
}
i hope you can help
In your code you're checking if the user mentioned is null, but it is at the end of the function. I think that putting the if just after you get the value should work:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
if (!member) return message.channel.send("You have to mention a valid member");
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
}
}
}
Move
if (!member) return message.channel.send("You have to mention a valid member");
Below where you define member.
const member = message.mentions.members.first();

Discord.js Ban Command with Command Handler

I made a Discord.js Ban Command with reason and stuff however i overcome an error whenever i try to use it. Here is my code :
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user from the server by using mentioning them!',
guildOnly: true,
aliases: ['ban', 'banbanban'],
usage: `-ban <USER_MENTION> <OPTIONAL_REASON>`,
cooldown: 5,
async execute(message, args, client) {
const daidinevermantion = new MessageEmbed()
daidinevermantion.setTitle('Incorrect arguments provided!')
daidinevermantion.setDescription('Please Mention a user to ban ;-;. Make sure it a mention. The bot may not be able to ban users not in the server')
daidinevermantion.addField('Usage','``;ban <USER_MENTION> <OPTIONAL REASON>``')
daidinevermantion.addField('Example Usage', ';ban <#760773438775492610> Good Bot')
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send(daidinevermantion);
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/. Make sure you are mentioning the user and the user is in the server!');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban({ days: 7, reason: reason }).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Banned by', message.author)
.addField('Reason', reason)
.setFooter('Banned On:', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
Here whenever i send this command I this message in return "This user can't be banned. It is either because they are a mod/admin, or their highest role is higher than mine" regardless of whatever the case is whether its position is higher or lower. I'm a bit new to Discord.js please help me out thanks a lot!
You are getting that message because member.bannable is always false, and the reason for that is your bot doesn't have the required permissions to ban a user. Use this permission calculator and reinvite the bot to the server with required permissions i.e "Ban Members" or "Administrator".

discord.js Cant use command with user ID

I'm making a command that rickrolls the mentioned user by sending them a dm and when i try to use it by mentioning someone using their ID it dosent work and sends the error message i added saying: The mentioned user is not in the server
const { DiscordAPIError } = require('discord.js');
const Discord = require('discord.js');
const BaseCommand = require('../../utils/structures/BaseCommand');
module.exports = class RickrollCommand extends BaseCommand {
constructor() {
super('rickroll', 'fun', []);
}
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You really thought i was boutta rickroll myself? AINT NO WAY CHEIF');
const rickrollEmbed = new Discord.MessageEmbed()
.setTitle("You've Been Rickrolled!")
.setThumbnail('https://i1.wp.com/my-thai.org/wp-content/uploads/rick-astley.png?resize=984%2C675&ssl=1')
.setDescription('Rick astley sends his regards')
.setColor('#FFA500');
await mentionedMember.send('https://tenor.com/view/dance-moves-dancing-singer-groovy-gif-17029825')
await mentionedMember.send(rickrollEmbed)
.then(() => {
message.channel.send("Successfully rickrolled the user.");
})
.catch(err => {
message.channel.send('I was unable to rickroll the user.');
});
}
}
The wierd part is it only works with my ID and not any other user's ID.
I think the problem is, that you are using the cache and not the guilds member manager. Therefore, when no other user is cached it will only work with your ID since you are the one sending the message => getting loaded into the cache.
Try this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}
I don't know for sure, but it might also be a bit more optimized if you still prefer the cache, but just use the member manager as an additional backup, like this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first()
|| message.guild.members.cache.get(args[0])
|| await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}

How to assign roles with a command - discord.js

I wanted to give my bot the functionality to assign roles with a command
For example, +mod #user would give #user the role of Mod.
Code in my main.js:
if(command == 'mod'){
client.commands.get('mod').execute(message, args);
}
Code in my mod.js file:
module.exports = {
name: 'mod',
description: "This command gives member the Mod role",
execute(message, args){
const member = message.mentions.users.first();
member.roles.add('role ID xxxx');
}
}
I get an error saying the member is empty. Am I doing something wrong?
I don't think it said member is empty. users don't have roles though, members have. So you will need to get the first mentioned member instead.
module.exports = {
name: 'mod',
description: 'This command gives member the Mod role',
async execute(message, args) {
const member = message.mentions.members.first();
if (!member) {
return message.reply('you need to mention someone');
}
try {
await member.roles.add('ROLE_ID');
message.reply(`${member} is now a mod 🎉`);
} catch (error) {
console.log(error);
message.reply('Oops, there was an error');
}
},
};

Categories

Resources