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

Discord.py 非子类实现Button超时自动禁用的配置方法

不需要自定义View子类,直接操作View实例的属性就能实现超时自动禁用按钮,有两种常见实现方案适配不同场景:

方案1:无交互超时(适合翻页类场景,最后一次操作后计时)

利用View自带的超时机制即可,初始化时传入超时时长,再绑定超时回调处理禁用逻辑:

button1 = Button(style=discord.ButtonStyle.blurple, emoji='⬅')
button2 = Button(style=discord.ButtonStyle.blurple, emoji='➡')

# 初始化View时指定timeout参数,单位为秒,示例为60秒无交互触发超时
view = View(timeout=60)
view.add_item(button1)
view.add_item(button2)

# 编写超时触发的回调逻辑
async def timeout_callback():
    # 禁用两个按钮
    button1.disabled = True
    button2.disabled = True
    # 更新原消息的view,让按钮禁用状态生效
    await message.edit(view=view)

# 给view实例绑定超时回调
view.on_timeout = timeout_callback

# 原有的embed逻辑
# *some embed code*

message = await ctx.send(embed=embedVar, view=view)

该方案的计时会在每次用户和按钮交互后重置,也就是没人操作按钮满指定时长后才会触发禁用,适配翻页按钮的使用场景。

方案2:固定时长超时(从消息发送开始计时,不受交互影响)

如果需要消息发出后固定时长就禁用按钮,不管期间有没有人点击,直接用异步等待实现即可:

import asyncio

button1 = Button(style=discord.ButtonStyle.blurple, emoji='⬅')
button2 = Button(style=discord.ButtonStyle.blurple, emoji='➡')

view = View()
view.add_item(button1)
view.add_item(button2)

# 原有的embed逻辑
# *some embed code*

message = await ctx.send(embed=embedVar, view=view)
# 等待指定时长,示例为60秒
await asyncio.sleep(60)
# 禁用按钮并更新消息
button1.disabled = True
button2.disabled = True
await message.edit(view=view)

小提示:如果需要超时后直接移除按钮而不是禁用,把编辑消息时的view参数设为None即可。

内容的提问来源于stack exchange,提问作者Tato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:45:29