Discord.py机器人启动报错:This client already has an associated command tree求助
解决Discord机器人启动时的"This client already has an associated command tree"错误
问题原因
你手动实例化了discord.app_commands.CommandTree(client),但commands.Bot对象本身已经自带了一个命令树实例(存放在client.tree属性中),重复创建命令树就会触发这个错误。
解决方案
不需要手动创建新的CommandTree,直接使用Bot自带的命令树即可,步骤如下:
删除手动创建的CommandTree实例
移除代码中的commandTree = discord.app_commands.CommandTree(client)这一行。替换命令装饰器
将命令的装饰器从@commandTree.command改为@client.tree.command,直接绑定到Bot自带的命令树上。(建议)同步命令到Discord
在on_ready事件中添加await client.tree.sync(),确保你的命令能被Discord服务器识别,首次运行或修改命令后必须执行同步。
修改后的完整代码
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix="/", intents=intents) @client.event async def on_ready(): print(f'已登录为 {client.user}') # 同步命令到Discord,首次运行或修改命令后执行 await client.tree.sync() print("命令树已同步") @client.tree.command(name="upload", description="上传文件到服务器") async def upload(ctx, file: discord.File): if not file: await ctx.send("你没有上传任何文件。") else: await file.save(f"uploads/{file.filename}") await ctx.send(f"文件 '{file.filename}' 上传成功。")
补充说明
不需要手动删除旧命令树,当你修改命令并重新运行client.tree.sync()时,Discord会自动更新命令列表——移除已删除的旧命令,添加或更新新命令。
内容的提问来源于stack exchange,提问作者toaster
相关产品推荐
相关产品推荐

