Как удалить все роли и добавить одну роль на дискорд-бота, а затем удалить добавленную роль и восстановить предыдущие роли - PullRequest
0 голосов
/ 01 апреля 2020

У меня есть строка кода для несогласного бота, чтобы удалить определенную c именованную роль и добавить роль с именем "muted" на указанное c количество времени. По сути, сервер может иметь только 3 роли, одна из которых может выдавать команду, «нормальный» ранг с обычными разрешениями и затем «приглушенная» роль. и мой код специально удалил обычную роль и добавляет отключенную роль, чтобы у них не было никаких разрешений.

Ну, я добавил своего бота на другой сервер с более чем 3 ролями, я решил дать всем нормальную роль, а также сделать отключенную роль. когда я запускаю команду, она работает, но, поскольку у людей есть другие роли, она позволяет затем продолжать говорить, даже если приглушенная роль имеет главный приоритет.

У меня есть вопрос, есть ли какой-то код, в котором я можно просто удалить все свои роли и добавить приглушенную роль. и когда отключенный период закончится, отключенная роль будет удалена, а их предыдущие роли восстановлены? вот мой код ниже:

 case 'mute':

    if(!message.member.roles.cache.find(r => r.name === "Admin")) return message.channel.send('You dont have permissions to do that you clown')

    let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
    if(!person) return message.reply("User Doesn't Exist");

    let mainrole = message.guild.roles.cache.find(role => role.name == "normal");
    let muterole = message.guild.roles.cache.find(role => role.name == "muted");

    if(!muterole) return message.reply("Role Doesn't Exist");

    let time = args[2];

    if(!time){
        return message.reply("How Long?");
    }

    person.roles.remove(mainrole.id);
    person.roles.add(muterole.id);

    message.channel.send(`@${person.user.tag} has now been muted for ${ms(ms(time))}`);

    setTimeout(function(){
        person.roles.add(mainrole.id);
        person.roles.remove(muterole.id);
        message.channel.send(`@${person.user.tag} has now been unmuted`)
    }, ms(time));
        break;
    case 'help':
        const embed2 = new MessageEmbed()
        .setTitle("How To Get Commands")
        .setColor(0x00fff7)
        .setDescription("Do /commands to get the list of commands");

        message.author.send(embed2);
        break;

Ответы [ 2 ]

1 голос
/ 02 апреля 2020

Самый простой способ сделать это - получить список ролей от пользователя, очистить их роли и затем подать заявку на отключенную роль. Затем вы захотите кэшировать их предыдущие роли или даже сохранить данные в базе данных на случай, если бот выйдет из строя, и после перезапуска вы можете получить данные и продолжить с того места, на котором остановились.

Вот быстрый Пример я написал на лету. Вы, вероятно, хотите кэшировать роли немного иначе, чем я, так как мой метод был просто для быстрой демонстрации, и я настоятельно рекомендую сохранить данные в базу данных или даже что-то вроде. json файла.

let cachedUserRoles = {};

function addMutedRole(guildId, userId, roleId) {
    //Get the guild the user is apart of
    let guild = client.guilds.get(guildId);
    //Specify the user from the guild
    let guildMember = guild.members.get(userId);

    //Cache the users existing roles so we can restore them later
    cachedUserRoles[userId] = guildMember.roles.cache
    //Remove all roles from user
    guildMember.roles.set([])
        //Add the muted role after all roles have been removed with an array of the single role ID
        .then(member => member.roles.add([roleId]))
        //Catch and report any errors that might happen
        .catch(console.error)
}

function restoreRoles(guildId, userId) {
    //Get the guild the user is apart of
    let guild = client.guilds.get(guildId);
    //Specify the user from the guild
    let guildMember = guild.members.get(userId);
    //Get and set the user's previouse roles from cachedUserRoles and error log if anything goes wrong
    guildMember.roles.set(cachedUserRoles[userId]).catch(console.error)
}

В вашем случае это будет выглядеть примерно так:

case 'mute':
        if(!message.member.roles.cache.find(r => r.name === "Admin")) return message.channel.send('You dont have permissions to do that you clown')

        let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
        if(!person) return message.reply("User Doesn't Exist");

        let muterole = message.guild.roles.cache.find(role => role.name == "muted");

        if(!muterole) return message.reply("Role Doesn't Exist");

        let time = args[2];

        if(!time){
            return message.reply("How Long?");
        }

        //Cache their already existing roles
        cachedUserRoles[person.id] = person.roles.cache;
        //Set their roles to an empty array to clear them, then add the muted role once all roles were removed successfully
        person.roles.set([]).then(member => member.roles.add(muterole)).catch(console.error);

        message.channel.send(`@${person.user.tag} has now been muted for ${ms(ms(time))}`);

        setTimeout(function(){
            //Grab their existing roles and set them back to the user, we wont need to remove the muted role since setting the roles would override all existing ones already
            person.roles.set(cachedUserRoles[person.id]).catch(console.error)
            message.channel.send(`@${person.user.tag} has now been unmuted`)
        }, ms(time));
        break;
    case 'help':
        const embed2 = new MessageEmbed()
            .setTitle("How To Get Commands")
            .setColor(0x00fff7)
            .setDescription("Do /commands to get the list of commands");

        message.author.send(embed2);
        break;
0 голосов
/ 01 апреля 2020

Я не уверен, есть ли более эффективный способ сделать это, но вы можете попробовать следующее:

L oop через все их роли и сохранить их в файл или даже базу данных и один раз время истекает, удалите приглушенную роль и l oop просмотрите список сохраненных ролей, чтобы добавить их обратно.

...