如何通过Discord按钮实现消息编辑?我的按钮功能失效
Discord按钮点击后无法更新样式及编辑消息的解决方案
你的代码存在两个关键问题导致按钮功能异常:
- 修改按钮样式后,未将更新后的
View实例传入edit_message,Discord无法感知按钮状态变化 - 仅修改消息内容而不同步View,按钮会保持初始样式
修正后的完整代码
class Buttons(discord.ui.View): def __init__(self, *, timeout=180): super().__init__(timeout=timeout) @discord.ui.button(label="Button", style=discord.ButtonStyle.gray) async def blurple_button(self, button: discord.ui.Button, interaction: discord.Interaction): # 更新按钮样式 button.style = discord.ButtonStyle.green # 编辑消息时传入更新后的View,确保按钮状态同步 await interaction.response.edit_message( content="This is an edited button response!", view=self ) class test(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def test(self, ctx): await ctx.send("This message has buttons!", view=Buttons())
核心说明
- 调用
interaction.response.edit_message时必须传入view=self:因为你修改了View内部的按钮属性,只有将更新后的View传递给Discord,它才会重新渲染按钮的新样式 - 若仅修改消息内容不传递View,Discord会保留按钮的初始状态,样式不会发生任何变化
内容的提问来源于stack exchange,提问作者FlamyIce
相关产品推荐
相关产品推荐

