如何实现仅消息作者可使用Discord按钮?现有代码失效求助
解决Discord按钮仅允许消息作者使用的问题
你的判断逻辑失效是因为discord.Interaction对象没有creator属性,正确的做法是在初始化View时传入消息作者并保存,再在按钮回调中进行校验。
修正后的代码实现
class HangmanButton(discord.ui.View): def __init__(self, author: discord.User, *, timeout=180): super().__init__(timeout=timeout) # 保存消息作者为实例变量 self.author = author @discord.ui.button(label="Начать Игру", style=discord.ButtonStyle.gray) async def button(self, interaction: discord.Interaction, button: discord.ui.Button): # 校验当前交互用户是否为消息作者 if interaction.user != self.author: embed = discord.Embed( title='❌| Ошибка', description='Вы не можете играть в своей собственной игре.', color=discord.Color.darker_grey() ) return await interaction.response.send_message(embed=embed, ephemeral=True) # 校验通过,打开模态框 await interaction.response.send_modal(HangmanStartModal())
使用示例
当发送带按钮的消息时,需要将消息作者传入View的初始化参数:
# 假设这是在命令或事件处理函数中,message是发送按钮的消息对象 await message.channel.send( content="Нажмите кнопку чтобы начать игру", view=HangmanButton(author=message.author) )
关键说明
- 在View的
__init__中新增author参数,将消息作者存储为实例变量,这样按钮回调可以直接访问。 - 校验时直接对比
interaction.user和self.author,确保只有消息作者能触发按钮的正常逻辑。 - 错误提示使用
ephemeral=True,确保只有触发交互的用户能看到错误信息。
内容的提问来源于stack exchange,提问作者user21343500
相关产品推荐
相关产品推荐

