
本文详解 discord.py 2.3+ 中 slash 命令的正确实现方式,包括 commandtree 的使用、@bot.tree.command 装饰器语法、命令同步机制及常见错误规避,帮助开发者快速构建合规、可部署的交互式命令系统。
本文详解 discord.py 2.3+ 中 slash 命令的正确实现方式,包括 commandtree 的使用、@bot.tree.command 装饰器语法、命令同步机制及常见错误规避,帮助开发者快速构建合规、可部署的交互式命令系统。
Discord.py 自 v2.0 起彻底重构了应用命令(即 Slash 命令)的支持机制:不再提供 SlashCommand 类,也不支持手动实例化命令对象。你遇到的 ImportError: cannot import 'SlashCommand' from 'discord.app_commands' 正是因为该类根本不存在于官方库中——它是对旧版第三方库(如 discord-py-slash-command)或过时教程的误用。
✅ 正确做法是使用内置的 app_commands.CommandTree,它负责注册、管理并同步所有应用命令。推荐搭配 commands.Bot(而非裸 discord.Client)使用,因其自动初始化 tree 属性,并提供更完善的事件与命令集成能力。
✅ 正确示例:实现 /mute Slash 命令
import discord
from discord.ext import commands
from discord import app_commands
import asyncio
# 使用 commands.Bot(推荐),自动集成 CommandTree
intents = discord.Intents.default()
intents.message_content = True
intents.members = True # 需要获取成员角色层级信息
bot = commands.Bot(command_prefix="!", intents=intents)
# 定义 Slash 命令(注意:装饰器为 @bot.tree.command,参数类型为 Interaction)
@bot.tree.command(name="mute", description="禁言指定成员")
@app_commands.describe(
member="要禁言的成员",
reason="禁言原因(可选)"
)
async def mute(interaction: discord.Interaction, member: discord.Member, reason: str = None):
# 权限检查(必须在 interaction.response.send_message 前完成)
if not interaction.user.guild_permissions.manage_roles:
await interaction.response.send_message("❌ 你没有管理身份组权限,无法执行此操作。", ephemeral=True)
return
if member.top_role >= interaction.guild.me.top_role:
await interaction.response.send_message("❌ 我无法禁言角色等级高于或等于我的成员。", ephemeral=True)
return
# 获取或创建 Muted 角色
muted_role = discord.utils.get(interaction.guild.roles, name="Muted")
if not muted_role:
muted_role = await interaction.guild.create_role(
name="Muted",
permissions=discord.Permissions(send_messages=False, send_messages_in_threads=False, speak=False),
reason="自动创建禁言角色"
)
# 可选:为所有文本/语音频道设置拒绝权限(需遍历频道)
for channel in interaction.guild.channels:
await channel.set_permissions(muted_role, send_messages=False, speak=False, send_messages_in_threads=False)
# 执行禁言
await member.add_roles(muted_role, reason=reason or "无原因")
await interaction.response.send_message(f"✅ {member.mention} 已被禁言。", ephemeral=False)
# 私信通知(仅当用户可接收 DM 时)
try:
dm_msg = f"你在服务器 `{interaction.guild.name}` 中已被禁言。"
if reason:
dm_msg += f"\n原因:{reason}"
await member.send(dm_msg)
except discord.Forbidden:
pass # 用户关闭了私信,忽略
# 同步命令到 Discord —— 关键步骤!必须显式调用且等待完成
@bot.command()
@commands.is_owner()
async def sync(ctx: commands.Context):
try:
synced = await ctx.bot.tree.sync()
await ctx.send(f"✅ 已同步 {len(synced)} 个应用命令。")
except Exception as e:
await ctx.send(f"❌ 同步失败:{e}")
# 推荐:在 bot 启动后延迟同步(避免 on_ready 中同步不稳定)
@bot.event
async def on_ready():
print(f"✅ {bot.user} 已上线,准备就绪!")
# 注意:不建议在 on_ready 中直接 await bot.tree.sync()(可能因网关未就绪失败)
# 更稳妥的方式是通过 sync 命令手动触发,或使用异步后台任务
bot.run("YOUR_BOT_TOKEN") # 替换为你的 Bot Token
⚠️ 关键注意事项
- 不要使用 Client + 手动 SlashCommand 实例:discord.Client 不自带 tree,且 SlashCommand 类从未存在于 discord.py 官方代码中。
- 同步不是自动的:应用命令需显式调用 await bot.tree.sync()(全局)或 await bot.tree.sync(guild=...)(特定服务器)才能在 Discord 端生效;首次部署或修改命令签名后务必重新同步。
- on_ready 中同步有风险:Discord 网关连接可能尚未完全稳定,易导致 400 Bad Request。生产环境应改用管理员指令(如 /sync)或带重试逻辑的后台任务。
- 权限与类型提示:Interaction 是应用命令的唯一上下文对象(非 Context),务必使用 discord.Member、discord.Role 等正确类型注解,以启用自动参数解析。
- 错误处理与用户体验:使用 ephemeral=True 发送仅发送者可见的响应;对 member.send() 添加 try/except discord.Forbidden 避免因隐私设置导致报错。
掌握 CommandTree 和 @bot.tree.command 是现代 discord.py 应用命令开发的核心。遵循官方范式,不仅能避免导入错误,更能确保命令稳定性、可维护性与 Discord 平台兼容性。











