You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py:点击按钮后如何编辑斜杠命令的临时消息?

问题解决方法

你的代码存在几个关键问题,导致点击按钮后无法编辑原临时消息,以下是修正方案:

错误原因分析

  1. 参数混淆:按钮回调里误用了未定义的ctx变量,实际可用的上下文对象是interaction。
  2. edit_message调用错误:该方法需要传入content或embed等明确参数,不能直接传字符串,且要针对当前交互的消息操作。
  3. 视图有效性问题:临时消息的视图若未设置持久化,可能在交互触发前超时失效。

修正后的完整代码

# 自定义视图类
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:14:58