Discord.js - Give role a all channel - discord.js

Hello I would like to create an order (! Giverole) so that it gives the roles (mute) to all the channels of the server or to be made the order.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
var mute_role = message.guild.roles.find(r => r.name == 'mute', {READ_MESSAGES: true, SEND_MESSAGES: false})
if (!mute_role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.overwritePermissions(channel => channel.addRole(mute_role));
var lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
thank you in advance

At the fist - try always get role with role ID, its more safely.
If I understand your question correctly and you need a certain role on all channels to establish certain rights. So you can use this code.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
let muteRole = message.guild.roles.get('ROLEID')
if (!muteRole) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.map(channel => {
if(channel.type === 'text') {
channel.overwritePermissions(muteRole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
})
.then(console.log)
.catch(console.log);
}
})
let lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
}
})
```

Related

When i try to create a role it gives me an error (discord.js)

So i am trying to make a command that mute a member. I want my bot to check if there is role name Muted and if there is not, to create a role for Muted members.
This is the code:
module.exports = {
name: 'mute',
description: 'mutes a member',
execute(message, args, Discord, bot) {
let mutedRole = message.guild.roles.cache.find(r => r.name === 'Muted')
if(!mutedRole) {
Guild.roles.create({
data: {
name: 'Muted',
color: 'BLACK'
}
})
}
}
}
and the error is this:
C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\mute.js:10
Guild.roles.create({
^
TypeError: Cannot read property 'create' of undefined
I don't think you should create a role via code. I think you should create a role in your Discord server (like actually just making one without code). Download the ms package. (npm i ms) Then, paste this code in:
const ms = require('ms');
module.exports = {
name: "mute",
description: "Mutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
if (!args[1]){
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted.`);
return;
}
if (isNaN(args[1]) || !args[1] === ' '){
message.channel.send("Please enter a real number! (If you have a space after the username and you don\'t want to set a time limit, delete the space. YOU HAVE TO.)");
return;
}
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);
setTimeout(function(){
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
}, ms(args[1]));
} else {
message.channel.send("Can't find that member!");
}
}
}
Thanks to CodeLyon for this code. Hope this works for you! It even includes a time limit.
format 1: !mute #User
format 2: !mute #User 1000 (1000 can be changed, just make sure it's in milliseconds)
module.exports = {
name: "unmute",
description: "Unmutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unmuted.`);
} else {
message.channel.send("Can't find that member!");
}
}
}
format: !unmute #User
Remember, this code only works if you have a role Member and a role Muted. So, in your server, add the role Member to everybody and add a role Muted (not to everybody).
Hope this works! If there's any need for clarification, please tell me in the comments.

What's the prefix for mute

Problems with my bot. Can't get mute to work. Help? Can't find any prefix and don't know where to add it or how to format it. I linked most of code below. Anti-spam and kick/ban works. New to coding to any help would be nice. Tips how set a general prefix for all code foward? Role is named mute and bot has all premissons it shall need to kick
const fs = require('fs');
module.exports = class mute {
constructor(){
this.name = 'mute',
this.alias = ['tempmute'],
this.usage = 'mute';
}
run(bot, message, args){
let member = message.mentions.members.first();
var command = args[0];
var mentioned = args[1];
var days = parseInt(args[3]);
var hours = parseInt(args[4]);
var seconds = parseInt(args[5]);
if (message.member.hasPermission('MANAGE_ROLES')) {
let muterole = message.guild.roles.find(role => role.name === "Muted");
if (!message.guild) {
if (message.guild.id === '505872328538718233') {
let memberrole = message.guild.roles.find("name", "Member");
member.removeRole(memberrole);
}}
let usermsg = new Discord.RichEmbed();
usermsg.setTitle('You have been Muted.');
usermsg.setColor('76b3fc');
usermsg.setFooter('Please do not attempt to bypass');
usermsg.addField('Muted by:',
`<#${message.author.id}>`);
let mutedmsg = new Discord.RichEmbed();
mutedmsg.setTitle('User has been Muted Successfully');
mutedmsg.setColor('76b3fc');
mutedmsg.setDescription(`User muted: ${mentioned}\nMuted by: <#${message.author.id}>\nReason: ${input}`);
mutedmsg.setFooter('This mute has been logged.');
if (message.content === `${command}`) {
return message.channel.send('You did not provide a member to mute.');
}
if (message.content === `${command} ${mentioned}`) {
return message.channel.send('Please input a reason for the mute.');
}
if (message.guild.roles.find(role => role.name)) {
message.member.addRole(muterole);
if (message.content.includes (`${days}d`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${hours} Seconds`);
}, `${args[2]} * 86400`);
}
if (message.content.includes (`${hours}h`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${hours} Seconds`);
}, `${args[3]} * 3600`);
}
if (message.content.includes (`${seconds}s`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${seconds} Seconds`);
}, `${args[4]} * 1000`);
}
if (message.content === `${command} ${mentioned} ${input}`) {
message.member.addRole(muterole);
usermsg.addField('Muted for',
`${input}`);
usermsg.addField('Punishment Time:',
'Permenant');
message.channel.send(mutedmsg);
}
if (message.member.id === `${message.author.id}`) {
return;
}
if (message.author.id === `${mentioned}`) {
return message.member.send(usermsg);
}
message.channel.send(mutedmsg);
console.log('===========================');
console.log(`Member Muted: ${mentioned}`);
console.log(`Muted by: ${message.author.tag}`);
console.log(`Reason: ${input}`);
console.log('===========================');
} else {
message.channel.send('You do not have a `Muted` Role, This command won\'t work.');
}
} else {
message.reply('You do not have permission to do this.');
}
let jsonlogs = JSON.parse(fs.writeFileSync("./storages/mutelogs.json"));
if (!jsonlogs[message.guild.id]){
jsonlogs[message.guild.id] = {
mutedby: `${message.author.tag}`,
user: `${mentioned}`,
reason: `${input}`,
days: `${days}`,
hours: `${hours}`,
seconds: `${seconds}`,
};
}
}
};
You seem to have a lot, and I mean A LOT of outdated methods from Discord.js v11.
I'd highly recommend installing the newest version of DJS and reading all of the v12 changes that can be found here:
https://github.com/discordjs/discord.js/releases/tag/12.0.0
Some examples:
Discord.RichEmbed() no longer exists -> Use Discord.MessageEmbed()
.addRole() no longer exists -> Use message.member.roles.add()
.removeRole() no longer exists -> Use message.member.roles.remove()

Discord.JS | Check If channel exists Ticket bot

So Hello again,
I am making a ticket bot for discord and I got this bug that I cannot solve it my self.
here's the create ticket command:
if(cmd === "new"){
const reason = message.content.split(" ").slice(1).join(" ");
if (message.guild.channels.exists("name", "ticket-" + message.author.username)) return message.channel.send(`You already have a ticket open.`);
message.guild.createChannel(`ticket-${message.author.username}`, "text").then(c => {
let role = message.guild.roles.find("name", "Support Team");
let role2 = message.guild.roles.find("name", "#everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(message.author, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
var embedcreated = new Discord.RichEmbed()
.setColor("#f00202")
.setDescription(`You ticket has been created ` + message.guild.channels.find(channel => channel.name === c.name).toString())
.setTitle("Tickets | MiZ")
.setFooter(`Tickets System`)
.setTimestamp();
message.channel.send(embedcreated);
const embed = new Discord.RichEmbed()
.setColor("#f00202")
.addField(`Hey ${message.author.username}!`, ` Please explain your problen to the staff team.`)
.setTimestamp();
c.send({ embed: embed });
}).catch(console.error);
let sChannel = message.guild.channels.find(x => x.name === "logs");
if(!sChannel) return message.channel.send("logs channel not found.")
var staff = new Discord.RichEmbed()
.setColor("#f00202")
.addField("Created a ticket: " , message.author)
.setTitle("Logs | MiZ")
.setTimestamp();
sChannel.send(staff)
}
I have a line that checks if the channel exists but it doesn't work as I can create more tickets.
Used:
Discord.js: ^11.3.2
Please next time be more specific and use the javascript block code so it's more understandeble
no block code
"Javascript block code"

Bot creates a second channel for no reason

I have a big mistake. Everything works perfectly! But the bot creates two instead of one channel. Why is that? I've been trying to figure it out for myself. But I can't find the error.
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.guild.id !== "601109434197868574") return;
if (reaction.emoji.name === "🛑") {
if (reaction.message.channel.id === "732018576604528640");
const channelName = `•┇ticket-${user.username}`
if(reaction.message.guild.channels.cache.find(channel => channel === `•┇ticket-${user.username}`)){
return user.send("Du hast bereits ein offnes Ticket!")
}
reaction.message.guild.channels.create(channelName, {parent: '731947024932667432', topic: `Ticket Owner: ${user}`}).then(c => {
const everyone = reaction.message.guild.roles.cache.find(role => role.name === '#everyone')
const sr = reaction.message.guild.roles.cache.find(role => role.name === 'ticketsuppport')
c.updateOverwrite(sr, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
c.updateOverwrite(everyone, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false,
});
c.updateOverwrite(user, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
let GreetEmbed = new Discord.MessageEmbed()
.setColor(colours.maincolour)
.setDescription(`> Guten Tag, ${user}!\n> \n> Du hast nun ein Support-Ticket erstellt. Wie können wir dir helfen?\n> \n> \🔒 Ticket schließen | \🆘 Weitere hilfe anfordern`)
.setFooter(`Ticket erstellt`)
.setTimestamp()
c.send(GreetEmbed)
let ping = c.send(`${user}`).then(message => {
message.delete(ping)
})
})
}```
You most-likely have two instances of the bot running.
To verify this, you can make a change to the code (like modifying the message it sends when creating the channel). If both channels have the modification, I am wrong xD. If not, you need to find where your second bot it running (separate server, minimized window, etc..).
if (reaction.message.guild.channels.cache.find(channel => channel.name === channelName)) {
return user.send("Du hast bereits ein offenes Ticket!")
}
I think you forgot the channel.name because otherwise it filters for the channel object which will never be the same as a string and throughout that it'll never return. (BTW: There's also a typo with offnes)

Cannot read the property 'roles' of undefined

I'm making a bot and I have an error that I don't understand in this code : pas
const Discord = require("discord.js");
const client = new Discord.Client();
const token = "";
client.login(token)
client.on("message", async(message) => {
let staffRole = message.guild.roles.find("name", "Staff");
let staff = message.guild.member(message.author);
if (message.author.id === "424974772959444993" || message.member.roles.has(staffRole.id)) {
return;
}
var badWords = [
'asd',
'legionmods',
'verga',
'vrga',
'nmms',
'alv',
'electromods',
'remake'
];
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
if (containsBadWord) {
message.delete();
message.author.send({embed: {
color: 3447003,
description: `Has dicho una palabra que no esta permitida en este servidor`
}
message.channel.send(`${prefix}tempmute ${message.author}`+" 5m palabra prohibida")
}
});
This is an error I get :
(node:4952) UnhandledPromiseRejectionWarning: TypeError: Cannot read property
'roles' of null
at Client.client.on (C:\Users\Francisco\Desktop\role\app.js:8:33)
Could someone help me please ? I am not good in debugging errors.
message.guild is probably returning null because the message was sent in a dm conversation, not a guild.
You can avoid this problem by writing:
if (message.channel.type !== 'text') return;
Also, a few GuildMemberRoleManager methods have changed a bit since discord.js v12+. You should replace:
let staffRole = message.guild.roles.find("name", "Staff");
With:
let staffRole = message.guild.roles.cache.find(role => role.name === "Staff");
And replace:
message.member.roles.has(staffRole.id)
With:
message.member.roles.cache.has(staffRole.id)

Resources