如何检查我的机器人是否可以在discord.js v12中添加角色?

时间:2020-10-29 10:24:45

标签: node.js discord.js

我已经发出了一个警告命令,给提到的用户一个警告角色,但是我遇到了一个问题。有时服务器所有者可能会忘记将僵尸程序的角色移到警告角色之上,这将导致僵尸程序无法将角色赋予用户。我尝试使用role.editable,但是即使该角色低于漫游器的角色,它也会返回false。警告用户的角色也比漫游器低。这是我的代码:

const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
const fs = require("fs");
const ms = require("ms")
//let warnedRoleList = JSON.parse(fs.readFileSync("./roleIDs/warnedRole.json", "utf-8"));
var mongoPath = '../../mongo.js' //path.join(__dirname, '..', 'mongo.js');
const mongo = require(mongoPath)
const setWarnedSchema = require('../../schemas/setwarned-schema.js')
const mongoose = require('mongoose');
const cache = {}
const setup = require('../../util/setup')
const moderation = require('../../util/moderation')
const index = require('../../index.js')
//const commands = require("./commands");

module.exports = {
    commands: ['warn'],
    expectedArgs: ['{user ping/user ID} [reason]'],
    permissionError: ['you are missing the manage messages permissions'],
    minArgs: 1,
    maxArgs: null,
    permissions: ['MANAGE_MESSAGES'],
    requiredRoles: [],
    description: "The bot will warn the mentioned user",
    callback: async (message, args, text) => {
        const guild = message.guild
        let guildID = message.guild.id;
        var warnedRoleID = null
        warnedRoleID = await setup.getWarnedRoles(guildID)

        warnedRoleID = warnedRoleID.toString()
        var UserID = args[0]
        var member = index.getMention(args[0], message)

        var warnReason = args
        warnReason.shift()
        warnReason = warnReason.toString()
        warnReason = warnReason.replace(/,/g, ' ')
        if(!member) {
            return message.reply('please specify the user that should be warned')
        };

        if (!warnReason) {
            warnReason = 'no reason given'
        };
        var warnedRole = message.guild.roles.cache.get(warnedRoleID);
        var warnedOneHighestRoleID = member.roles.highest.id;
        var warningOneHighestRoleID = message.member.roles.highest.id;

        if(!warnedRole) {
            return message.reply('there is not a role set as the warned role, set it by doing &setwarnedrole (that requires manage server permissions)')
        };

        //let warnReason = args.join(" ").slice(18);
        if(member.id === message.author.id) {
            return message.reply('can not allow self-harm')
        }
        if (message.member.roles.highest.comparePositionTo(member.roles.highest) <= 0) { //warnedOneHighestRoleID === warningOneHighestRoleID
            return message.reply('you can not warn a user with the same (or higher) permissions as you')
        }
        if(!message.member.permissions.has('MANAGE_MESSAGES')){
            return message.reply(`you don't have manage messages permissions that are required to execute this command.`);
        }

        if (member.roles.cache.has(`${warnedRoleID}`)) {
            const logEmbed = new Discord.MessageEmbed()
            .setColor('#FF0000')
            .setTitle(`An attempt to warn an already warned member happened`)
            //.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
            .setDescription(`**Warned member:** <@${member.user.id}>\n**Warned by:** <@${message.author.id}>\n**Warn reason:** ${warnReason}`)
            .setTimestamp()
    
            index.modLog(guildID, logEmbed)
            message.reply('this user is already warned!')
            return
        };
        console.log(warnedRole.editable)
        if(!warnedRole.editable) {
            message.reply(`failed to warn <@${member.id}> as the warned role is above my highest role. Try moving at least one of my roles above other ones`)
            return
        };
        member.roles.add(warnedRoleID)
        .then(memberAdded => {
         message.reply(`you have succesfully warned <@${member.id}> with the reason **${warnReason}**`);
        })
        .catch(error => {
        //console.log(error);
            if(message.member.permissions.has('ADMINISTRATOR')){
                message.reply('there is no role set as the warned role. Set it by doing `&setwarnedrole add {role ID}`')
            } else message.reply('there is no role set as the warned role. Ask an admin to set it by doing `&setwarnedrole add {role ID}`')
        });
        const embed = new Discord.MessageEmbed()

        .setColor('#FF0000')
        .setTitle(`You hev been warned in ${message.guild.name}`)
        //.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
        .setDescription(`**Warned by:** <@${message.author.id}>\n**Warn reason:** ${warnReason}`)
        .setTimestamp()

        member.user.send(embed).catch(error => {
            message.channel.send(`Failed to DM <@${member.id}> the info about this action`)
            console.log(error)
        })

        const logEmbed = new Discord.MessageEmbed()
        .setColor('#FF0000')
        .setTitle(`A member has been warned`)
        //.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
        .setDescription(`**Warned member:** <@${member.user.id}>\n**Warned by:** <@${message.author.id}>\n**Warn reason:** ${warnReason}`)
        .setTimestamp()

        index.modLog(guildID, logEmbed)
    }
}

是否可以检查机器人是否可以将角色添加到用户?预先感谢。

1 个答案:

答案 0 :(得分:1)

角色hiearchy并不是确定角色是否可编辑的唯一因素。例如,如果您的漫游器没有MANAGE_ROLES权限,那么无论您的漫游器的最高角色有多高,Role#editable仍将返回false。

您要做的是首先检查GuildMember是否可管理(通过GuildMember#manageable)。如果不是,您就无法期望能够向其中添加角色。 然后,您要检查您的漫游器是否具有MANAGE_ROLES权限。 最后,您要检查所述“警告角色”的位置是否高于机器人最高角色的位置。

最后2个步骤应由Role#editable内部完成(请参见https://github.com/discordjs/discord.js/blob/master/src/structures/Role.js#L128

所以你可以做的是

if(!member.manageable || !warnedRole.editable) return console.log("Nope, cannot add role to that member)