Поиск роли discord js v12
Permissions are Discord's primary feature, enabling users to customize their server's workings to their liking. Essentially, Permissions and permission overwrites tell Discord who is allowed to do what and where. Permissions can be very confusing at first, but this guide is here to explain and clarify them, so let's dive in!
If you want to keep your bot's permission checks simple, you might find it sufficient to check if the member executing the command has a specific role.
If you have the role ID, you can check if the .roles Collection on a GuildMember object includes it, using .has() . Should you not know the ID and want to check for something like a "Mod" role, you can use .some() .
If you want to enhance this system slightly, you can include the guild owner by comparing the executing member's ID with message.guild.ownerId .
To include permission checks like ADMINISTRATOR or MANAGE_GUILD , keep reading as we will cover Discord Permissions and all their intricacies in the following sections.
- Permission: The ability to execute a certain action in Discord
- Overwrite: Rule on a channel to modify the permissions for a member or role
- Bit field: Binary representation of Discord permissions
- Flag: Human readable string in MACRO_CASE (e.g., 'KICK_MEMBERS' ) that refers to a position in the permission bit field. You can find a list of all valid flags on the Permissions.FLAGS
You can provide permission decimals wherever we use flag literals in this guide. If you are interested in a handy permission calculator, you can look at the "Bot" section in the Discord developer portal
Base permissions are set on roles, not the guild member itself. To change them, you access a Role object (for example via member.roles.cache.first() or guild.roles.cache.random() ) and use the .setPermissions() method. This is how you'd change the base permissions for the @everyone role, for example:
Any permission not referenced in the flag array or bit field is not granted to the role.
Note that flag names are literal. Although VIEW_CHANNEL grants access to view multiple channels, the permission flag is still called VIEW_CHANNEL in singular form.
Alternatively you can provide permissions as a property of the CreateRoleOptions
open in new window typedef during role creation as an array of flag strings or a permission number:
open in new window and provide a permission flag, array, or number to check for. You can also specify if you want to allow the ADMINISTRATOR permission or the guild owner status to override this check with the following parameters.
If you provide multiple permissions to the method, it will only return true if all permissions you specified are granted.
You can learn more about the .has() method here.
Permission overwrites control members' abilities for this specific channel or a set of channels if applied to a category with synchronized child channels.
As you have likely already seen in your desktop client, channel overwrites have three states:
- Explicit allow ( true , green ✓)
- Explicit deny ( false , red X)
- Default ( null , gray /)
To add a permission overwrite for a role or guild member, you access the channel's PermissionOverwriteManager
open in new window and use the .create() method. The first parameter is the target of the overwrite, either a Role or User object (or its respective resolvable), and the second is a PermissionOverwriteOptions
Let's add an overwrite to lock everyone out of the channel. The guild ID doubles as the role id for the default role @everyone as demonstrated below:
Any permission flags not specified get neither an explicit allow nor deny overwrite and will use the base permission unless another role has an explicit overwrite set.
You can also provide an array of overwrites during channel creation, as shown below:
To edit permission overwrites on the channel with a provided set of new overwrites, you can use the .edit() method.
To replace all permission overwrites on the channel with a provided set of new overwrites, you can use the .set() method. This is extremely handy if you want to copy a channel's full set of overwrites to another one, as this method also allows passing an array or Collection of PermissionOverwrites
To remove the overwrite for a specific member or role, you can use the .delete() method.
If the permission overwrites on a channel under a category match with the parent (category), it is considered synchronized. This means that any changes in the categories overwrites will now also change the channels overwrites. Changing the child channels overwrites will not affect the parent.
To easily synchronize permissions with the parent channel, you can call the .lockPermissions() method on the respective child channel.
To check your bot's permissions in the channel the command was used in, you could use something like this:
The .permissionsFor() and .permissionsIn() methods return a Permissions object with all permissions set if the member or role has the global ADMINISTRATOR permission and does not take overwrites into consideration in this case. Using the second parameter of the .has() method as described further down in the guide will not allow you to check without taking ADMINISTRATOR into account here!
If you want to know how to work with the returned Permissions objects, keep reading as this will be our next topic.
open in new window object is a discord.js class containing a permissions bit field and a bunch of utility methods to manipulate it easily. Remember that using these methods will not manipulate permissions, but rather create a new instance representing the changed bit field.
discord.js provides a toArray() method, which can be used to convert a Permissions object into an array containing permission flags. This is useful if you want to display/list them and it enables you to use other array manipulation methods. For example:
Additionally, you can serialize the Permissions object's underlying bit field by calling .serialize() . This returns an object that maps permission names to a boolean value, indicating whether the relevant "bit" is available in the Permissions instance.
Some methods and properties in discord.js return permission decimals rather than a Permissions object, making it hard to manipulate or read them if you don't want to use bitwise operations. However, you can pass these decimals to the Permissions constructor to convert them, as shown below.
You can also use this approach for other PermissionResolvable
open in new window s like flag arrays or flags.
The Permissions object features the .has() method, allowing an easy way to check flags in a Permissions bit field. The .has() method takes two parameters: the first being either a permission number, single flag, or an array of permission numbers and flags, the second being a boolean, indicating if you want to allow the ADMINISTRATOR permission to override (defaults to true ).
Let's say you want to know if the decimal bit field representation 268550160 has MANAGE_CHANNELS referenced:
The Permissions object enables you to easily add or remove individual permissions from an existing bit field without worrying about bitwise operations. Both .add() and .remove() can take a single permission flag or number, an array of permission flags or numbers, or multiple permission flags or numbers as multiple parameters.
You can utilize these methods to adapt permissions or overwrites without touching the other flags. To achieve this, you can get the existing permissions for a role, manipulating the bit field as described above and passing the changed bit field to role.setPermissions() .
If you want to compare your code to the code we've constructed so far, you can review it over on the GitHub repository here
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
8 contributors
Ответы 3
В объекте GuildMember у вас есть доступная функция имеет разрешение. Так что вы можете просто сделать member.hasPermission('ADMINISTRATOR')
Если вас интересуют все остальные строки, для которых разрешается разрешение, вы можете найти их в файле discord.js документы.
if (message.content.startsWith('!kick') && member.hasPermission('ADMINISTRATOR')) < это то, что я сделал, но я получил ReferenceError: член не определен
Вероятно, вам следует опубликовать больше своего кода, чтобы увидеть контекст этого. И как вы получаете/получаете фактический объект-член.
В этом контексте вам понадобится message.member.hasPermission('ADMINISTRATOR')
Часть следующего кода необходимо изменить для использования в новейшей основной версии Discord.js (v12 на момент редактирования) из-за реализации менеджеров.
На самом деле здесь необходимо ответить на три разных вопроса. Все они связаны, но у каждого есть разные прямые ответы.
How do I check if the message author has an Admin role?
Вы можете искать роль двумя основными способами:
Итак, связывая все это вместе:
How do I check if the message author's role has the Administrator permission?
Вы также можете применить эту концепцию к любой конкретной роли.
Лучший способ в этой ситуации.
How do I check if the message author has the Administrator permission?
Рассмотрим этот короткий пример:
Я пробовал иметь разрешения для конкретной роли, но это означает, что на всех серверах, на которых работает бот, должна быть одинаковая роль.
Для объекта GuildMember доступна функция hasPermission. Так что вы можете просто сделать member.hasPermission(‘ADMINISTRATOR’)
Если вас интересуют все остальные строки, которые разрешаются разрешением, вы можете найти их в документах discord.js.
Здесь действительно нужно рассмотреть три разных вопроса. Они все связаны, но у каждого разные прямые ответы.
Коллекцию ролей участников можно получить с помощью GuildMember.roles .
Вы можете искать роль двумя основными способами:
Итак, связывая все это вместе:
- Опять же, нам нужно использовать GuildMember из Message.member .
- И снова нам нужно использовать коллекцию GuildMember.roles .
- И. дежа вю. вы можете искать в коллекции с помощью Collection.find() .
- На этот раз вы должны специально проверить Role.hasPermission() в функции предиката.
Вы можете применить эту концепцию и к любой конкретной роли.
Лучший метод для этой ситуации.
- Мы продолжаем использовать Message.member для доступа к GuildMember.
- Тем не менее, вы можете проверить все права доступа члена с помощью GuildMember.hasPermission() .
Рассмотрим этот короткий пример:
t1mofe1 commented Dec 1, 2020 •
It works partially, like when I run the command and I react, I get the role, others dont, but if they run it, they do, I dont, how do I fix that so that only me can run the command and everyone gets the role
TheMutedPlayer commented Dec 22, 2020
TheMutedPlayer commented Dec 22, 2020
It wont work this is the code i have const Discord = require("discord.js");
module.exports = name: "Coolperson",
aliases: ["cool", "Cool"],
args: true, // or false
cooldown: 1, // in seconds
description: "description",
execute(message, args, client) // command code
client.on("message", async message => // Checking if the message author is a bot.
if (message.author.bot) return false;
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Roles and Permissions
Roles are a powerful feature in Discord, and admittedly have been one of the hardest parts to master in discord.js. This walk through aims at explaining how roles and permissions work. We'll also explore how to use roles to protect your commands.
Let's start with a basic overview of the hierarchy of roles in Discord.
. or actually not, they already explain it better than I care to: Role Management 101. Read up on that, then come back here. I'll wait. (Yeah I know that's cheesy, so sue me).
Let's get down to brass tacks. You want to know how to use roles and permissions in your bot.
Get Role by Name or ID
This is the "easy" part once you actually get used to it. It's just like getting any other Collection element, but here's a reminder anyway!
To get the ID of a role, you can either mention it with a \ before it, like \@rolename , or copy it from the role menu. If you mention it, the ID is the numbers between the <> . To get the ID of a role without mentioning it, enable developer mode in the Appearance section of your user settings, then go to the role menu in the server settings and right click on the role you want the ID of, then click "Copy ID".
Check if a member has a role
In a messageCreate handler, you have access to checking the GuildMember class of the message author:
To grab members and users in different ways see the FAQ Page.
Get all members that have a role
Add a member to a role
Alright, now that you have roles, you probably want to add a member to a role. Simple enough! Discord.js provides 2 handy methods to add, and remove, a role. Let's look at them!
Alright I feel like I have to add a little precision here on implementation:
- You can not add or remove a role that is higher than the bot's. This should be obvious.
- The bot requires MANAGE_ROLES permissions for this. You can check for it using the code further down this page.
- Because of global rate limits, you cannot do 2 role "actions" immediately one after the other. The first action will work, the second will not. You can go around that by using .roles.set([array, of, roles]) . This will overwrite all existing roles and only apply the ones in the array so be careful with it.
Check specific permission of a member on a channel
To check for a single permission override on a channel:
We pass false for the checkAdmin parameter because Administrator channel overwrites don't implicitly grant any permissions, unlike in Roles or when you are the Guild Owner. (The API will allow you to create an overwrite with Administrator, and even tell D.JS that a channel overwrite has had Administrator permissions set. Discord developers have stated this is intended behavior.)
Get all permissions of a member on a guild
Just as easy, woah!
Now get to coding!
ADDENDUM: Permission Names
Click here for the full list of internal permission names, used for .has(name) in the above examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/* |
NOTE: This gist is no longer supported and won't get updated. |
Please refer to https://github.com/JakyeRU/discord.js-examples for the latest version. |
If you have any issues/suggestions you can open an issue/pull request there. |
*/ |
client . on ( "message" , async message => |
// Checking if the message author is a bot. |
if ( message . author . bot ) return false ; |
// Getting the role by ID. |
const Role1 = message . guild . roles . cache . get ( "RoleID" ) ; |
// Creating a filter. |
const Filter = ( reaction , user ) => user . id == message . author . id ; |
// Creating the embed message. |
const Embed = new discord . MessageEmbed ( ) |
. setDescription ( `Choose a role: $ < Role1 . name >` ) |
// Awaiting for the embed message to be sent. |
const reactionMessage = await message . channel . send ( Embed ) ; |
// Reacting to the embed message. |
await reactionMessage . react ( "😎" ) ; |
// Awaiting a reaction to the embed message. Time is measured in ms. (30000 ms - 30 seconds) |
reactionMessage . awaitReactions ( Filter , < max : 1 , time : 30000 , errors : [ "time" ] >) . then ( collected => |
// Getting the first reaction in the collection. |
const reaction = collected . first ( ) ; |
// Creating a switch statement for reaction.emoji.name. |
switch ( reaction . emoji . name ) |
case "😎" : |
// Checking if the member already has the role. |
if ( message . member . roles . cache . has ( Role1 . id ) ) < return message . channel . send ( "You already have the role." ) >; |
// Adding the role. |
message . member . roles . add ( Role1 ) . then ( message . channel . send ( "Role added!" ) ) ; |
// Breaking the switch statement to make sure no other cases are executed. |
break |
> |
> ) |
> ) ; |
plant-to-flower commented Dec 17, 2020
You have to change the role1 ("RoleId")
Проверка предопределенной роли и выполнение команды
Существует состояние, в котором объект может быть действительным, но неопределенным:
действительное, но неуказанное состояние [§ 17.3]
состояние объекта, которое не указано, за исключением того, что инварианты объекта выполняются, и операции над объектом ведут себя так, как указано для его типа
[ Пример: Если объект x типа std :: vector находится в действительном, но неуказанном состоянии , x.empty () можно назвать безоговорочно, а x.front () можно вызвать только в том случае, если x.empty () возвращает false. -end example ]
При чтении стандарта C ++ состояние data() не указывается, когда вектор пуст. Итак, состояние действительное, но неуказанное состояние . Поэтому возвращаемое значение data() , когда вектор пуст, может быть любым (нулевое или случайное значение). Это зависит от реализации компилятора.
В этом случае, следуя примеру в § 17.3, вы должны вызвать empty() перед использованием data() , чтобы убедиться, что возвращаемое значение является вашим ожиданием.
A1an-org commented Dec 10, 2020
It does. You just don't know how to set it up.
Alright, Why ichigo >:c
raunakrajadh commented Dec 1, 2020
Thanks Man, It works, I started with Reaction Role from this code, got the basic idea of making a reaction role from your code!
Nigelrex commented Dec 24, 2020
All This is fine But i wanted it to happen in a specific channel and how do i do that?
JakyeRU commented Dec 10, 2020
hi jakye i want to ask question that can i make in another file or not because i want in another file we need client.on("message", async message => // Checking if the message author is a bot.
if (message.author.bot) return false
code also when we do in another file ??
Discord.js check roles
Scenario: I have two discord servers, one old with 3k+ people, the other new: only selected people can join, my bot is on both. I have been handing out invites through PM, but I want to make the invite link public But only certain people can join new server, only the people that have "OG" role, if they don’t have that role in server 1, they will get kicked/banned from server two whenever they try to join
so far I have this:
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
t1mofe1 commented Dec 1, 2020
It works partially, like when I run the command and I react, I get the role, others dont, but if they run it, they do, I dont, how do I fix that so that only me can run the command and everyone gets the role
the filter is checking is the message author id and reaction user id same. (const Filter = (reaction, user) => user.id == message.author.id)
1 Answer 1
As long as you have the Guild object of the server you want to check the role of in your client’s list of Guilds, this isn’t too difficult to do. All you need to do is figure out the id string of the Guild you want to check permissions in. Then, you need to get the user’s GuildMember from the other Guild and check its roles. If they aren’t in the other Guild or they don’t have the role, kick/ban them.
Related
Hot Network Questions
JakyeRU commented Dec 24, 2020
All This is fine But i wanted it to happen in a specific channel and how do i do that?
Я пробовал иметь разрешения для конкретных ролей, но это означает, что на всех серверах, на которых находится бот, должна быть роль с одним и тем же именем.
Итак, вы изучили основы JavaScript и хотите перейти к изучению структур данных. Мотивация для изучения/понимания Структур данных может быть разной.
Прошлая статья была первой из цикла статей о создании системы электронной коммерции с использованием Keystone.js, и она была посвящена главным образом.
Обучение на практике - это проверенная тема для достижения успеха в любой области. Если вы знаете контекст фразы "Практика делает человека.
В 2022 году мы все слышим о трендах фронтенда (React, Vue), но мы не знаем, почему мы должны использовать эти фреймворки, когда их использовать, а.
Сегодня я собираюсь вкратце рассказать о прототипах в JavaScript, а также представить и объяснить вам работу с базой данных MongoDB.
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Roles and Permissions
Roles are a powerful feature in Discord, and admittedly have been one of the hardest parts to master in discord.js. This walk through aims at explaining how roles and permissions work. We'll also explore how to use roles to protect your commands.
Let's start with a basic overview of the hierarchy of roles in Discord.
. or actually not, they already explain it better than I care to: Role Management 101. Read up on that, then come back here. I'll wait. (Yeah I know that's cheesy, so sue me).
Let's get down to brass tacks. You want to know how to use roles and permissions in your bot.
Get Role by Name or ID
This is the "easy" part once you actually get used to it. It's just like getting any other Collection element, but here's a reminder anyway!
To get the ID of a role, you can either mention it with a \ before it, like \@rolename , or copy it from the role menu. If you mention it, the ID is the numbers between the <> . To get the ID of a role without mentioning it, enable developer mode in the Appearance section of your user settings, then go to the role menu in the server settings and right click on the role you want the ID of, then click "Copy ID".
Check if a member has a role
In a messageCreate handler, you have access to checking the GuildMember class of the message author:
To grab members and users in different ways see the FAQ Page.
Get all members that have a role
Add a member to a role
Alright, now that you have roles, you probably want to add a member to a role. Simple enough! Discord.js provides 2 handy methods to add, and remove, a role. Let's look at them!
Alright I feel like I have to add a little precision here on implementation:
- You can not add or remove a role that is higher than the bot's. This should be obvious.
- The bot requires MANAGE_ROLES permissions for this. You can check for it using the code further down this page.
- Because of global rate limits, you cannot do 2 role "actions" immediately one after the other. The first action will work, the second will not. You can go around that by using .roles.set([array, of, roles]) . This will overwrite all existing roles and only apply the ones in the array so be careful with it.
Check specific permission of a member on a channel
To check for a single permission override on a channel:
We pass false for the checkAdmin parameter because Administrator channel overwrites don't implicitly grant any permissions, unlike in Roles or when you are the Guild Owner. (The API will allow you to create an overwrite with Administrator, and even tell D.JS that a channel overwrite has had Administrator permissions set. Discord developers have stated this is intended behavior.)
Get all permissions of a member on a guild
Just as easy, woah!
Now get to coding!
ADDENDUM: Permission Names
Click here for the full list of internal permission names, used for .has(name) in the above examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/* |
NOTE: This gist is no longer supported and won't get updated. |
Please refer to https://github.com/JakyeRU/discord.js-examples for the latest version. |
If you have any issues/suggestions you can open an issue/pull request there. |
*/ |
client . on ( "message" , async message => |
// Checking if the message author is a bot. |
if ( message . author . bot ) return false ; |
// Getting the role by ID. |
const Role1 = message . guild . roles . cache . get ( "RoleID" ) ; |
// Creating a filter. |
const Filter = ( reaction , user ) => user . id == message . author . id ; |
// Creating the embed message. |
const Embed = new discord . MessageEmbed ( ) |
. setDescription ( `Choose a role: $ < Role1 . name >` ) |
// Awaiting for the embed message to be sent. |
const reactionMessage = await message . channel . send ( Embed ) ; |
// Reacting to the embed message. |
await reactionMessage . react ( "😎" ) ; |
// Awaiting a reaction to the embed message. Time is measured in ms. (30000 ms - 30 seconds) |
reactionMessage . awaitReactions ( Filter , < max : 1 , time : 30000 , errors : [ "time" ] >) . then ( collected => |
// Getting the first reaction in the collection. |
const reaction = collected . first ( ) ; |
// Creating a switch statement for reaction.emoji.name. |
switch ( reaction . emoji . name ) |
case "😎" : |
// Checking if the member already has the role. |
if ( message . member . roles . cache . has ( Role1 . id ) ) < return message . channel . send ( "You already have the role." ) >; |
// Adding the role. |
message . member . roles . add ( Role1 ) . then ( message . channel . send ( "Role added!" ) ) ; |
// Breaking the switch statement to make sure no other cases are executed. |
break |
> |
> ) |
> ) ; |
Читайте также: