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

discord.py中Encuesta类如何给@discord.ui.button传入self.buttonid

解决discord.py中View类实例属性作为按钮custom_id的问题

因为@discord.ui.button装饰器是在类定义阶段执行的,此时还没有创建类的实例,自然无法访问self(self只有在实例方法执行时才存在),所以直接在装饰器里写custom_id=self.buttonid会报错。

不需要修改原装饰器,用动态添加按钮的方式就能解决,具体实现如下:

import discord
from discord.ui import View, Button

class Encuesta(View):
    def __init__(self, button_id: str, timeout=None):
        super().__init__(timeout=timeout)
        self.buttonid = button_id
        
        # 动态创建按钮,将实例的buttonid赋值给custom_id
        vote_button = Button(
            label="参与调查",
            custom_id=self.buttonid,
            style=discord.ButtonStyle.primary
        )
        # 绑定按钮的回调函数
        vote_button.callback = self.on_vote_click
        # 将按钮添加到视图中
        self.add_item(vote_button)
    
    # 按钮点击的回调逻辑
    async def on_vote_click(self, interaction: discord.Interaction):
        # 这里写你的调查处理逻辑,比如记录投票、返回反馈等
        await interaction.response.send_message(
            f"已记录你的投票,当前按钮custom_id: {self.buttonid}",
            ephemeral=True
        )

使用这个类时,只需传入不同的button_id就能创建多个独立的调查视图:

# 示例:创建两个不同的调查
encuesta1 = Encuesta(button_id="survey_001")
encuesta2 = Encuesta(button_id="survey_002")

# 发送调查消息
await ctx.send("请参与调查1", view=encuesta1)
await ctx.send("请参与调查2", view=encuesta2)

这种方式的核心是:在类实例化后(__init__方法中)创建按钮,此时self已经存在,可以直接引用实例属性buttonid作为按钮的custom_id,完全避开了装饰器阶段无法访问self的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:24:27