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

如何让discord.py验证按钮在Bot重载后无需重发即可生效?

解决Discord.py重载Bot后验证按钮无需重发即可工作的问题

问题根源

你当前的代码有两个关键问题导致重载Bot后旧按钮失效:

  1. 你在on_interaction里用了bot.wait_for("button_click"),这完全多余,而且会阻塞事件处理——按钮的点击逻辑本来就该由View里的按钮回调函数处理。
  2. 没有将设置了timeout=None的View注册到Bot上。Discord.py要求永久View(超时为None)必须通过bot.add_view()注册,这样Bot重启后才能识别之前发送的按钮的交互请求。

修改步骤

  1. 移除无效的on_interaction监听器:这个监听器不仅没用,还会干扰正常的按钮回调逻辑,直接删掉就行。
  2. 注册永久View:在setup函数里,实例化你的button View,然后调用bot.add_view()注册它,这样Bot启动时就会监听这个View对应的按钮交互。
  3. 补全缺失的导入:你的代码里用到了discord.ui.View和discord.ButtonStyle,但只导入了discord.ui.Button,需要添加import discord。

修改后的完整代码

import discord
from discord.ext import commands
from discord import app_commands
import json
from discord.ui import Button

with open('.\config.json') as f:
    data = json.load(f)  


class button(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        
    @discord.ui.button(label="验证", style=discord.ButtonStyle.success, custom_id="ver")
    async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):    
        user = interaction.user
        role = interaction.guild.get_role(data['verify_role'])
        await user.add_roles(role)
        await interaction.response.send_message("验证成功!", ephemeral=True)

        
class verify(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command(name="ver", description="发送验证按钮")
    async def verify(self, interaction: discord.Interaction) -> None:
        await interaction.response.send_message("点击下方按钮完成验证", view=button())


async def setup(bot: commands.Bot) -> None:
    # 注册永久View,确保Bot重启后能处理旧按钮
    await bot.add_cog(verify(bot))
    bot.add_view(button())

原理说明

当你调用bot.add_view(button())时,Bot会记住这个View里的按钮custom_id(这里是"ver"),之后不管是Bot重启前还是重启后发送的带有这个custom_id的按钮,只要被点击,Bot都会自动找到对应的回调函数执行,不需要重新发送按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:50:37