So, members who have ban permissions cannot ban, which is good. But those who have ban permissions can ban those with higher roles than them, which means a mod can ban an admin if he has ban permissions. I want it so that you can't ban members with higher roles than you, even if you have ban permissions.
const Discord = require('discord.js');
module.exports = {
name : 'kick',
description : 'Kick',
async execute(message, args) {
console.log("Works");
if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("You do not have permissions to use this command");
const member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (!reason) reason = "No specified reason.";
const kickEmbed = new Discord.MessageEmbed()
.setTitle(`${member.user.tag} was kicked from ${message.guild.name}`)
.setDescription(`Reason: ${reason}`)
.setColor("#FF0000")
.setTimestamp()
.setFooter(message.author.tag, message.author.displayAvatarURL())
.setAuthor(member.user.tag, member.user.displayAvatarURL({dynamic : true}))
.setThumbnail(member.guild.iconURL({ dynamic: true }))
if (!args[0]) return message.channel.send(`You need to specify the user that is going to be kicked`);
if (!member) return message.channel.send(`The member you mentioned is not in the server`);
try {
await member.send(kickEmbed);
}
catch(err){
console.log(`I was unable to message the member`);
}
try {
member.kick(reason);
await message.channel.send(kickEmbed);
}
catch(err){
console.log(err);
message.channel.send("I was unable to kick the member you mentioned");
}
}
}
You can use <message>.member.roles.position.highest to determine the position of a member role and apply an appropriate fix
const Discord = require('discord.js');
module.exports = {
name : 'kick',
description : 'Kick',
async execute(message, args) {
console.log("Works");
if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("You do not have permissions to use this command");
const member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (!reason) reason = "No specified reason.";
const kickEmbed = new Discord.MessageEmbed()
.setTitle(`${member.user.tag} was kicked from ${message.guild.name}`)
.setDescription(`Reason: ${reason}`)
.setColor("#FF0000")
.setTimestamp()
.setFooter(message.author.tag, message.author.displayAvatarURL())
.setAuthor(member.user.tag, member.user.displayAvatarURL({dynamic : true}))
.setThumbnail(member.guild.iconURL({ dynamic: true }))
if (!args[0]) return message.channel.send(`You need to specify the user that is going to be kicked`);
if (!member) return message.channel.send(`The member you mentioned is not in the server`);
// the fix for your issue
if (member.roles.highest.position >= message.member.roles.highest.position) return message.reply('Yikes the person you tried to kick has higher or equal roles than you!')
try {
await member.send(kickEmbed);
}
catch(err){
console.log(`I was unable to message the member`);
}
try {
member.kick(reason);
await message.channel.send(kickEmbed);
}
catch(err){
console.log(err);
message.channel.send("I was unable to kick the member you mentioned");
}
}
}
Related
So im making a ban slash command using .addUserOption but when i try to get the permissions from the .addUserOption so that the bot doesnt crash when trying to ban an admin i get an error. I already know why, you cant get permissions from a user, only a GuildMember, so how would i go from user to GuildMember?
CODE: (if needed)
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName("ban")
.setDescription("Bans the specified user!")
.addUserOption((option) =>
option
.setName("user")
.setDescription('Who do you want to ban?')
.setRequired(true)
)
.addStringOption((option) =>
option
.setName('reason')
.setDescription("Whats the reason youre banning this user?")
),
async execute(client, interaction) {
if (client.cooldowns.has(interaction.user.id)) {
let cooldownEmbed = new MessageEmbed()
.setTitle("Please wait for the cooldown to end.")
.setDescription("This is so that the bot doesnt overload")
.setColor("RED")
.setFooter("The cooldown is 5 sec")
.setTimestamp()
interaction.reply({ embeds: [cooldownEmbed], ephemeral: true });
} else {
const user = interaction.member
const permission = user.permissions.has('BAN_MEMBERS');
let embed = new MessageEmbed()
.setTitle("❌️ | You dont have the permissions to use this command.")
if(!permission)
return interaction.reply({embeds: [embed]})
const tgt = interaction.options.getUser('user')
let permsEmbed = new MessageEmbed()
.setTitle("The user you are trying to ban is an Administrator!")
.setColor("RED")
if (tgt.permissions.has('BAN_MEMBERS')) return interaction.reply({ embeds: [permsEmbed]})
const reason = interaction.options.getString('reason') || "No reason specified"
client.cooldowns.set(interaction.user.id, true);
setTimeout(() => {
client.cooldowns.delete(interaction.user.id);
}, client.COOLDOWN_SECONDS * 1000);
}
}
}
I checked CollinD's suggestion and i managed to fix the problem. Heres the code if anyone else runs into this problem and needs an answer.
CODE:
const tgt = interaction.options.getUser('user');
let permsEmbed = new MessageEmbed()
.setTitle('The user you are trying to ban is an Administrator!')
.setColor('RED');
const guildMember = interaction.guild.members.cache.get(tgt.id);
if (guildMember.permissions.has('BAN_MEMBERS'))
return interaction.reply({ embeds: [permsEmbed] });
const Discord = require('discord.js');
const config = require('../config.json');
const { Permissions } = require('discord.js');
module.exports.run = async (client, message, args) => {
if(!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('You can\'t use that!')
if(!message.guild.me.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('I don\'t have the permissions.')
const member = message.mentions.members.first();
if(!args[0]) return message.channel.send('Please specify a user');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
message.guild.members.unban(`${member}`, `${reason}`)
.catch(err => {
if(err) return message.channel.send('Something went wrong')
})
let banembed = new Discord.MessageEmbed()
.setTitle('Member Unbanned')
.addField('User Unbanned', member)
.addField('Unbanned by', message.author)
.addField('Reason', reason)
.setFooter('Time Unbanned', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
You're using a message.mentions.members.first() which is referring to a pinged person. To use their ID's you can use .fetch or cache.get
const member = await message.guild.members.fetch(args[0])
const member = await message.guild.members.cache.get(args[0])
also you can use them on the same line using or ||
const member = message.mentions.members.first() || await message.guild.members.fetch(args[0]) || await message.guild.members.cache.get(args[0])
I only don't know if its going to work with unban because the bot and the user should on the same server
I am creating a slash command to overwrite permissions on a private text channel so that when the command is called, a channel and role is specified by the user and that role is the only one that will be able to see that channel. I am using the permission overwrite manager to accomplish this but when the command is run, it will say it worked but when I actually check the channel, nothing has changed. My code for this command is below. What am I doing wrong?
const { Permissions } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('givechannel')
.setDescription('Give an existing role to a channel')
.addChannelOption((option) =>
option
.setName('target')
.setDescription('Channel to give the role to')
)
.addRoleOption(option =>
option
.setName('role')
.setDescription('role to give the channel')
),
async execute(interaction) {
const channel = interaction.options.getChannel("target");
const role = interaction.options.getRole("role");
const name = interaction.guild.channels.cache.get(channel.id);
const id = interaction.guild.roles.cache.get(role.id);
if (!name) {
interaction.reply({ content: `That channel does not exist in the server!`, ephemeral: true});
return;
}
if (!id) {
interaction.reply({ content: `That role does not exist in the server!`, ephemeral: true })
}
if (!interaction.member.permissions.has([Permissions.FLAGS.ADMINISTRATOR])) {
interaction.reply({ content: `You don't have the permissions to give roles!`, ephemeral: true});
return;
} else {
try {
await interaction.channel.permissionOverwrites.edit( role, { VIEW_CHANNEL: true });
interaction.reply({ content: `${channel} has been given ${role} role!`, ephemeral: true});
} catch(err) {
console.log(err)
interaction.reply({ content: `Failed to give ${role} to ${channel}!`, ephemeral: true });
return;
}
}
}
}
So I'm trying to code a utility bot on my server and for some reason, this error popped out "Reference error"
ReferenceError: member is not defined
Every single time I solve a problem another one pops out. I know you guys will be asking me to save it (member) but I already did, like 7 times?
This is my current code:
const { Discord } = require("discord.js");
exports.run = async(client, msg, args) => {
if(!msg.member.hasPermission('BAN_MEMBERS')) return msg.reply('You do not have permission to use this command!')
var user = msg.mentions.user.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply('You did not mention a user for me to punish!')
var member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
if(member){
if(member.hasPermission('MANAGE_MESSAGES')) return msg.reply('You cannot ban a fellow staff member!');
}
var reason = args.splice(1).join(' ');
if(!reason) return msg.reply('Please make sure to specify a reason for me to punish this user!')
var channel = msg.guild.channels.cache.find(c => c.name === 'mod-logs');
var verify = msg.guild.emojis.cache.find(emoji => emoji.name === 'white_check_mark')
var log = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been kicked by ${msg.author} for "**${reason}**"`)
channel.send(logs);
var userLog = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`You have been banned from the server! Thats sadge. You can appeal the ban by message a staff member!`)
try {
await user.send(userLog);
} catch(err) {
console.warn(err);
}
msg.guild.members.ban(user);
var confir = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been banned by ${msg.author} for "**${reason}**"`)
msg.channel.send(confir);
msg.delete();
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
const { Discord } = require("discord.js");
exports.run = async(client, msg, args) => {
if(!msg.member.hasPermission('BAN_MEMBERS')) return msg.reply('You do not have permission to use this command!')
var user = msg.mentions.user.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply('You did not mention a user for me to punish!')
var member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
if(member){
if(member.hasPermission('MANAGE_MESSAGES')) return msg.reply('You cannot ban a fellow staff member!');
}
var reason = args.splice(1).join(' ');
if(!reason) return msg.reply('Please make sure to specify a reason for me to punish this user!')
var channel = msg.guild.channels.cache.find(c => c.name === 'mod-logs');
var verify = msg.guild.emojis.cache.find(emoji => emoji.name === 'white_check_mark')
var log = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been kicked by ${msg.author} for "**${reason}**"`)
channel.send(logs);
var userLog = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`You have been banned from the server! Thats sadge. You can appeal the ban by message a staff member!`)
try {
await user.send(userLog);
} catch(err) {
console.warn(err);
}
msg.guild.members.ban(user);
var confir = new Discord.MessageEmbed()
.setColor('0xecd776')
.setDescription(`${verify} ${user} has been banned by ${msg.author} for "**${reason}**"`)
msg.channel.send(confir);
msg.delete();
}
You can try this code:
const CUser = message.mentions.users.first() || message.guild.members.cache.get(args[0]) || message.guild.member(message.author);
let member
if (message.mentions.members.first()) {
member = CUser
} else {
member = CUser.user
}
instead of your:
var user = msg.mentions.user.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply('You did not mention a user for me to punish!')
var member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
Please note this code was written on discord.js version 12.5.3
So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel