Setting perms and giving roles to user - javascript

I am trying to make a mute command for my bot and ran into these issues. I have been getting them for a very long time now.
const { Guild } = require("discord.js");
module.exports = {
name: "mute",
description: "Mutes a member",
execute(message,args,Mention){
if (message.member.hasPermission("ADMINISTRATOR") || message.author.username === "creepersaur"){
let targetMember = message.mentions.members.first();
const guild = message.guild
let myRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!myRole) {
newRole = message.guild.roles.create({
data: {
name: 'Muted',
color: 'BLUE',
Permissions: '',
},
reason: `Make a muted role if it doesn't exist.`
})
.then(console.log)
.catch(console.error);
//message.guild.roles.Muted.setPermissions({'SEND_MESSAGES': true})
targetMember.roles.add(newRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
} else if (myRole) {
targetMember.roles.add(myRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
}
}
}
};
It will see if there is a mute role in the server and if not, then it will create a mute role to give the user. Except the permissions don't work. And because of that, it is not giving the role itself to the user I want. :(
bump x1

I don't really see anything bad in the role section but this code should have the permissions fixed.
const { Guild } = require("discord.js");
module.exports = {
name: "mute",
description: "Mutes a member",
execute(message,args,Mention){
if (message.member.hasPermission("ADMINISTRATOR") || message.author.username === "creepersaur"){
let targetMember = message.mentions.members.first();
const guild = message.guild
let myRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!myRole) {
newRole = message.guild.roles.create({
data: {
name: 'Muted',
color: 'BLUE',
Permissions: '',
},
reason: `Make a muted role if it doesn't exist.`
})
.then(console.log)
.catch(console.error);
message.guild.channels.cache.forEach(ch =>
{
if(ch.type == "text") {
ch.updateOverwrite(
newRole, {
SEND_MESSAGES: false
}
targetMember.roles.add(newRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
} else if (myRole) {
targetMember.roles.add(myRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
}
}
}
};

Related

discord.js creating a role with permissions

how can i make the bot create a role with specific permissions? (in this case it has to set SEND_MESSAGES to disabled), this is the code i made:
var muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!muteRole) message.guild.roles.create(
{ data: { name: 'Muted', reason: 'the role is needed', permissions: ["SEND_MESSAGES" = false]} });
You will have to create the role first, then modify the permissions, this cannot be done in one function call. Here's how you can do it:
var muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!muteRole) message.guild.roles.create({
data: {
name: 'Muted',
reason: 'the role is needed'
}
})
.then(role => role.setPermissions(["ANY_PERMISSION_HERE"])
.catch(error => /* catch error (optional) */);
Or if you want, you can use JavaScript's async/await API:
try {
var muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!muteRole) muteRole = await message.guild.roles.create({
data: {
name: 'Muted',
reason: 'the role is needed'
}
});
muteRole.setPermissions(["YOUR_PERMISSIONS"]);
} catch (error) {
// catch the error (optional)
}

how to make a role without send messages permission using discord.js

I'm making a discord bot but i can not figure out how to make a muted role without send messages permissions. Heres what i have so far:
var role = message.guild.roles.cache.find(r => r.name === 'muted');
if(!role) {
message.guild.roles.create({
data: {
name: 'muted',
color: 0,
permissions: [SEND_MESSAGES, false],
},
})
}
Any help would be great!
You should use the client/bot function? like:
var guild = client.guilds.cache.get('guild-id'); //<-- Change guild-id to guild id
var role = guild.roles.cache.find(role => role.name == 'muted');
if(!role) {
async function mutedR() {
let role1 = await guild.roles.create({
data: {
name: 'muted',
color: 0,
},
})
guild.channels.cache.forEach(async (channel, id) => {
await channel.createOverwrite(role1, {
SEND_MESSAGES: false,
});
});
message.channel.send(`Created Muted Role For Test ${role1}`) //<-- You can change this message as well
}
mutedR()
}
Also, I perfected the code a little bit.
You can also check the code here: https://cdn.discordapp.com/attachments/817529510948896772/841117091754016808/Recording_3.mp4

The bot does not write in a private message Discord.js

I want to make the bot write to the BOT through the mention and through the ID.
Now it only works via ID
client.on("message", async (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(" ");
const command = args.shift().toLowerCase();
const target = message.mentions.members.first() || message.guild.members.cache.get(args[0])
const { guild } = message;
const { name, region, memberCount, owner, afkTimeout } = guild;
const icon = guild.iconURL();
const User = client.users.cache.get(`${args[0]}`);
const time = args.slice(1).join(" ");
const reason = args.slice(2).join(" ");
if (command === "mute") {
client.users.fetch(args[0]).then((target) => {
target.send({
embed: {
title: `${User.username}`,
description: `**Miderator:** ${message.author} \n**Time:** ${args[1]} \n**Reason:** ${reason}`,
thumbnail: {
url: `${User.avatarURL()}`,
},
},
});
}); }});
You can do like
let person = message.mentions.users.first().id || args[0]
client.users.fetch(person).then(target => {
target.send({
embed: {
title: `${User.username}`,
description: `**Miderator:** ${message.author} \n**Time:** ${args[1]} \n**Reason:** ${reason}`,
thumbnail: {
url: `${User.avatarURL()}`,
},
},
});
});

Discord.js Error Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes

I'm making a mute command for my bot where it creates a muted role if there isn't one already and gives it to the user that is mentioned in the command, currently the error im getting is;
[INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
My best guess is that this error occurs because it doesn't create the role that it is supposed to create therefor it cannot give it to the mentioned member, i may be completely wrong though.
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' || 'Muted';
let newrole = message.guild.roles.cache.find(x => x.name === role);
if (typeof newrole === undefined) {
message.guild.roles.create({
data: {
name: 'Muted',
color: '#ff0000',
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');
};
};
let muterole = message.guild.roles.cache.find(x => x.name === role);
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 (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)
.then(() => message.channel.send("There was an error while muting the member"))
.catch((err) => console.log(err));
}
}
The line of code where the role is created is:
message.guild.roles.create({
data: {
name: 'Muted',
color: '#ff0000',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
You can use either async/await or .then, but i recommend using async/await. For example:
const mentionedMember = message.mentions.members.first() || await
message.guild.members.fetch(args[0]);
const newMutedRole = await message.guild.roles.create({
data: {
name: 'Muted',
color: '#ff0000',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
mendtionedMember.roles.add(newMutedRole)

Overwrite Permissions for all channels in a discord server

I'm trying to create a moderation discord bot with a mute command. The mute command works in the channel that you send the command in but it doesn't work in all of the other channels. I've tried to have it go over all channels using forEach() but that doesn't seem to work. I've looked through this and tried the other solutions but its still not working. Here is the code, I hope you can help.
const Discord = require("discord.js");
const ms = require('ms')
module.exports = {
name: "mute",
aliases: [],
category: "moderation",
run: async(bot, message, args) => {
let toMute = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[0]));
if(!toMute) return message.channel.send("Couldn't find the user.");
if(toMute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them")
let muteRole = message.guild.roles.cache.find(muteRole => muteRole.name === "Muted");
//This is where the problem starts
if(!muteRole){
muteRole = await message.guild.roles.create({ data: { name: "Muted", color: 0x000000, permissions: [] } })
message.guild.channels.cache.each(async (channel) => {
await channel.overwritePermissions(muteRole, {
"SEND_MESSAGES": false,
"ADD_REACTIONS": false,
"TALK": false
});
});
}
let muteTime = args[1];
if(!muteTime) return message.reply("Please Specify a time.");
await(toMute.roles.add(muteRole));
const mEmbed = new Discord.MessageEmbed()
.setTitle("Muted")
.addFields({ name: "Member", value: toMute, inline: false },
{ name: "Time", value: muteTime })
.setTimestamp()
message.channel.send(mEmbed)
setTimeout(function() {
toMute.roles.remove(muteRole);
message.channel.send(`<#${toMute.id}> has been unmuted`);
}, ms(muteTime))
}
}
I changed the overwritePermissions() to updateOverwrite() and it seemed to work. Here is the code:
if(!muteRole){
muteRole = await message.guild.roles.create({
data: {
name: "Muted",
color: "#000000",
permissions: [],
},
});
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(muteRole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false
})
});
}
I also organized the code to make it easier to see.

Categories