简体   繁体   English

(discord.js) 如何使此命令仅适用于某些角色/用户?

[英](discord.js) How can I make this command only work for certain roles/users?

I'm still fairly inept when it comes to software development, and need some help with making this command work for only certain roles on my discord server, or only work for certain users在软件开发方面我仍然相当无能,并且需要一些帮助才能使此命令仅适用于我的 discord 服务器上的某些角色,或者仅适用于某些用户

client.on('message', async message => {
    if (message.content === '-fruits') {
        try {
            await message.react('🍎');
            await message.react('🍊');
            await message.react('🍇');
        } catch (error) {
            console.error('One of the emojis failed to react:', error);
        }
    }
});

You can restrict a command to specific users by creating an array of user IDs, and if the message authors ID is in the list check if it matches any commands.您可以通过创建用户 ID 数组将命令限制为特定用户,如果消息作者 ID 在列表中,请检查它是否与任何命令匹配。

// Create an array of user ids
const adminIDs = [/* List of user IDs */]

client.on('message', async message => {
    // Check if the user who sent the message is in the list 
    if (adminIDs.include(message.author.id)) {
        // If user is in list, then check if message matches a command
        if (message.content === 'foo') {
            // do stuff...
        } else if (message.content === 'bar') {
           // do more stuff..
        }
    }
});

As for roles, you can check if a user has a specific role.至于角色,您可以检查用户是否具有特定角色。

client.on('message', async message => {
    // Check if the user has a role with the name "Admin"
    if (message.member.roles.find(r => r.name === 'Admin')){
        if (message.content === 'foo') {
            // do stuff...
        } else if (message.content === 'bar') {
           // do more stuff..
        }
    }
});

Comment on @KyleRifqi's answer (I don't have 50 rep.)评论@KyleRifqi 的回答(我没有 50 个代表。)

Roles also have IDs , so you can do message.member.roles.find(r => r.id === "Role ID string") instead, if you happen to have multiple roles with the same name 角色也有 ID ,因此如果您碰巧有多个具有相同名称的角色,您可以改为message.member.roles.find(r => r.id === "Role ID string")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM