Difficulty creating the mute command - DIscord.js - discord

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!

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.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.

So I am trying to ask a question to retrieve a mentioned channel but doesn't work

So I am trying to make my giveaway bot but can't make a create command so the person can add more details about the giveaway! Thus, I need questions but everytime I try it never goes well!
message.channel.send("Please mention the channel you want the giveaway to be in! **e.g #channel**");
try {
let msgs = await message.channel.awaitMessages(u2=>u2.author.id===message.author.id, { time: 15000, max: 1, errors: ["time"]});
if(parseInt(msgs.first().content)==mention.channel) {
const Channel = message.mentions.channels.first();
await Channel.send("HEY")
}
else {
message.channel.send("You did not mentioned a channel!");
}
}catch(e) {
return message.channel.send("Command Cancel!")
}
It either returns to the catch(e) line or "You did not mentioned a channel!"!
This should be what you want i think. (works with mentioning the channel, providing a channel ID or providing a channel name)
message.channel.send("Please mention the channel you want the giveaway to be in! **e.g #channel**");
let channel;
let response;
try {
response = await message.channel.awaitMessages(msg => msg.author.id === message.author.id, { max: 1, time: 1000*60*3, errors: ['time'] })
} catch {
return message.channel.send("Command Cancel!")
}
if (response.first().mentions.channels.first()) {
channel = response.first().mentions.channels.first()
} else if (!isNaN(response.first().content) && message.guild.channels.cache.get(response.first().content)) {
channel = message.guild.channels.cache.get(response.first().content)
} else if (isNaN(response.first().content) && message.guild.channels.cache.find(c => c.name.toLowerCase() === response.first().content.toLowerCase())) {
channel = message.guild.channels.cache.find(c => c.name.toLowerCase() === response.first().content.toLowerCase())
}
if (channel) {
await channel.send("HEY")
} else {
return message.channel.send("You did not mentioned a channel!");
}

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