如何在 discord.py 2.x 中正确创建和同步 Slash 命令

酷浩姑娘_3767

酷浩姑娘_3767

2026-07-04

873人浏览

原创

如何在 discord.py 2.x 中正确创建和同步 Slash 命令

本文详解 discord.py 2.3+ 中 Slash 命令的正确实现方式,包括 CommandTree 的使用、命令注册、同步机制及常见错误规避,帮助开发者告别 ImportError: cannot import 'SlashCommand'。

本文详解 discord.py 2.3+ 中 slash 命令的正确实现方式,包括 commandtree 的使用、命令注册、同步机制及常见错误规避,帮助开发者告别 `importerror: cannot import 'slashcommand'`。

Discord.py 自 2.0 版本起彻底重构了应用命令(即 Slash 命令)的支持机制:不再提供 SlashCommand 类,也不支持手动实例化命令对象。你遇到的 Import Error: cannot import 'SlashCommand' from 'discord.app_commands' 正是因为该类根本不存在于当前版本的 discord.py 中——它属于过时的第三方库或早期非官方实现,与官方 discord.py 2.x 的设计范式完全不符。

✅ 正确做法是使用内置的 app_commands.CommandTree(通常通过 Bot.tree 访问),配合装饰器 @tree.command() 或 @bot.tree.command() 注册命令。以下是重构后的完整、可运行的 /mute 示例:

Debuild
Debuild

Debuild是一款AI开发辅助工具,低代码快速开发网页应用。

下载
import discord
from discord.ext import commands
from discord import app_commands

# 推荐使用 commands.Bot 而非 raw Client —— 它内置 CommandTree 并简化事件管理
intents = discord.Intents.default()
intents.message_content = True
intents.members = True  # 需要获取 member.top_role 和检查权限

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

# ✅ 正确注册 Slash 命令:使用 bot.tree.command()
@bot.tree.command(name="mute", description="Mutes a member for a specific reason.")
@app_commands.describe(
    member="The member to mute",
    reason="Optional reason for muting"
)
async def mute(interaction: discord.Interaction, member: discord.Member, reason: str = None):
    # 权限检查:执行者需有管理角色权限
    if not interaction.user.guild_permissions.manage_roles:
        await interaction.response.send_message("❌ You lack `Manage Roles` permission.", ephemeral=True)
        return

    # 权限检查:Bot 自身需能管理目标成员(角色层级)
    if member.top_role >= interaction.guild.me.top_role:
        await interaction.response.send_message("❌ I cannot mute users with equal or higher roles.", ephemeral=True)
        return

    # 查找或创建 "Muted" 角色
    muted_role = discord.utils.get(interaction.guild.roles, name="Muted")
    if not muted_role:
        try:
            muted_role = await interaction.guild.create_role(
                name="Muted",
                permissions=discord.Permissions(send_messages=False, speak=False),
                reason="Auto-created for mute functionality"
            )
            # 将角色置于底部(确保不影响其他权限),或手动调整位置
            await muted_role.edit(position=1)
        except discord.Forbidden:
            await interaction.response.send_message("❌ Failed to create `Muted` role. Check my role position and permissions.", ephemeral=True)
            return

    # 执行静音:添加角色
    try:
        await member.add_roles(muted_role, reason=reason or "No reason provided")
        await interaction.response.send_message(f"✅ {member.mention} has been muted.", ephemeral=False)

        # 可选:私信通知被静音用户
        if reason:
            try:
                await member.send(f"You were muted in **{interaction.guild.name}** for: {reason}")
            except discord.Forbidden:
                pass  # 用户关闭了私信
    except discord.Forbidden:
        await interaction.response.send_message("❌ Failed to assign `Muted` role. Please check my role hierarchy and permissions.", ephemeral=True)

# ✅ 同步命令:避免在 on_ready 中直接调用 sync()(易因网关未就绪失败)
@bot.command()
@commands.is_owner()
async def sync(ctx: commands.Context):
    try:
        synced = await bot.tree.sync()
        await ctx.send(f"✅ Synced {len(synced)} application command(s).")
    except Exception as e:
        await ctx.send(f"❌ Sync failed: {e}")

# ❌ 不推荐:on_ready 中 sync(可能触发 400 Bad Request 或超时)
# @bot.event
# async def on_ready():
#     await bot.tree.sync()  # ⚠️ 不稳定,尤其在多服务器环境下
#     print(f'Logged in as {bot.user}')

bot.run("YOUR_BOT_TOKEN")  # 替换为你的 token

? 关键注意事项:

  • 不要使用 Client + 手动 SlashCommand 实例:discord.Client 不自带 tree 属性,且 SlashCommand 类从未存在于官方 discord.py 中。
  • 务必使用 commands.Bot:它自动初始化 CommandTree,并提供更完善的命令生命周期管理。
  • 同步不是一次性操作:每次修改命令(如改名、加参数、删命令)后都需重新 sync();生产环境建议搭配 /sync 管理命令。
  • 权限与角色层级:member.top_role >= interaction.guild.me.top_role 是判断 Bot 是否有权操作的关键逻辑,不可省略。
  • ephemeral=True:对敏感操作(如权限检查失败)使用临时响应,避免暴露给全体成员。
  • 错误处理必须显式:网络请求、角色创建、DM 发送均可能失败,应 try/except 捕获 discord.Forbidden、discord.HTTPException 等。

? 最后提醒:官方文档始终是权威来源——请优先查阅 discord.py App Commands 文档 及 examples/app_commands 中的实战示例。摒弃过时教程中“手动构建 SlashCommand”的思路,拥抱 CommandTree 这一现代、稳定、可扩展的设计模式。

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

2023.07.20

1591

4

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

2023.07.25

3804

7

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

2023.07.31

1589

3

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

2023.08.03

21937

23

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.08.04

2687

5

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.08.04

2747

5

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.11

1103

5

python合并两个列表
python合并两个列表

Python是一种强大的编程语言,具有许多方便的功能和工具。在Python中,有多种方法可以合并两个列表。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.08.10

596

4

python是前端还是后端
python是前端还是后端

Python属于前端也属于后端,其灵活性和丰富的生态系统使得开发人员能够在不同的领域中灵活运用。本专题为大家提供python相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.11

2123

5

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.6万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 133.2万人学习