使用discord.py开发机器人遇Interaction失败问题求助
问题排查与修复
1. 确保命令同步正确完成
你的on_ready事件仅调用tree.sync(),未指定目标服务器,可能导致同步延迟或失败。改为指定服务器同步,能让命令更快生效:
@client.event async def on_ready(): guild = discord.Object(id=GUILD) # 需确保GUILD是字符串格式的服务器ID await tree.sync(guild=guild) print(f"已在服务器 {guild.id} 同步命令,机器人就绪!")
注意:.env文件中GUILD变量必须填写正确的服务器ID(纯数字字符串)。
2. 检查机器人权限
确保你的机器人在目标服务器拥有以下权限:
- 发送消息权限
- 使用应用命令权限(邀请机器人时需勾选
applications.commandsscope,或在服务器角色设置中为机器人开启该权限)
3. 添加错误捕获定位问题
给命令绑定错误处理函数,能直接在控制台和Discord内看到具体报错:
@testouille.error async def test_error(interaction: discord.Interaction, error: app_commands.AppCommandError): await interaction.response.send_message(f"命令出错:{str(error)}", ephemeral=True) print(f"命令错误:{error}")
修复后的完整代码
# bot.py import os import discord from dotenv import load_dotenv from discord import app_commands load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') intents = discord.Intents.default() client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) @client.event async def on_ready(): guild = discord.Object(id=GUILD) await tree.sync(guild=guild) print(f"已在服务器 {guild.id} 同步命令,机器人就绪!") @tree.command(name="test", description="My first application Command") async def testouille(interaction: discord.Interaction): await interaction.response.send_message("Hello!") print("test") @testouille.error async def test_error(interaction: discord.Interaction, error: app_commands.AppCommandError): await interaction.response.send_message(f"命令出错:{str(error)}", ephemeral=True) print(f"命令错误:{error}") client.run(TOKEN)
额外注意事项
- 重启机器人后,等待
on_ready输出就绪信息再测试命令 - 若命令仍未生效,重新生成机器人邀请链接,确保勾选
bot和applications.commands两个scope后重新邀请机器人
内容的提问来源于stack exchange,提问作者Mauviette
相关产品推荐
相关产品推荐

