discord.py:如何通过按钮固定斜杠命令的响应?
解决discord.py中斜杠命令响应固定的AttributeError问题
你遇到的AttributeError: 'InteractionResponse' object has no attribute 'pin'是因为interaction.response仅用于处理交互的回复逻辑,本身没有固定消息的方法。要固定斜杠命令的响应消息,必须先获取对应的Message对象再调用pin()方法。
解决方案
在按钮回调中,可通过以下两种方式获取目标消息并固定:
- 使用
interaction.message:直接获取触发按钮的消息(即斜杠命令的响应消息) - 使用
await interaction.original_response():获取当前交互的原始响应消息
修改后的代码示例
class suggestion_options(discord.ui.View): def __init__(self, embed): super().__init__() self.embed = embed @discord.ui.button(label='Deny Suggestion', emoji="❌", style=discord.ButtonStyle.primary) async def asdf(self, interaction: discord.Interaction, button: discord.ui.Button): view = undor(undor) # 注意确保undor是已定义的有效View类 await interaction.response.edit_message(content=f"Status: Denied", view=view) @discord.ui.button(label='Accept Suggestion', emoji="✅", style=discord.ButtonStyle.primary) async def hjkl(self, interaction: discord.Interaction, button: discord.ui.Button): view = undor(undor) await interaction.response.edit_message(content=f"Status: Accepted", view=view) @discord.ui.button(label='Save for Later', emoji="⏱️", style=discord.ButtonStyle.secondary) async def qqeqe(self, interaction: discord.Interaction, button: discord.ui.Button): # 获取原始斜杠命令响应消息并固定 original_msg = await interaction.original_response() await original_msg.pin() # 给点击按钮的用户发送仅其可见的反馈 await interaction.response.send_message("已固定该建议消息", ephemeral=True)
注意事项
- 确保机器人拥有固定消息的服务器权限,否则会抛出权限不足的异常。
- 如果需要在斜杠命令的主回调中固定自身响应,需先完成响应发送(如
await interaction.response.send_message(...)),再通过await interaction.original_response()获取消息执行固定操作。 ephemeral=True参数可让反馈消息仅对操作用户可见,避免干扰频道其他成员。
内容的提问来源于stack exchange,提问作者As2Bax
相关产品推荐
相关产品推荐

