Discord.py斜杠命令无法使用求助:MissingApplicationID报错
Discord.py斜杠命令无法显示及MissingApplicationID错误解决方案
错误原因
你的代码存在三个核心问题:
- 同时创建了
commands.Bot和discord.Client实例,属于冗余操作,且discord.Client未传入application_id,导致命令树无法获取机器人的应用ID。 - 使用了错误的装饰器
@app_command(),正确的斜杠命令装饰器应为@bot.tree.command()。 - 单独创建的
CommandTree对象未与实际运行的Bot实例绑定,同步操作无效。
修复步骤
- 移除冗余的
discord.Client实例:commands.Bot继承自discord.Client,完全可以替代单独的Client,无需重复创建。 - 给
Bot实例传入application_id:在Discord开发者门户的机器人应用页面可以找到该ID,将其作为参数传入commands.Bot构造函数。 - 使用正确的装饰器定义命令:直接使用
bot.tree的command装饰器来绑定斜杠命令。 - 同步正确的命令树:在
on_ready事件中同步bot.tree,建议添加判断避免每次重启都重复同步。
修复后的完整代码
from discord import app_commands, Object from discord.ext import commands import config # 确保你的config文件包含TOKEN和APPLICATION_ID intents = commands.Intents.all() intents.members = True # 传入application_id参数,使用Bot自带的命令树 bot = commands.Bot( command_prefix="!", case_insensitive=True, intents=intents, application_id=config.APPLICATION_ID # 替换为你的机器人应用ID ) bot.remove_command("help") # 使用bot.tree.command装饰器定义斜杠命令 @bot.tree.command(name="test", description="测试斜杠命令") async def test(interaction): await interaction.response.send_message("Hello!") @bot.event async def on_ready(): # 仅在首次就绪时同步命令树(可选,避免重复同步) if not getattr(bot.tree, "_synced", False): # 替换为你的服务器ID,全局同步可去掉guild参数 await bot.tree.sync(guild=Object(id="你的服务器ID")) bot.tree._synced = True print(f"已登录为 {bot.user}") bot.run(config.TOKEN)
额外说明
- 如果需要全局同步斜杠命令(所有服务器可见),直接调用
await bot.tree.sync()即可,无需传入guild参数,但全局同步可能需要1小时左右的缓存时间。 - 确保你的机器人在Discord开发者门户中已开启"Message Content Intent"权限,否则可能影响命令响应。
内容的提问来源于stack exchange,提问作者Entasa
相关产品推荐
相关产品推荐

