Discord.py 2.0.0报错:ClientException,客户端已关联命令树
问题解决:Discord.py斜杠命令报错"This client already has an associated command tree"
错误原因
你手动创建app_commands.CommandTree(bot)属于重复操作——Discord.py 2.0及以上版本中,Bot类实例已经自带了一个内置的命令树对象bot.tree,重复创建会触发该异常。
修正后的代码
删除手动创建命令树的行,所有用到tree的地方替换为bot.tree即可:
import discord from discord import app_commands from discord.ext.commands import Bot bot = Bot(command_prefix='!', intents=discord.Intents.all()) @bot.event async def on_ready(): print(f'Bot Name: {bot.user}') # 全局同步命令树(所有服务器生效,可能需数分钟) await bot.tree.sync() # 若仅需同步已加入服务器的命令,可保留以下循环(生效更快) # for server in bot.guilds: # await bot.tree.sync(guild=discord.Object(id=server.id)) @bot.tree.command(name="test", description="Test to see if slash commands are working") async def test(interaction): await interaction.response.send_message("Test") bot.run('My Token')
补充说明
- 若为测试场景,指定
guild参数同步命令会比全局同步更快生效; - 确保你的机器人在Discord开发者平台已开启
applications.commands权限。
内容的提问来源于stack exchange,提问作者turrnut
相关产品推荐
相关产品推荐

