You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.js中实现存储权限、解锁时恢复的lockdown命令?

Fixing Discord Lockdown/Unlock Permission Overwrites

Got it, let's sort out this permission issue once and for all. The core problem with your current setup is that you're overwriting permissions without saving the original state—so when you unlock, you have no way to revert back to what was there before. Here's a straightforward approach to implement the behavior you want:

Core Logic

  1. On !lockdown:
    • Iterate through every text channel in the guild
    • For your target role (e.g., @everyone or a specific member role), save the current SEND_MESSAGES permission state for each channel
    • Apply the lockdown (set SEND_MESSAGES to false for that role)
  2. On !unlock:
    • Retrieve the saved permission states
    • Reapply each original SEND_MESSAGES permission to its respective channel
    • Clear the saved cache to avoid conflicts with future lockdowns

Example Implementation (Discord.js v14)

First, we'll use a Map to cache permissions in memory (note: this resets if your bot restarts—we'll cover persistence later):

// At the top of your bot file, outside command handlers
const channelPermissionsCache = new Map();

// !lockdown command handler
client.on('messageCreate', async (message) => {
  if (!message.content.startsWith('!lockdown') || !message.member.permissions.has('Administrator')) return;

  const targetRole = message.guild.roles.everyone; // Replace with your specific role if needed
  channelPermissionsCache.clear(); // Clear old cache just in case

  // Iterate all text channels
  for (const channel of message.guild.channels.cache.filter(c => c.type === 0)) { // Type 0 = TextChannel
    try {
      // Get current permission overwrite for the target role
      const overwrite = channel.permissionOverwrites.cache.get(targetRole.id);
      // Save the original SEND_MESSAGES state (default to true if no overwrite exists)
      const originalSendPermission = overwrite ? overwrite.sendMessages : true;
      channelPermissionsCache.set(channel.id, originalSendPermission);

      // Apply lockdown
      await channel.permissionOverwrites.edit(targetRole.id, {
        SendMessages: false
      });
    } catch (err) {
      console.error(`Failed to lock channel ${channel.name}:`, err);
      message.channel.send(`Oops, couldn't lock ${channel.name}.`);
    }
  }

  message.channel.send('🔒 Server locked down successfully!');
});

// !unlock command handler
client.on('messageCreate', async (message) => {
  if (!message.content.startsWith('!unlock') || !message.member.permissions.has('Administrator')) return;

  if (channelPermissionsCache.size === 0) {
    return message.channel.send('No active lockdown to unlock!');
  }

  const targetRole = message.guild.roles.everyone; // Match the role used in lockdown

  // Iterate cached permissions and revert
  for (const [channelId, originalPermission] of channelPermissionsCache) {
    const channel = message.guild.channels.cache.get(channelId);
    if (!channel) continue; // Skip if channel was deleted

    try {
      await channel.permissionOverwrites.edit(targetRole.id, {
        SendMessages: originalPermission
      });
    } catch (err) {
      console.error(`Failed to unlock channel ${channel.name}:`, err);
      message.channel.send(`Oops, couldn't unlock ${channel.name}.`);
    }
  }

  channelPermissionsCache.clear();
  message.channel.send('🔓 Server unlocked successfully! Original permissions restored.');
});

Key Notes & Improvements

  • Persistence: The in-memory Map works for testing, but if your bot restarts during a lockdown, you'll lose the cached permissions. For production, use a database (like SQLite, MongoDB, or even a JSON file) to save the cache to disk.
  • Target Role Flexibility: Replace message.guild.roles.everyone with a specific role ID if you only want to lock down a particular group instead of all members.
  • Channel Types: The example filters for text channels (type 0), but you can adjust this to include news channels (type 5) or threads if needed.
  • Error Handling: The try/catch blocks prevent a single failed channel from breaking the entire lockdown/unlock process.

Let me know if you need help adapting this to your bot's framework (like discord.py, JDA, etc.) or setting up persistent storage!

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:07:51