Discord Role not getting created - javascript

I'm making a mute command and for the most part it works, when the 'Muted' role exists it gives it to the member with no problem and everything works out fine, but when the role doesn't exist it gives me the error;
Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
Here is the code:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
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("MUTE_MEMBERS")) return message.channel.send("I do not have Permissions to mute members.");
const Embedhelp = new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu'},
{ name: '**Info**', value: 'You cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours\nYou cannot mute members that have already been muted'}
)
.setFooter(client.user.tag, client.user.displayAvatarURL());
const mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
let reason = args.slice(1).join(" ");
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());
let role = 'Muted';
let newrole = message.guild.roles.cache.find(x => x.name === role);
if (typeof newrole === undefined) {
await message.guild.roles.create({
data: {
name: 'Muted',
color: '#414247',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
.catch(console.log(err)); {
message.channel.send('Could not create muted role');
};
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!mentionedMember) return message.channel.send(Embedhelp);
if (!mentionedMember.bannable) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == message.author.id) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == client.user.id) return message.channel.send(Embedhelp);
if (mentionedMember.roles.cache.find(x => x.name === role)) return message.channel.send(Embedhelp);
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.channel.send(Embedhelp);
mendtionedMember.roles.add(newrole)
.catch(err => {
console.log(err); {
return message.channel.send('I was unable to mute the user');
};
}).then(() => {
message.channel.send('Successfully Muted '+mentionedMember.user.tag);
});
} else {
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!mentionedMember) return message.channel.send(Embedhelp);
if (!mentionedMember.bannable) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == message.author.id) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == client.user.id) return message.channel.send(Embedhelp);
if (mentionedMember.roles.cache.find(x => x.name === role)) return message.channel.send(Embedhelp);
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.channel.send(Embedhelp);
await mentionedMember.roles
.add(newrole)
.catch(err => {
console.log(err); {
return message.channel.send('I was unable to mute the user');
}
}).then(() => {
message.channel.send('Successfully Muted '+mentionedMember.user.tag);
});
};
}
}
the part where the role is created is;
let newrole = message.guild.roles.cache.find(x => x.name === role);
if (typeof newrole === undefined) {
await message.guild.roles.create({
data: {
name: 'Muted',
color: '#414247',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
.catch(console.log(err)); {
message.channel.send('Could not create muted role');
};
it checks if the Muted role already exists and then if it doesn't it creates a Muted role, I am not sure if the error originates here but I believe that it fails to create the role which is why it doesn't exist and it cannot give it to the mentioned user, if there is anyway to fix this please let me know.

I don't understand why are you making a new post about the same question as I have already answered your question with clear instruction on your previous post created yesterday. Here is the answer for the question.

Related

TypeError: Cannot read property 'highest' of undefined - Mute Command

So hey Stackoverflow community, Im here kinda confused on why this stopped working all of the sudden, and I get the error that is stated in the title.
Basically it would check to see if the user who was attempting to mute a user had a higher role than the other user, and if they did.. it would mute them, and if they didn't it would throw an error.
But now all it does is just throw the error stated in the title once again and I cannot find a fix on the docs?
Also when i remove the highest.position from the check, it allows anyone with the right perms to mute anyone above or below them.
So here I am, asking nicely for some help/understanding on why this method of muting users has stopped working unexpectedly.
const { MessageEmbed } = require("discord.js");
const db = require("quick.db");
const ms = require("ms");
const modSchema = require("../../models/modLogs");
module.exports = {
name: "mute",
description: "Mutes a user in a server",
usage: "[name | nickname | mention | ID] (reason)",
run: async (client, message, args) => {
try {
if (!message.member.permissions.has('MANAGE_ROLES')) return message.reply('You do not have perms to mute users. - `[MANAGE_ROLES]`')
if (!message.guild.me.permissions.has('MANAGE_ROLES')) return message.reply('I do not have perms to mute users. - `[MANAGE_ROLES]`');
if (!args[0]) return message.reply("```Usage: c!mute <user>```");
var mutedMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!mutedMember) return message.reply("Please provide a valid user to mute.");
if (mutedMember === message.member) return message.reply("I'm afraid you cannot mute yourself, Captain.");
if (message.author.roles.highest.position <= mutedMember.roles.highest.position) return message.reply("<a:CL_No:909440866622517318> You cannot mute that user because they have the same or higher role than you.");
let reason = args.slice(1).join(" ");
if (mutedMember.user.bot) return message.reply("<a:CL_No:909440866622517318> I am unable to mute other bots.");
const userRoles = mutedMember.roles.cache.filter(role => role.id !== message.guild.id).map(role => role.id);
let muterole;
let dbmute = await db.fetch(`muterole_${message.guild.id}`);
let muteerole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!message.guild.roles.cache.has(dbmute)) {
muterole = muteerole;
} else {
muterole = message.guild.roles.cache.get(dbmute);
}
if (!muterole) {
try {
message.reply("<a:CL_No:909440866622517318> I was unable to find the `Muted` role, attempting to create one now...");
muterole = await message.guild.roles.create({
name: "Muted",
color: "#010101",
permissions: []
});
message.guild.channels.cache.forEach(async channel => {
await channel.permissionOverwrites.create(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false,
CONNECT: false
});
});
message.reply("<a:CL_CheckMark:858853559940808724> Successfully created the \`Muted\` role.");
} catch (err) {
message.reply(`\`${err}\``)
}
}
if (mutedMember.roles.cache.has(muterole.id)) return message.reply(`\`${mutedMember.user.tag}\` is already muted.`);
db.set(`muteeid_${message.guild.id}_${mutedMember.id}`, userRoles);
try {
mutedMember.roles.set([muterole.id]).then(() => {
const muteEmbed1 = new MessageEmbed()
.setColor("RED")
.setAuthor({ name: message.guild.name, iconURL: message.guild.iconURL() })
.setDescription(`${mutedMember.user.tag}, You were muted in \`${message.guild.name}\``)
.addField("Reason:", `${reason || "No Reason Specified."}`)
.setTimestamp()
.setFooter({ text: `Moderator: ${message.author.tag}` });
mutedMember.send({ embeds: [muteEmbed1] });
});
} catch {
mutedMember.roles.set([muterole.id]);
}
if (reason) {
const muteEmbed2 = new MessageEmbed()
.setColor("RED")
.setAuthor({ name: message.guild.name, iconURL: message.guild.iconURL() })
.setDescription(`\`${mutedMember.user.tag}\` has been muted.`)
.addField("User Roles:", "<a:CL_CheckMark:858853559940808724> | Removed all user roles.")
.setTimestamp();
message.reply({ embeds: [muteEmbed2] });
} else {
const muteEmbed3 = new MessageEmbed()
.setColor("RED")
.setAuthor({ name: message.guild.name, iconURL: message.guild.iconURL() })
.setDescription(`\`${mutedMember.user.tag}\` has been muted.`)
.addField("User Roles:", "<a:CL_CheckMark:858853559940808724> | Removed all user roles.")
.setTimestamp();
message.reply({ embeds: [muteEmbed3] });
}
modSchema.findOne({ Guild: message.guild.id }, async (err, data) => {
if (!data) return;
const logschannel = message.guild.channels.cache.get(data.Channel);
if (logschannel) {
const muteMemberEmbed = new MessageEmbed()
.setTitle('User Muted')
.addField('User', `${mutedMember.user.username} (${mutedMember.user.id})`)
.addField('Moderator', `${message.author.tag}`)
.addField('Reason', `${reason || 'No Reason Specified'}`)
.addField('Muted', `<t:${Math.floor(Date.now() / 1000)}:R>`)
.setColor('ORANGE')
.setThumbnail(mutedMember.user.displayAvatarURL({ dynamic: true }))
logschannel.send({ embeds: [muteMemberEmbed] });
}
});
} catch (err) {
return message.reply(`\`\`\`${err}\`\`\``);
}
}
};
The problem is that message.author returns a User and Users don't have roles; only GuildMembers have. While a User is a global user on Discord, a GuildMember is a user on a specific server and this member has roles on that server.
So, instead of message.author you should use message.member that returns a GuildMember:
if (message.member.roles.highest.position <= mutedMember.roles.highest.position)
return message.reply(
"<a:CL_No:909440866622517318> You cannot mute that user because they have the same or higher role than you."
);

Discord.js bot channel createOverwrite not working

Hai i am working on a discord moderation bot i made a mute command but it will add mute role to people and if the role doesn't exist it will create one and add it to the member but i have a problem it wont deny send message permission in every channel i added the code for that but it isn't working and i get no errors in console here is my code
message.guild.channels.cache.forEach(async (channel) => {
await channel.createOverwrite(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false,
CONNECT: false,
})
Here is my full mute.js code
const { MessageEmbed } = require("discord.js");
const db = require('quick.db');
module.exports = {
name: 'mute',
description: 'mutes a user',
async execute(message, args) {
try {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.channel.send("**You Dont Have Permmissions To Mute Someone! - [MANAGE_GUILD]**");
if (!message.guild.me.hasPermission("MANAGE_GUILD")) return message.channel.send("**I Don't Have Permissions To Mute Someone! - [MANAGE_GUILD]**")
if (!args[0]) return message.channel.send("**Please Enter A User To Be Muted!**");
var mutee = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!mutee) return message.channel.send("**Please Enter A Valid User To Be Muted!**");
if (mutee === message.member) return message.channel.send("**You Cannot Mute Yourself!**")
if (mutee.roles.highest.comparePositionTo(message.guild.me.roles.highest) >= 0) return message.channel.send('**Cannot Mute This User!**')
let reason = args.slice(1).join(" ");
if (mutee.user.bot) return message.channel.send("**Cannot Mute Bots!**");
const userRoles = mutee.roles.cache
.filter(r => r.id !== message.guild.id)
.map(r => r.id)
let muterole;
let dbmute = await db.fetch(`muterole_${message.guild.id}`);
let muteerole = message.guild.roles.cache.find(r => r.name === "muted")
if (!message.guild.roles.cache.has(dbmute)) {
muterole = muteerole
} else {
muterole = message.guild.roles.cache.get(dbmute)
}
if (!muterole) {
try {
muterole = await message.guild.roles.create({
data: {
name: "muted",
color: "#514f48",
permissions: []
}
})
message.guild.channels.cache.forEach(async (channel) => {
await channel.createOverwrite(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false,
CONNECT: false,
})
})
} catch (e) {
console.log(e);
}
};
if (mutee.roles.cache.has(muterole.id)) return message.channel.send("**User Is Already Muted!**")
db.set(`muteeid_${message.guild.id}_${mutee.id}`, userRoles)
try {
mutee.roles.set([muterole.id]).then(() => {
mutee.send(`**Hello, You Have Been Muted In ${message.guild.name} for - ${reason || "No Reason**"}`).catch(() => null)
})
} catch {
mutee.roles.set([muterole.id])
}
if (reason) {
const sembed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`${mutee.user.username} was successfully muted for ${reason}`)
message.channel.send(sembed);
} else {
const sembed2 = new MessageEmbed()
.setColor("GREEN")
.setDescription(`${mutee.user.username} was successfully muted`)
message.channel.send(sembed2);
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (!channel) return;
let embed = new MessageEmbed()
.setColor('RED')
.setThumbnail(mutee.user.displayAvatarURL({ dynamic: true }))
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("**Moderation**", "mute")
.addField("**Mutee**", mutee.user.username)
.addField("**Moderator**", message.author.username)
.addField("**Reason**", `${reason || "**No Reason**"}`)
.addField("**Date**", message.createdAt.toLocaleString())
.setFooter(message.member.displayName, message.author.displayAvatarURL())
.setTimestamp()
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
} catch {
return;
}
}
}
Hope i get a answer have a wonderful day happy coding...
Make sure that the "mute" role was added to the channel and the permission node "SEND_MESSAGES" was denied.
This does only work if the user's highest role is the "mute" role!

error handling not catching error when reason is given discord.js mute

I made a mute command and I am having trouble handling an error that is thrown by the 'ms' npm package when I dont give a mute reason it works fine, it handles the error properly but when I do give a reason it logs the error and Doesn't handle it like its supposed to I do not know the reason of this and couldn't find a fix online
here is my code;
const Discord = require('discord.js');
const ms = require('ms');
module.exports = {
commands: 'mute',
minArgs: 1,
maxArgs: null,
description: 'Mutes a member so that they can no longer type nor speak in text or voice channels',
info: new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (reason)\n=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu\n =mute #Michael 1d ur gay'},
{ name: '**Info**', value: 'You cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours'}
)
.setFooter("Pepe's Helper command help"),
callback: async (message, args, text, client) => {
if (!message.guild.me.hasPermission("MUTE_MEMBERS")) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I do not have Permission to Mute members**')
.setColor('#FF0000'));
if (!message.guild.me.hasPermission("MANAGE_ROLES")) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I do not have Permission to Manage roles**')
.setColor('#FF0000'));
const target = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
const Embedhelp = new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (reason)\n=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu\n =mute #Michael 1d ur gay'},
{ name: '**Info**', value: 'You cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours'}
)
.setFooter(client.user.tag, client.user.displayAvatarURL());
let reason = args.slice(2).join(" ");
if (!reason) reason = 'No reason Provided'
const ErrorEmbed7 = new Discord.MessageEmbed()
.setDescription(':no_entry: **There was a problem setting permissions for all the channels**')
.setColor('#FF0000')
const ErrorEmbed9 = new Discord.MessageEmbed()
.setDescription(':no_entry: **There was a problem while creating the muted role.**')
.setColor('#FF0000')
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!target) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **Invalid User ID**')
.setColor('#FF0000'))
let botrole = message.guild.roles.cache.find(x => x.name === "Pepe's Helper");
if (target.roles.highest.position > botrole.position) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **My role is not high enough to manage that user, please move my role up the role heiarchy in order to let me manage them.**')
.setColor('#FF0000'));
if (target.hasPermission('ADMINISTRATOR')) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **That user is a Mod/Admin I cannot manage them.**')
.setColor('#FF0000'))
if (target.user.id == message.author.id) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **You cannot mute yourself.**')
.setColor('#FF0000'));
if (target.user.id == client.user.id) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **You cannot mute me.**')
.setColor('#FF0000'));
if (target.roles.cache.find(x => x.name === 'Muted')) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **That user is already muted**')
.setColor('#FF0000'));
if (message.member.roles.highest.position <= target.roles.highest.position) return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **You do not have permission to mute that user, as they have a higher role than you.**')
.setColor('#FF0000'));
try {
let muterole = message.guild.roles.cache.find(x => x.name === 'Muted');
if (typeof muterole === "undefined") {
message.guild.roles.create({
data: {
name: 'Muted',
color: '7e7e7e',
permissions: []
},
reason: 'to mute people',
})
.catch(err => console.log(err).then(message.channel.send(ErrorEmbed9)))
.then((newmuterole => {
target.roles.add(newmuterole)
.then(() => {
message.channel.send(new Discord.MessageEmbed()
.setDescription(':white_check_mark: **Successfully Muted '+target.user.tag+' for ``'+reason+'`` '+ms(ms(args[1]))+'**')
.catch(err => {
console.log(err)
})
.setColor('#0ef606'))
.then(target.send(new Discord.MessageEmbed()
.setTitle('**You have been Muted in:** '+message.guild.name)
.setDescription('**Reason for mute:** ``'+reason+'``\n**Duration:** '+ms(ms(args[1])))
.catch(err => {
console.log(err)
})
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())))
.catch(err => {
console.log(err)
})
})
.catch(err => {
console.log(err);
return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I was unable to mute that user.**')
.setColor('#FF0000'));
})
message.guild.channels.cache.forEach(channel => {
try {
channel.updateOverwrite(newmuterole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false,
READ_MESSAGE_HISTORY: true
});
} catch (err) {
message.channel.send(ErrorEmbed7)
};
})
setTimeout( function () {
target.roles.remove(newmuterole)
}, ms(args[1]))
}))
} else {
target.roles.add(muterole)
.catch(err => {
console.log(err);
return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I was unable to mute that user.**')
.setColor('#FF0000'));
})
.then(() => {
message.channel.send(new Discord.MessageEmbed()
.setDescription(':white_check_mark: **Successfully Muted '+target.user.tag+' for ``'+reason+'`` '+ms(ms(args[1]))+'**')
.setColor('#0ef606'))
.then(target.send(new Discord.MessageEmbed()
.setTitle('**You have been Muted in:** '+message.guild.name)
.setDescription('**Reason for mute:** ``'+reason+'``\n**Duration:** '+ms(ms(args[1])))
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())))
})
message.guild.channels.cache.forEach(channel => {
try {
channel.updateOverwrite(muterole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false,
READ_MESSAGE_HISTORY: true
});
} catch (err) {
message.channel.send(ErrorEmbed7)
};
})
setTimeout( function () {
target.roles.remove(muterole)
}, ms(args[1]))
}
} catch (error) {
console.log(error)
if (error instanceof Error) {
let reason = args.slice(1).join(" ");
if (!reason) reason = 'No reason provided'
let muterole = message.guild.roles.cache.find(x => x.name === 'Muted');
if (typeof muterole === "undefined") {
message.guild.roles.create({
data: {
name: 'Muted',
color: '7e7e7e',
permissions: []
},
reason: 'to mute people',
})
.catch(err => console.log(err).then(message.channel.send(ErrorEmbed9)))
.then((newmuterole => {
target.roles.add(newmuterole)
.then(() => {
message.channel.send(new Discord.MessageEmbed()
.setDescription(':white_check_mark: **Successfully Muted '+target.user.tag+' for ``'+reason+'``**')
.setColor('#0ef606'))
.then(message.target.send(new Discord.MessageEmbed()
.setTitle('**You have been Muted in:** '+message.guild.name)
.setDescription('**Reason for mute:** ``'+reason+'``\n**Duration:** Permanent')
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())))
})
.catch(err => {
console.log(err);
return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I was unable to mute that user.**')
.setColor('#FF0000'));
});
message.guild.channels.cache.forEach(channel => {
try {
channel.updateOverwrite(muterole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false,
READ_MESSAGE_HISTORY: true
});
} catch (err) {
message.channel.send(ErrorEmbed7)
};
})
}))
} else {
target.roles.add(muterole)
.catch(err => {
console.log(err);
return message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I was unable to mute that user.**')
.setColor('#FF0000'));
})
.then(() => {
message.channel.send(new Discord.MessageEmbed()
.setDescription(':white_check_mark: **Successfully Muted '+target.user.tag+' for ``'+reason+'``**')
.setColor('#0ef606'))
.then(target.send(new Discord.MessageEmbed()
.setTitle('**You have been Muted in: '+message.guild.name)
.setDescription('**Reason for mute:** ``'+reason+'``\n**Duration:** Permanent')
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())))
})
message.guild.channels.cache.forEach(channel => {
try {
channel.updateOverwrite(muterole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false,
READ_MESSAGE_HISTORY: true
});
} catch (er) {
message.channel.send(ErrorEmbed7)
};
})
}
} else {
message.channel.send(new Discord.MessageEmbed()
.setDescription(':no_entry: **I was unable to mute that user.**')
.setColor('#FF0000'))
}
}
},
permissions: 'MUTE_MEMBERS',
requiredRoles: []
}
this code tries to mute the target with a timeout using the 'ms' npm package, but if the given time amount is invalid it catches the error that is thrown by the 'ms' npm package (error is thrown due to invalid time amount) and then instead perm mutes the user and sets that 'inavlid time amount' as the reason, the problem is the error catching only works when there is no time amount given, if the time amount is given and is invalid then it for some reason doesn't handle the error
if you did not understand my problem please let me know and I will try to explain better.

Discord.js Mute command only sends embed for incorrect command

So im making a mute command for my discord bot which finds if a "Muted" role exists and if it doesn't then the bot creates a "Muted" role and then gives that role to the mentioned member and currently when i run the command it only gives me the embed that its supposed to send if the command was written incorrectly.
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
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("MUTE_MEMBERS")) return message.channel.send("I do not have Permissions to mute members.");
const Embedhelp = new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu'},
{ name: '**Info**', value: 'You cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours\nYou cannot mute members that have already been muted'}
)
.setFooter(client.user.tag, client.user.displayAvatarURL());
let role = 'Muted'
let muterole = message.guild.roles.cache.find(x => x.name === role);
if (typeof muterole === undefined) {
message.guild.roles.create({
data: {
name: 'muted',
color: '#ff0000',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
.catch(err => console.log(err).then(message.channel.send('Mute Role could not be created')))
}
const mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
let reason = args.slice(1).join(" ");
const banEmbed = 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());
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!mentionedMember) return message.channel.send(Embedhelp);
if (!mentionedMember.bannable) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == message.author.id) return message.channel.send(Embedhelp);
if (muterole = undefined) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == client.user.id) return message.channel.send(Embedhelp);
if (mentionedMember.roles.cache.has(muterole)) return message.channel.send(Embedhelp);
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.channel.send(Embedhelp);
await mentionedMember.send(banEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muterole).catch(err => console.log(err).then(message.channel.send('There was an error while muting the member')))
}
}
I am still unable to find out what the problem is and why it does this, i would very much like to know the error in my code and if there are any more erros that i am unaware of.
We can see your code:
let role = 'Muted'
let muterole = message.guild.roles.cache.find(x => x.name === role);
if (typeof muterole === undefined) {
message.guild.roles.create({
data: {
name: 'muted',
color: '#ff0000',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
.catch(err => console.log(err).then(message.channel.send('Mute Role could not be created')))
}
if (muterole = undefined) return message.channel.send(Embedhelp);
and this will stop the runnning while muterole is undefined.
Since the muterole is not able to create, it will stop running while running to the if muterole line.
To fix the problem, while creating a role in discord.js, permissions flag is needed only when you want to add the permissions to the role. You don't have to put false/deny to specific which permissions you don't want in the role since it's marking all the permissions as false if you don't't label them out.
Therefore, we could replace the permissions with only bracket:
if (muterole === undefined) {
message.guild.roles.create({
data: {
name: 'muted',
color: '#ff0000',
permissions: []
},
reason: 'to mute people',
})
.catch(err => console.log(err).then(message.channel.send('Mute Role could not be created')))
}

How create a unmute command similar to my mute command that requires the permissions of a Moderator or Admin?

I'm currently coding a discord.js discord bot and I have managed to do the basic Kick, Ban & Warn commands (all of which do log to a channel) but now I'm working on the Mute/Unmute commands, I do have the mute command created but the issue I am having right now is creating the Unmute command in a similar format.
This is my mute command
if(command === "mute") {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
let logchannel = message.guild.channels.find('name', 'cgr420-logs');
if (!logchannel) return message.reply('I cannot find a logs channel');
if (!message.member.hasPermission("MUTE_MEMBERS")) return
message.reply(":no_entry_sign: **Error:** You don't have the **Mute Members**
permission!");
if (reason.length < 1) return message.reply('You must supply a reason for the
mute.');
if (message.mentions.users.size < 1) return message.reply('You must mention
someone to mute them.').catch(console.error);
if (!message.guild.member(user).bannable) return
message.reply(`:no_entry_sign: I cannot mute that member`);
message.guild.member(user).ban();
const embed = new Discord.RichEmbed()
.setColor(0xFF0000)
.setTimestamp()
.addField('Action:', 'Mute')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:',
`${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason);
message.channel.send(`:hammer: Bippity boppity **MUTED**! I\'ve logged the
mute in the logs channel.`)
return client.channels.get(logchannel.id).send({embed});
};
I would appreciate any form of help in the right direction.
Thanks In Advance.
if(command === "unmute") {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
let logchannel = message.guild.channels.find('name', 'cgr420-logs');
let role = message.guild.roles.find('name', 'mute')
//CHANGE THIS ^^
if (!logchannel) return message.reply('I cannot find a logs channel');
if (!message.member.hasPermission("MUTE_MEMBERS")) return
message.reply(":no_entry_sign: **Error:** You don't have the **Mute Members**
permission!");
if (reason.length < 1) return message.reply('You must supply a reason for the mute.');
if (message.mentions.users.size < 1) return message.reply('You must mention
someone to mute them.').catch(console.error);
if (!message.guild.member(user).roles.has(role)) return message.reply(`:no_entry_sign: I cannot unmute that member`);
message.guild.member(user).removeRole(role);
const embed = new Discord.RichEmbed()
.setColor("0xFF0000")
.setTimestamp()
.addField('Action:', 'Unmute')
.addField('User:', `${user.tag} (${user.id})`)
.addField('Moderator:',
`${message.author.tag}`)
.addField('Reason', reason);
message.channel.send(`:hammer: Bippity boppity **UNMUTED**! I\'ve logged the
unmute in the logs channel.`)
return logchannel.send(embed);
};
You don’t have to do client.channels.get(logchannel.id).send(), you can just do logchannel.send().
I see that you’ve made it ban the member that has to be "unmuted", I’ve made a variable, mute, that finds a role named 'mute', you can change it to whatever you’d like. The command removes the mute role from the member.
const db = require('quick.db');
module.exports = {
config: {
name: "mute",
description: "Mutes a member in the discord!",
usage: "[name | nickname | mention | ID] <reason> (optional)",
},
run: async (bot, message, args) => {
try {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.channel.send("**You Dont Have Permmissions To Mute Someone! - [MANAGE_GUILD]**");
if (!message.guild.me.hasPermission("MANAGE_GUILD")) return message.channel.send("**I Don't Have Permissions To Mute Someone! - [MANAGE_GUILD]**")
if (!args[0]) return message.channel.send("**Please Enter A User To Be Muted!**");
var mutee = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!mutee) return message.channel.send("**Please Enter A Valid User To Be Muted!**");
if (mutee === message.member) return message.channel.send("**You Cannot Mute Yourself!**")
if (mutee.roles.highest.comparePositionTo(message.guild.me.roles.highest) >= 0) return message.channel.send('**Cannot Mute This User!**')
let reason = args.slice(1).join(" ");
if (mutee.user.bot) return message.channel.send("**Cannot Mute Bots!**");
const userRoles = mutee.roles.cache
.filter(r => r.id !== message.guild.id)
.map(r => r.id)
let muterole;
let dbmute = await db.fetch(`muterole_${message.guild.id}`);
let muteerole = message.guild.roles.cache.find(r => r.name === "muted")
if (!message.guild.roles.cache.has(dbmute)) {
muterole = muteerole
} else {
muterole = message.guild.roles.cache.get(dbmute)
}
if (!muterole) {
try {
muterole = await message.guild.roles.create({
data: {
name: "muted",
color: "#514f48",
permissions: []
}
})
message.guild.channels.cache.forEach(async (channel) => {
await channel.createOverwrite(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false,
CONNECT: false,
})
})
} catch (e) {
console.log(e);
}
};
if (mutee.roles.cache.has(muterole.id)) return message.channel.send("**User Is Already Muted!**")
db.set(`muteeid_${message.guild.id}_${mutee.id}`, userRoles)
try {
mutee.roles.set([muterole.id]).then(() => {
mutee.send(`**Hello, You Have Been Muted In ${message.guild.name} for - ${reason || "No Reason"}`).catch(() => null)
})
} catch {
mutee.roles.set([muterole.id])
}
if (reason) {
const sembed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`${mutee.user.username} was successfully muted for ${reason}`)
message.channel.send(sembed);
} else {
const sembed2 = new MessageEmbed()
.setColor("GREEN")
.setDescription(`${mutee.user.username} was successfully muted`)
message.channel.send(sembed2);
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (!channel) return;
let embed = new MessageEmbed()
.setColor('RED')
.setThumbnail(mutee.user.displayAvatarURL({ dynamic: true }))
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("**Moderation**", "mute")
.addField("**Mutee**", mutee.user.username)
.addField("**Moderator**", message.author.username)
.addField("**Reason**", `${reason || "**No Reason**"}`)
.addField("**Date**", message.createdAt.toLocaleString())
.setFooter(message.member.displayName, message.author.displayAvatarURL())
.setTimestamp()
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
} catch {
return;
}
}
}```
i want for this anyone tell pls

Categories

Resources