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

如何使用discord.py获取所有文本频道?实现只读bunker命令

Hey there! Let's tackle this problem step by step—first grabbing all text channels in a server, then building that "bunker" command to lock every one down to read-only. I'll be using discord.py v2.x (the latest stable release) since that's what most folks are working with now.

1. Fetching All Text Channels

To get all text channels in a guild (server), you can use the guild.text_channels attribute. This returns a list of TextChannel objects you can iterate over. For a command that runs in the context of the server it's used in, we'll just reference ctx.guild directly.

Here's a quick example to list all text channels (with admin checks to prevent misuse):

@bot.command()
async def list_channels(ctx):
    # Verify the user has admin access first
    if not ctx.author.guild_permissions.administrator:
        await ctx.send("You need admin permissions to use this command!")
        return
    
    text_channels = ctx.guild.text_channels
    if not text_channels:
        await ctx.send("This server has no text channels.")
        return
    
    # Format the channel list for readability
    channel_list = "\n".join([f"- {channel.name} (ID: {channel.id})" for channel in text_channels])
    await ctx.send(f"Text channels in this server:\n{channel_list}")
2. Building the "Bunker" Command

The bunker command will update the @everyone role's permissions in every text channel, setting send_messages to False (making channels read-only). We'll add safeguards to ensure only admins can run it, plus error handling for channels the bot can't modify.

Full working code:

import discord
from discord.ext import commands

# Enable required intents (don't forget to turn these on in the Discord Developer Portal!)
intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.command(name="bunker")
@commands.has_permissions(administrator=True)
async def activate_bunker(ctx):
    text_channels = ctx.guild.text_channels
    if not text_channels:
        await ctx.send("No text channels found to lock down!")
        return
    
    locked_count = 0
    failed_channels = []
    
    for channel in text_channels:
        try:
            # Get the server's default @everyone role
            everyone_role = ctx.guild.default_role
            # Update permissions to block message sending
            await channel.set_permissions(everyone_role, send_messages=False)
            locked_count += 1
        except discord.Forbidden:
            failed_channels.append(channel.name)
        except Exception as e:
            failed_channels.append(f"{channel.name} (Error: {str(e)})")
    
    # Send a summary of what happened
    response = f"✅ Locked down {locked_count} text channels!\n"
    if failed_channels:
        response += f"❌ Failed to lock: {', '.join(failed_channels)}"
    await ctx.send(response)

# Error handler for users missing admin permissions
@activate_bunker.error
async def bunker_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You need Administrator permissions to activate bunker mode!")

# Replace with your bot token
bot.run("YOUR_BOT_TOKEN_HERE")

Key Details to Remember:

  • Intents: Make sure you've enabled the message_content intent in your Discord Developer Portal—without it, the bot won't be able to read your commands.
  • Reversing the Lock: If you want an "unbunker" command, just change send_messages=False to send_messages=None (resets to server-level permissions) or send_messages=True.
  • Error Handling: The code catches cases where the bot doesn't have permission to modify a channel, so you'll get a clear report of any failures.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:47:56