Nextcord机器人按钮重启不失效:嵌套类调用问题求助
解决Nextcord机器人重启后按钮失效及嵌套类访问问题
问题根源
你把按钮所属的View类(或Button类)嵌套在Cog的命令方法内部,会导致两个关键问题:
- 该类的作用域仅限于命令方法内部,外部的
on_ready事件无法直接访问它; - 只有当这个命令被执行过一次后,嵌套类才会被Python定义,机器人重启后未执行命令时,这个类根本不存在,自然无法注册。
正确解决方案
步骤1:重构View类的位置
把负责按钮的View类从命令方法内部移到Cog的类级别(与Cog的方法同级),或者直接放在模块的全局作用域,让外部可以访问。
示例Cog代码:
from nextcord.ext import commands import nextcord from nextcord import Interaction, ButtonStyle class MyCog(commands.Cog): # 将View类移到Cog类内部(类级别,非方法内部) class PersistentButtonView(nextcord.ui.View): def __init__(self): super().__init__(persistent=True) # 必须开启持久化 @nextcord.ui.button( label="重启依然有效", style=ButtonStyle.primary, custom_id="persist_btn_001" # 必须指定唯一custom_id,不能省略 ) async def handle_button(self, button: nextcord.ui.Button, interaction: Interaction): await interaction.response.send_message("按钮触发成功!", ephemeral=True) def __init__(self, bot): self.bot = bot @commands.command() async def send_persist_btn(self, ctx): # 实例化View并发送消息 view = self.PersistentButtonView() await ctx.send("点击下方按钮(重启机器人后仍可使用)", view=view) def setup(bot): bot.add_cog(MyCog(bot))
步骤2:在on_ready中注册View
在on_ready事件里,通过Cog实例获取View类,实例化后调用bot.add_view()注册:
@bot.event async def on_ready(): print(f"已登录:{bot.user.name}") # 获取目标Cog实例 target_cog = bot.get_cog("MyCog") if target_cog: # 实例化持久化View并注册 persistent_view = target_cog.PersistentButtonView() bot.add_view(persistent_view)
关键注意事项
- 所有需要持久化的按钮必须显式指定
custom_id,不能依赖自动生成的ID; - View类必须在初始化时设置
persistent=True; - 机器人首次发送带该View的消息时,不需要提前调用
add_view,但重启后必须在on_ready中注册,否则Discord不会将按钮交互事件转发给机器人。
内容的提问来源于stack exchange,提问作者Jacob3ez
相关产品推荐
相关产品推荐

