如何在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令牌")
关键说明
- 客户端与命令树绑定:将
CommandTree作为自定义客户端的属性,彻底避免全局变量带来的上下文混乱 - Cog的正确继承:所有功能模块必须继承
discord.Cog,通过构造函数接收客户端实例,从而关联到对应的命令树 - 命令装饰器使用:用
@app_commands.command()替代全局tree.command,确保命令属于当前Cog的上下文 - 自动注册命令:通过
walk_app_commands()遍历Cog内所有命令并自动注册,无需手动逐个添加
内容的提问来源于stack exchange,提问作者godofclash
相关产品推荐
相关产品推荐

