my prevention to stop people muting someone twice doesnt work - discord

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)
}
}

Related

DiscordAPIError: Cannot send an empty message (discord.js v13)

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

Difficulty creating the mute command - DIscord.js

I'm having problems making my mute command. I tested it but it doesn't create the Muted role. Maybe I made some mystakes in the over-writing section. I wish someone could help me. Anyway, here's my code:
if (message.content.startsWith(config.prefix + "mute")) {
let toMute = message.mentions.users.first();
if (!message.guild.member(message.author).hasPermission("MANAGE_MESSAGES")) {
return message.channel.send('You do not have the permission for mute users!');
}
if (!message.guild.member(client.user).hasPermission("MANAGE_MESSAGES")) {
return message.channel.send("I don’t have the permission for mute users!");
}
if (!toMute) {
return message.channel.send("You need to ping a user or the user can't be found!");
}
let mutedRole = message.guild.roles.cache.find(mR => mR.name === "Muted");
if (!mutedRole) {
try {
mutedRole = await message.guild.createRole({
name: "Muted",
color: "#000000",
permissions: []
});
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(mutedRole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
})
});
} catch (err) {
console.log(err.stack);
}
}
if (message.guild.member(toMute).roles.cache.has(mutedRole.id)) return message.channel.send("This user is already muted!");
await message.guild.member(toMute).roles.add(mutedRole);
message.channel.send(`${toMute} got muted by <#${message.author.id}> 🔇`)
let {guild} = message;
toMute.send(`You got muted in **${guild.name}** by ${message.author}`)
}
and I'm getting this error.
Can someone help me fixing please? Thanks in advance!

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.js-commando how would I check if a mentioned user has a role, like a muted role for example?

So I have been trying to figure out how to check if the mentioned user has the muted role before attempting to add it, and if they do, say they are already muted, and I can't figure it out. Here is my code for my mute command, any help is appreciated.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
module.exports = class MuteCommand extends Command {
constructor(client) {
super(client, {
name: 'mute',
aliases: ['mute-user'],
memberName: 'mute',
group: 'guild',
description:
'Mutes a tagged user (if you have already created a Muted role)',
guildOnly: true,
userPermissions: ['MANAGE_ROLES'],
clientPermissions: ['MANAGE_ROLES'],
args: [
{
key: 'userToMute',
prompt: 'Please mention the member that you want to mute them.',
type: 'member'
},
{
key: 'reason',
prompt: 'Why do you want to mute this user?',
type: 'string',
default: message =>
`${message.author.tag} Requested, no reason was given`
}
]
});
}
run(message, { userToMute, reason }) {
const mutedRole = message.guild.roles.cache.find(
role => role.name === 'Muted'
);
if (!mutedRole)
return message.channel.send(
':x: No "Muted" role found, create one and try again.'
);
const user = userToMute;
if (!user)
return message.channel.send(':x: Please try again with a valid user.');
user.roles
.add(mutedRole)
.then(() => {
const muteEmbed = new MessageEmbed()
.addField('Muted:', user)
.addField('Reason', reason)
.setColor('#420626');
message.channel.send(muteEmbed);
})
.catch(err => {
message.reply(
':x: Something went wrong when trying to mute this user.'
);
return console.error(err);
});
}
};
To see if a mentioned user has a role you can do:
member = message.mentions.first();
if (member._roles.includes('<role ID>') {
//code
}
and obviously, replace <role ID> with the role id of the muted role.
This works because members objects have a _roles array that contains all the IDs of the roles they have.

user.ban is Not a function?

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()

Resources