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

Discord Modal组件无法用self.user.name设置TextInput默认值的问题

问题分析与解决方案

核心问题

你定义的name是类属性,在类加载阶段就会执行discord.ui.TextInput的初始化逻辑,此时类还未实例化,self(实例对象的引用)根本不存在,自然无法访问self.user.name。另外,你通过requests.get获取的是Response对象,需要先解析为JSON数据才能拿到name字段。


修正后的代码

1. 调整Modal类的实现(动态添加组件)

class ModalRegisterUser(discord.ui.Modal, title='Registrar Pedido'):
    def __init__(self, user_data):
        super().__init__()
        self.user_data = user_data
        
        # 动态创建TextInput并添加到模态框
        self.name_input = discord.ui.TextInput(
            default=self.user_data.get('name', ''),  # 用get避免键不存在报错
            label='Seu nome',
            style=discord.TextStyle.short,
            placeholder='Pucci',
            required=True,
            max_length=20
        )
        self.add_item(self.name_input)

    async def on_submit(self, interaction: discord.Interaction):
        # 获取输入框的内容需要访问value属性
        print(f"Nome registrado: {self.name_input.value}")
        await interaction.response.send_message(f'Você foi registrado!', ephemeral=True)

    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        if isinstance(error, PriceError):
            await interaction.response.send_message(error.args[0], ephemeral=True)
        else:
            await interaction.response.send_message("Oops, ocorreu algum erro...", ephemeral=True)

2. 修正实例化时的请求处理

@app_commands.command(
    name="registrar_usuario",
    description="Registra seu perfil no code freelas!"
) 
async def Registrar(self, interaction: discord.Interaction):
    response = requests.get(f'http://localhost:7777/{interaction.user.id}')
    # 解析后端返回的JSON数据
    user_data = response.json()
    await interaction.response.send_modal(ModalRegisterUser(user_data))

关键说明

  • 将TextInput组件的创建移到__init__方法中,此时实例已生成,可以正常访问self.user_data
  • 使用self.add_item()手动将组件添加到模态框(类属性方式是discord.py自动识别添加,动态创建需手动操作)
  • 必须解析requests.get的响应为JSON,否则无法获取name字段
  • 获取输入框内容时要访问.value属性,而不是直接打印组件对象

内容的提问来源于stack exchange,提问作者Camper Que Odeia Camper COC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:35:27