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

如何在Discord.py的Cog中使用discord.app_commands实现斜杠命令?

在Discord.py Cog中实现斜杠命令的正确方式

原代码的核心问题

  • 全局CommandTree实例与自定义客户端类耦合混乱,应将命令树绑定到客户端实例内部
  • Cog类错误继承CommandTree,正确继承对象是discord.Cog
  • 使用全局tree.command装饰器无法关联Cog所属的客户端实例
  • 命令方法用self作为名称,属于Python关键字,会引发语法错误

修正后的完整代码

import discord
from discord import app_commands

# 自定义客户端类,内置CommandTree实例
class MyClient(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.all())
        self.tree = app_commands.CommandTree(self)  # 将命令树绑定到客户端
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            # 同步指定服务器的命令,全局同步可移除guild参数
            await self.tree.sync(guild=discord.Object(id=1007367355208319126))
            self.synced = True
            print(f"已登录为 {self.user},斜杠命令已同步")

# 定义斜杠命令Cog,必须继承discord.Cog
class SlashCommandsCog(discord.Cog):
    def __init__(self, client: MyClient):
        self.client = client
        # 自动注册Cog内的所有斜杠命令
        for command in self.walk_app_commands():
            self.client.tree.add_command(command)

    # 用app_commands.command装饰器定义斜杠命令
    @app_commands.command(name="ping", description="返回Pong响应")
    async def ping(self, interaction: discord.Interaction, name: str = "Pong"):
        await interaction.response.send_message(f"Pong {name}!")

# 注册Cog的标准函数
async def setup(client: MyClient):
    await client.add_cog(SlashCommandsCog(client))

# 启动客户端
if __name__ == "__main__":
    client = MyClient()
    client.run("你的Bot令牌")

关键说明

  1. 客户端与命令树绑定:将CommandTree作为自定义客户端的属性,彻底避免全局变量带来的上下文混乱
  2. Cog的正确继承:所有功能模块必须继承discord.Cog,通过构造函数接收客户端实例,从而关联到对应的命令树
  3. 命令装饰器使用:用@app_commands.command()替代全局tree.command,确保命令属于当前Cog的上下文
  4. 自动注册命令:通过walk_app_commands()遍历Cog内所有命令并自动注册,无需手动逐个添加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:39:23