开发Discord音乐机器人点击按钮提示“This interaction failed”如何解决
错误原因
- 字符串语法错误:发送歌单列表的字符串存在引号错位,
('1. Test1\n2. Test2.\n3. Test3'\n4. Test4')中Test3后的单引号提前闭合,属于基础语法错误,会直接导致代码无法运行。 - 组件未初始化:导入
Discord_Components后未和bot实例绑定,无法监听按钮点击事件,交互无法被识别触发报错。 - 缩进错误:
if response.custom_id == '1'代码行缩进不符合Python语法规范,代码无法正常执行。 - 响应逻辑覆盖不全:仅处理了id为1的按钮点击事件,剩余3个按钮点击后无任何响应逻辑,Discord要求交互必须在3秒内回复,未响应的交互会直接返回“This interaction failed”。
- 可选注意:当前使用的
discord-components库已停止维护,若后续出现兼容问题可切换至discord.py 2.0+版本的原生组件功能。
修正后代码
import discord from discord.ext import commands from discord_components import Discord_Components, Button, ButtonStyle intents = discord.Intents.all() bot = commands.Bot(command_prefix='$') # 绑定组件实例,开启按钮事件监听 Discord_Components(bot) @bot.command() async def playlist(ctx): await ctx.send('Hey! You can choose the playlist by choosing your mood:') # 修复字符串引号错位问题 await ctx.send('1. Test1\n2. Test2.\n3. Test3\n4. Test4', components=[ [ Button(style=ButtonStyle.blue, label='Test1', custom_id='1'), Button(style=ButtonStyle.green, label='Test2', custom_id='2'), Button(style=ButtonStyle.red, label='Test3', custom_id='3'), Button(style=ButtonStyle.gray, label='Test4', custom_id='4') ], ]) response = await bot.wait_for("button_click", check=lambda inter: inter.channel == ctx.channel) # 修复缩进错误 if response.custom_id == '1': await response.respond( embed=discord.Embed(title='Open it ?'), components=[ [ Button(style=ButtonStyle.red, label='No', custom_id='no'), Button(style=ButtonStyle.URL, label='Yep', url='https://www.youtube.com/') ] ] ) # 补充其余按钮的基础响应逻辑,避免超时报错 else: await response.respond(f"你选择了编号{response.custom_id}的歌单", ephemeral=True) bot.run('TOKEN')
内容的提问来源于stack exchange,提问作者Максим Шнер
相关产品推荐
相关产品推荐

