【问题标题】:How can I choose a random role and give it to a user Discord.js如何选择随机角色并将其提供给用户 Discord.js
【发布时间】:2021-08-23 13:47:18
【问题描述】:

现在我的代码选择了一个带有Math.Random 的随机角色,并可以在控制台中显示它,但我不知道如何将该随机角色添加给用户。

const random = Math.floor(Math.random() * Choices.length);

console.log(Choices[random])

这是选择角色并在控制台中显示的代码,Choices 是可供选择的不同角色。

await reaction.message.guild.members.cache.get(user.id).roles.add();

如果我将常量 random 添加为要添加的角色,则不会将其检测为角色。 请帮忙,谢谢。

这是代码

        const GRole = message.guild.roles.cache.find(role => role.name === "Green");
        const BRole = message.guild.roles.cache.find(role => role.name === "Blue");
        const RRole = message.guild.roles.cache.find(role => role.name === "Red");
        const YRole = message.guild.roles.cache.find(role => role.name === "Yellow");

        const RandomEmoji = '????';

        const Choices = [
            "GRole",
            "BRole",
            "RRole",
            "YRole",
        ];


        const rereg = (args[0] === "reregister");

        if (!rereg) {

            let embed = new Discord.MessageEmbed()
                .setColor('#cf44c9')
                .setTitle('Random Role⠀⠀')

            let messageEmbed = await message.channel.send(embed);
            messageEmbed.react(RandomEmoji);

            client.on('messageReactionAdd', async (reaction, user) => {
                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.channel.id == channel) {
                    if (reaction.emoji.name === RandomEmoji) {
                        const random = Math.floor(Math.random() * Choices.length);
                        console.log(Choices[random])

                        await reaction.message.guild.members.cache.get(user.id).roles.add();
                    }
                } else {
                    return;
                }
            });

        }

【问题讨论】:

  • 我们可以看看你的“Choices”数组的结构吗?
  • 我添加了我的代码,请看一下。
  • 不需要指定要添加的角色吗?
  • 是的,但是如果我添加 random 随机选择的角色,它不会被识别为角色。
  • 嘿,数组由字符串而不是角色组成的事实呢?

标签: javascript node.js discord discord.js bots


【解决方案1】:

要为用户分配角色,您可以使用以下代码:

(假设常数“random”是来自“Choices”的随机索引。而“Choices”是一个角色数组)

var role = message.guild.roles.cache.find(role => role.name === Choices[random]);
message.member.addRole(role);

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 2019-03-10
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多