如何在discord.py中实现View超时后按钮点击提示功能?
在discord.py中实现View超时后按钮点击提示功能
核心思路
discord.py的discord.ui.View支持设置超时时间,超时会触发内置的on_timeout方法。我们可以给自定义View添加一个状态标记,在按钮的回调逻辑里先检查这个标记,判断是否已超时,进而返回对应的提示信息。
完整实现代码
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.default()) class TimeoutView(discord.ui.View): def __init__(self): # 设置超时时间(示例为30秒,可按需调整) super().__init__(timeout=30.0) # 标记View是否已超时 self.timed_out = False # 重写超时回调方法 async def on_timeout(self): self.timed_out = True # 可选:如果希望超时后按钮变灰禁用,取消下方注释 # for item in self.children: # item.disabled = True # await self.message.edit(view=self) @discord.ui.button(label="测试按钮", style=discord.ButtonStyle.primary) async def test_button(self, interaction: discord.Interaction, button: discord.ui.Button): # 优先检查是否超时 if self.timed_out: await interaction.response.send_message("时间已过期,请重复执行命令", ephemeral=True) return # 未超时情况下的正常逻辑 await interaction.response.send_message("按钮点击成功!", ephemeral=True) @bot.command() async def test(ctx): view = TimeoutView() # 保存消息对象,用于后续可能的View更新(比如禁用按钮) view.message = await ctx.send("点击下方按钮测试超时功能", view=view) bot.run("你的机器人令牌")
关键细节说明
timed_out属性:作为超时状态的标记,初始为False,超时后由on_timeout方法改为True。- 按钮回调判断:每次点击按钮时先校验超时状态,若已超时则直接返回提示,不执行原有业务逻辑。
ephemeral=True:让提示消息仅对点击按钮的用户可见,避免干扰其他成员。- 可选禁用按钮:如果希望超时后按钮直接变灰无法点击,可取消
on_timeout方法内的注释代码,通过编辑消息更新View状态。
内容的提问来源于stack exchange,提问作者SharkiKos
相关产品推荐
相关产品推荐

