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

Discord Modal提及打开用户遇NameError,求解决方法

解决方案

你的错误根源在于:feedback_text是类级别的属性,在类定义阶段就会被解析,此时类还未实例化,self根本不存在,所以会抛出NameError。要实现动态根据用户设置输入框标签,必须在实例初始化阶段创建输入框。

修正后的代码

import discord
from discord.ext import commands

class Feedback(discord.ui.Modal, title='Feedback'):
    def __init__(self, ctx: commands.Context):
        # 先调用父类的初始化方法
        super().__init__(title='Feedback')
        self.ctx = ctx
        
        # 动态生成第一个输入框,此时self已存在,可以访问ctx.author
        user_feedback_input = discord.ui.TextInput(
            label=f'Hey {self.ctx.author}, 你觉得服务器目前怎么样?',
            placeholder='在这里输入反馈...'
        )
        self.add_item(user_feedback_input)
        
        # 添加第二个输入框
        feature_feedback_input = discord.ui.TextInput(
            label='你觉得这个新功能怎么样?',
            style=discord.TextStyle.long,
            placeholder='在这里输入详细反馈...',
            required=False,
            max_length=300,
        )
        self.add_item(feature_feedback_input)

# 调用模态框的命令示例
@bot.command()
async def feedback(ctx):
    # 传入上下文实例化模态框
    modal = Feedback(ctx)
    await ctx.send_modal(modal)

关键说明

  1. 类属性 vs 实例属性:类级别的变量在类加载时就会被初始化,无法访问实例化后的self;只有在__init__方法内创建的实例属性,才能正常使用self访问上下文。
  2. 父类初始化:必须先调用super().__init__()完成父类的初始化,再调用self.add_item()添加输入框。
  3. 版本要求:确保你的discord.py版本在2.0及以上,模态框功能是v2.0新增的特性。

内容的提问来源于stack exchange,提问作者Eliahs Johansson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:55:22