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

discord.py如何实现触发create命令自动批量创建3个预设文本频道

前置要求
  • 你使用的是discord.py 2.x 版本
  • 已在Discord开发者后台给机器人开启 Manage Channels 权限
  • 已在开发者后台的「Privileged Gateway Intents」板块开启 Guilds Intent 权限
  • 机器人在对应服务器内拥有「管理频道」的身份组权限

斜杠命令实现(主流方案)
import discord
from discord import app_commands

# 预设要创建的3个文本频道名称,可自行修改
PRESET_CHANNEL_NAMES = ["公告栏", "交流区", "资源分享"]

# 初始化客户端
intents = discord.Intents.default()
intents.guilds = True # 必须开启服务器相关权限
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

# 定义create斜杠命令
@tree.command(name="create", description="批量创建预设文本频道")
@app_commands.checks.has_permissions(manage_channels=True) # 限制只有有管理频道权限的用户才能触发命令
async def create_preset_channels(interaction: discord.Interaction):
    # 先发延迟回复避免操作超时
    await interaction.response.defer(ephemeral=True)
    created_channels = []

    for channel_name in PRESET_CHANNEL_NAMES:
        # 在当前服务器创建文本频道
        new_channel = await interaction.guild.create_text_channel(
            name=channel_name,
            # 可额外配置频道参数
            # category=discord.Object(id=你的分类ID), # 放入指定分类
            # topic="频道自定义主题"
        )
        created_channels.append(new_channel.mention)

    # 发送成功提示
    await interaction.followup.send(f"✅ 批量创建频道成功,已创建的频道:{'、'.join(created_channels)}", ephemeral=True)

# 机器人启动事件
@client.event
async def on_ready():
    # 同步全局命令,首次同步最长1小时生效,测试可指定服务器ID加快同步:await tree.sync(guild=discord.Object(id=测试服务器ID))
    await tree.sync()
    print(f"机器人已登录:{client.user}")

# 填入你的机器人Token运行
client.run("你的机器人Token")

前缀命令实现(无需等待命令同步)

如果你习惯用前缀触发命令,可以使用以下版本,触发命令为!create,需要额外开启Message Content Intent权限:

import discord
from discord.ext import commands

PRESET_CHANNEL_NAMES = ["公告栏", "交流区", "资源分享"]

intents = discord.Intents.default()
intents.message_content = True # 前缀命令必须开启消息内容权限
intents.guilds = True

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

@bot.command(name="create")
@commands.has_permissions(manage_channels=True)
async def create_preset_channels(ctx: commands.Context):
    created_channels = []
    for channel_name in PRESET_CHANNEL_NAMES:
        new_channel = await ctx.guild.create_text_channel(name=channel_name)
        created_channels.append(new_channel.mention)
    await ctx.send(f"✅ 批量创建频道成功,已创建的频道:{'、'.join(created_channels)}")

@bot.event
async def on_ready():
    print(f"机器人已登录:{bot.user}")

bot.run("你的机器人Token")

代码调整说明
  • 可直接修改PRESET_CHANNEL_NAMES列表内的值自定义要创建的频道名称
  • 不需要限制触发用户权限的话,删掉对应权限校验的装饰器即可
  • 需要把频道放入指定分类的话,在create_text_channel方法内传入category参数和对应分类ID即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:45:03