discord.py:点击按钮后如何编辑斜杠命令的临时消息?
问题解决方法
你的代码存在几个关键问题,导致点击按钮后无法编辑原临时消息,以下是修正方案:
错误原因分析
- 参数混淆:按钮回调里误用了未定义的
ctx变量,实际可用的上下文对象是interaction。 edit_message调用错误:该方法需要传入content或embed等明确参数,不能直接传字符串,且要针对当前交互的消息操作。- 视图有效性问题:临时消息的视图若未设置持久化,可能在交互触发前超时失效。
修正后的完整代码
# 自定义视图类 class MyView(discord.ui.View): def __init__(self): super().__init__(timeout=None) # 禁用超时,保持视图持久有效 # 确认按钮逻辑 @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green) async def confirm_button(self, interaction: discord.Interaction, button: discord.ui.Button): # 禁用按钮防止重复点击 button.disabled = True # 创建提交成功的新Embed success_embed = discord.Embed(title="提交成功", description="你的建议已确认提交", color=discord.Colour.green()) success_embed.set_footer(text=f"用户ID: {interaction.user.id}") # 编辑原临时消息,替换内容并更新视图 await interaction.response.edit_message(embed=success_embed, view=self) @bot.tree.command(name="suggest", description="提交你的建议") async def suggest(interaction: discord.Interaction, title: str, description: str): # 创建初始确认用的Embed embed = discord.Embed(title="请确认以下信息是否正确?", description="点击确认按钮提交建议", color=discord.Colour.random()) embed.set_thumbnail(url=interaction.user.avatar.url) embed.add_field(name="标题", value=title, inline=False) embed.add_field(name="描述", value=description, inline=False) embed.set_footer(text=f"用户ID: {interaction.user.id}") # 发送临时消息并附加视图 await interaction.response.send_message(embed=embed, view=MyView(), ephemeral=True)
关键修改说明
- 将斜杠命令的参数名从
ctx改为interaction,符合discord.py的命名规范,避免上下文混淆。 - 按钮回调中使用
interaction.response.edit_message编辑原消息,同时传入更新后的Embed和禁用按钮的视图。 - 视图初始化时设置
timeout=None,确保临时消息的视图不会提前超时失效。 - 点击按钮后禁用按钮,避免用户重复触发交互操作。
内容的提问来源于stack exchange,提问作者As2Bax
相关产品推荐
相关产品推荐

