You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何基于discord.js实现成员监禁(Jail)与解除监禁(Unjail)命令

Implementing Jail & Unjail Commands for Your Discord Bot

Got it, let's walk through building these commands step by step using Discord.js v14 (the latest stable release right now). I’ll keep things straightforward so you can drop this into your bot quickly.

Prerequisites

First, make sure you have these sorted before writing code:

  • Your bot needs the ManageRoles permission (or Administrator access, though least privilege is better).
  • Create two server roles:
    • A Jailed role: Configure its permissions to restrict the user (e.g., disable sending messages, viewing channels, reacting to messages).
    • A Member role: Your server’s default role for regular, non-jailed users.
  • Optional (but more reliable): Note down the role IDs (enable Discord Developer Mode, right-click the role, and copy ID) to use instead of role names.

Jail Command (Lock a User)

This command will strip the target of all their existing roles (except the mandatory @everyone role) and assign the Jailed role. Here’s a slash command implementation (the modern standard for Discord bots):

const { SlashCommandBuilder, PermissionsBitField } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('jail')
        .setDescription('Restrict a member by putting them in jail')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('The member to jail')
                .setRequired(true)),
    async execute(interaction) {
        // Check if the command user has permission to manage roles
        if (!interaction.member.permissions.has(PermissionsBitField.Flags.ManageRoles)) {
            return interaction.reply({ content: "You don't have permission to use this command!", ephemeral: true });
        }

        const targetUser = interaction.options.getUser('target');
        const targetMember = interaction.guild.members.cache.get(targetUser.id);
        const jailRole = interaction.guild.roles.cache.find(role => role.name === 'Jailed'); // Replace with role.id === 'YOUR_JAIL_ROLE_ID' for reliability
        const memberRole = interaction.guild.roles.cache.find(role => role.name === 'Member'); // Same here: use ID if preferred

        // Validate roles exist
        if (!jailRole) return interaction.reply({ content: "Jail role not found! Please create a role named 'Jailed' first.", ephemeral: true });
        if (!memberRole) return interaction.reply({ content: "Member role not found! Please create a role named 'Member' first.", ephemeral: true });

        // Prevent jailing bots or users with higher roles than the bot
        if (targetUser.bot) return interaction.reply({ content: "You can't jail bots!", ephemeral: true });
        if (targetMember.roles.highest.position >= interaction.guild.members.me.roles.highest.position) {
            return interaction.reply({ content: "I can't jail this member—their role is higher than mine!", ephemeral: true });
        }

        // Replace all user's roles with the Jailed role
        await targetMember.roles.set([jailRole.id]);

        await interaction.reply(`Successfully jailed ${targetUser.tag}! 🚔`);
    },
};

Unjail Command (Release a User)

This command removes the Jailed role and restores the user’s default Member role:

const { SlashCommandBuilder, PermissionsBitField } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('unjail')
        .setDescription('Release a member from jail')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('The member to unjail')
                .setRequired(true)),
    async execute(interaction) {
        if (!interaction.member.permissions.has(PermissionsBitField.Flags.ManageRoles)) {
            return interaction.reply({ content: "You don't have permission to use this command!", ephemeral: true });
        }

        const targetUser = interaction.options.getUser('target');
        const targetMember = interaction.guild.members.cache.get(targetUser.id);
        const jailRole = interaction.guild.roles.cache.find(role => role.name === 'Jailed');
        const memberRole = interaction.guild.roles.cache.find(role => role.name === 'Member');

        if (!jailRole) return interaction.reply({ content: "Jail role not found! Please create a role named 'Jailed' first.", ephemeral: true });
        if (!memberRole) return interaction.reply({ content: "Member role not found! Please create a role named 'Member' first.", ephemeral: true });

        // Check if the user is actually jailed
        if (!targetMember.roles.cache.has(jailRole.id)) {
            return interaction.reply({ content: "This member isn't in jail!", ephemeral: true });
        }

        // Remove jail role and add back the Member role
        await targetMember.roles.remove(jailRole.id);
        await targetMember.roles.add(memberRole.id);

        await interaction.reply(`Successfully released ${targetUser.tag} from jail! 🎉`);
    },
};

Bonus: Restore All Original Roles (Optional)

If you want to restore all of the user’s original roles (not just the Member role) when unjailing, you’ll need to store their roles before jailing. Here’s how to adjust the code:

Update the Jail Command to Save Roles

Add this code before setting the Jailed role to save roles to a JSON file (use a database for larger servers):

const fs = require('fs');
const jailedUsersPath = './jailedUsers.json';

// Load existing jailed users data
let jailedUsers = {};
if (fs.existsSync(jailedUsersPath)) {
    jailedUsers = JSON.parse(fs.readFileSync(jailedUsersPath, 'utf8'));
}

// Save the user's roles (exclude @everyone, which is mandatory)
const userOriginalRoles = targetMember.roles.cache
    .filter(role => role.id !== interaction.guild.id)
    .map(role => role.id);
jailedUsers[targetUser.id] = userOriginalRoles;

// Write back to the file
fs.writeFileSync(jailedUsersPath, JSON.stringify(jailedUsers));

Update the Unjail Command to Restore Roles

Replace the role restoration part with this:

const fs = require('fs');
const jailedUsersPath = './jailedUsers.json';

if (!fs.existsSync(jailedUsersPath)) {
    return interaction.reply({ content: "No jailed users found!", ephemeral: true });
}

const jailedUsers = JSON.parse(fs.readFileSync(jailedUsersPath, 'utf8'));
if (!jailedUsers[targetUser.id]) {
    return interaction.reply({ content: "This member wasn't jailed by me!", ephemeral: true });
}

// Restore all original roles
await targetMember.roles.set(jailedUsers[targetUser.id]);

// Remove the user from the jailed list
delete jailedUsers[targetUser.id];
fs.writeFileSync(jailedUsersPath, JSON.stringify(jailedUsers));

Key Notes

  • Role Position: Your bot’s highest role must be above both the Jailed and Member roles in the server’s role hierarchy—otherwise it can’t modify those roles for users.
  • Permissions: Double-check the Jailed role’s permissions to ensure restricted access (you can set this at the server level or per-channel).
  • Error Handling: The code includes basic checks, but you can expand it for edge cases (e.g., if the target user leaves the server mid-command).

内容的提问来源于stack exchange,提问作者AnArWi

火山引擎 最新活动