How to create a channel that only a given role can see? - discord.js

msg.guild.createRole({
name: msg.author.username,
color: "#ff0000"
}).then(role => {
msg.member.addRole(role)
})
I want only this role can see this channel
guild.createChannel( `${msg.author.username}`, "text")
.then(channel => {
let category = guild.channels.find(c => c.name == "INFO" && c.type == "category");
if (!category) throw new Error("Category channel does not exist");
channel.setParent(category.id).then(
channel.send(embed)
it is possible?

It's possible to create a channel that only a given role can see. It's called Overwrite Permission
To add new permission in a channel, use like this
<Text Channel>.overwritePermission(<Role>,
{
VIEW_CHANNEL: true,
SEND_MESSAGES: true /* you can remove send messages part if need */
}
)
Replace <Text Channel> with text channel defined, <Role> with role defined as your code like this
msg.guild.createRole({
name: msg.author.username,
color: "#ff0000"
}).then(role => {
msg.member.addRole(role)
guild.createChannel( `${msg.author.username}`, "text")
.then(channel => {
channel.overwritePermission(role, {
VIEW_CHANNEL: true,
SEND_MESSAGES: true
})
})
})
Also you can read the docs about it by pressing here

Related

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.

Cache a guild user by id discord.js

I'm making a moderation bot with my friend and I am trying to make it so if a user is muted when the bot restarts or crashes, on startup it loops all users in my database per guild and checks if they still have mute time to serve, then use a setTimeout() to wait however long until their muted role gets removed, however the bot does not have the user cached so I get an error where the user is undefined. If anyone knows how to cache a user by id or do this in another way any help is appreciated.
My code:
client.on("ready", () => {
client.user.setActivity(process.env.STATUS);
console.log(`Logged in as ${client.user.tag}`);
console.log(`Guilds: ${client.guilds.cache.size}`);
client.guilds.cache.forEach(function (guild) {
console.log(guild.name, ":", guild.id);
for (user in db.get(`${guild.id}.users`)) {
if (
ms(db.get(`${guild.id}.users.${moderation.mute.time}`)) +
Date.now(db.get(`${guild.id}.users.${moderation.mute.date}`)) >=
Date.now()
) {
let mutedRole = message.guild.roles.cache.find(
(mR) => mR.name === "Muted"
);
if (!mutedRole)
mutedRole = await message.guild.roles.create({
data: { name: "Muted", color: "#000000", permissions: [] },
});
client.guild.channels.cache.forEach(async (channel) => {
await channel.updateOverwrite(mutedRole, {
SEND_MESSAGES: false,
SPEAK: false,
VIDEO: false,
ADD_REACTIONS: false,
SEND_TTS_MESSAGES: false,
ATTACH_FILES: false,
});
});
let user = client.users.cache.get(user);
user.roles.remove(mutedRole);
}
}
});
});
You can cache or even save the id of a user and get the assigned GuildMember back by this method:
// 'user' will become the GuildMember of your cached id
let user = null;
// 'cachedId' is the id of the cached user
let cachedId = yourCachedId;
client.users.fetch(cachedId).then(usr => {user = usr})

How can I change user permissions for sending messages for all channels?

How can I change user permissions for sending messages for all channels?
I want to block user sending messages to all channels by discord.js.
I try this in code:
let member = message.mentions.members.first()
member.updateOverwrite(client.guild.roles.member, { SEND_MESSAGES: false });
You can iterate over the channels in a particular guild, then modify the permissions for a particular user.
client.on('message', message => {
if (message.mentions.members.array().length === 0) return message.reply('No user was mentioned.');
message.guild.channels.cache.each(channel => {
channel.overwritePermissions([{
id: message.mentions.members.first().id, // user ID
deny: 'SEND_MESSAGES'
}]).catch(err => console.error(err));
});
});
If you want to only edit the permissions on certain channels, you can use this:
client.on('message', message => {
if (message.mentions.members.array().length === 0) return message.reply('No user was mentioned.');
[/* channel IDs */].forEach(channel => {
message.guild.channels.cache.get(channel).overwritePermissions([{
id: message.mentions.members.first().id, // user ID
deny: 'SEND_MESSAGES'
}]).catch(err => console.error(err));
});
});
});
If you want to exclude certain channels from all of them, you can use this:
client.on('message', message => {
if (message.mentions.members.array().length === 0) return message.reply('No user was mentioned.');
message.guild.channels.cache.each(channel => {
if ([/* channel IDs */].includes(channel.id) return;
channel.overwritePermissions([{
id: message.mentions.members.first().id, // user ID
deny: 'SEND_MESSAGES'
}]).catch(err => console.error(err));
});
});
References:
GuildChannel.overwritePermissions()

TypeError [INVALID_TYPE]: Supplied roles is not an Role, Snowflake or Array or Collection of Roles or Snowflakes

I have a code where if mutes a mentioned person by giving it a role with no permissions but then I can't assign the role
Here's the code
try{
muterole = message.guild.roles.create({
data: {
name: 'muted',
color: 'BLUE',
permissions:[0]
}
})
}catch(err){
console.log(err);
message.channel.send("An error occured logs were sent to the dev")
}
message.mentions.members.first().roles.add(muterole.id);
Any help is apreciated :)
message.guild.roles.create({
data: {
name: "Muted",
color: "BLUE",
permissions: []
}
}).then(role => {
message.mentions.members.first().roles.add(role).catch(error => {message.channel.send("Couldn't add the role."); console.error(error)});
}).catch(error => {message.channel.send("An error occured, logs were sent to the developer."); console.error(error)});

React Native If Exist in Firebase

My firebase structure:
Hello, i am trying;
One person opening a announcement with own userid. After another person get in this announcement's inside. If second person wants to send a notification to first person, he uses first person's userid's table in firebase and he put own userid's to first persons userid's table. If first person wants to see, who sends notification to him, he looks to own user id's table and he sees other peoples userids (other people are sended notification to him).. Now one person can send lots of time notification, i want to one person can send just one time for this reason i am trying to control it.
if (firebase.database().ref(`/bavuruistek/${userid}`).child(katilan) === null ) {
firebase.database().ref(`/bavuruistek/${userid}`)
.push({
katilan, istek })
.then(() => {
dispatch({ type: STUDENT_REQUEST_SUCCESS });
Actions.pop();
});
}
if (firebase.database().ref(`/bavuruistek/${userid}`).child(katilan) !== null) {
console.log(firebase.database().ref(`/bavuruistek/${userid}/${katilan}`));
Alert.alert(
'Mesaj',
'Daha önce başvurunuz yapılmış!',
[
{ text: 'Tamam', onPress: () => null }
]
);
}
firebase.database().ref(`/basvuruistek/${userid}`).on('value', (snapshot) => {
const { currentUser } = firebase.auth();
const notes = snapshot.val();
Object.keys(notes).forEach(key => {
if (notes[key].katilan !== currentUser.uid) {
this.setState({ click: true });
} if (notes[key].katilan === currentUser.uid) {
this.setState({ click: false });
}
});
});
You are trying to use firebase.database().ref(`/bavuruistek/${userid}`).child(katilan) inside an if statement, which doesn't work because 1) .child() returns a Reference object. Trying something like this may help you achieve the intended outcome:
firebase.database().ref(`/bavuruistek/${userid}`).child(katilan).once('value').then(snapshot => {
if (snapshot.val() === null ) {
firebase.database().ref(`/bavuruistek/${userid}`)
.update({
katilan, istek
})
.then(() => {
dispatch({ type: STUDENT_REQUEST_SUCCESS });
Actions.pop();
});
} else {
console.log(snapshot.val());
Alert.alert(
'Mesaj',
'Daha önce başvurunuz yapılmış!',
[
{ text: 'Tamam', onPress: () => null }
]
);
}
}
The main difference is that I'm using .once, reading the resulting snapshot value, and using that as part of the if statement to check if it is null.

Resources