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

Pycord自定义View传参报错'children'不存在,按钮不渲染求助

问题解决方法

核心原因

你的MyView类重写了__init__方法,但没有调用父类discord.ui.View的构造函数,导致父类负责初始化的children属性缺失,这是按钮无法渲染、报错的直接原因。

修复步骤及代码调整

  1. 调用父类构造函数:在MyView的__init__中添加super().__init__(),确保父类的必要属性被初始化。可按需设置timeout(比如timeout=None让View永久有效)。
  2. 修正按钮禁用属性:按钮禁用的正确属性是disabled,而非disable。
  3. 修正实例方法调用:video_finder是实例方法,需用self.video_finder()调用,不能直接通过类调用MyView.video_finder()。
  4. 补充缺失方法:你的代码中未定义video_finder方法,需补充实现(否则会触发新的报错)。

修复后的完整代码

class MyView(discord.ui.View):
    def __init__(self, link):
        # 调用父类构造函数,初始化children等核心属性
        super().__init__(timeout=None)
        self.link = link

    # 补充实现video_finder方法,根据需求编写下载逻辑
    async def video_finder(self):
        # 使用self.link获取传入的视频链接,执行下载操作
        pass

    @discord.ui.button(label='480p', style=discord.ButtonStyle.gray, emoji='🎥')
    async def button_callback_480(self, button, interaction):
        button.disabled = True
        await self.video_finder()

        await interaction.response.send_message('downloading the file. Check the server for file')
        await interaction.followup.send('follow up added to the queue')
        # 更新消息的View,让按钮禁用状态生效
        await interaction.message.edit(view=self)

    @discord.ui.button(label='720p', style=discord.ButtonStyle.danger, emoji='🎥')
    async def button_callback_720(self, button, interaction):
        button.disabled = True
        # 若720p也需调用下载逻辑,取消下方注释
        # await self.video_finder()
        
        await interaction.response.send_message('downloading the file. Check the server for file')
        await interaction.followup.send('follow up added to the queue')
        await interaction.message.edit(view=self)

# 斜杠命令无需修改
@bot.command(description="Choose the quality of video you want to download")
async def ytdl(ctx, link: str):
    view = MyView(link)
    await ctx.respond('Choose the quality of video you want to download', view=view)

额外说明

  • 调用interaction.message.edit(view=self)是为了让按钮的禁用状态实时同步到消息上,用户能直观看到按钮状态变化。
  • 如果不需要View永久生效,可将timeout设为具体秒数,比如super().__init__(timeout=300)表示5分钟后View自动失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:25:37