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

Discord机器人动态列表选择报错:NameError变量未定义求助

问题原因

你遇到的NameError本质是代码执行时机不匹配:

  1. Select_buyer类里的@discord.ui.select装饰器会在类被定义的时候就执行里面的列表推导式,这时候你在on_submit里赋值的全局变量character_in_raid还不存在(毕竟用户还没提交Modal呢)。
  2. 另外你写的character_in_raid ['name']是语法错误,character_in_raid是个字典列表,应该直接遍历列表本身,而不是取它的name键。
修正方案

把Select_buyer改成通过构造函数接收字符列表,动态生成下拉选项,这样就能等拿到数据后再创建选项:

class logs_input(discord.ui.Modal, title="Test"):
    tst = discord.ui.TextInput(label="1")
    async def on_submit(self, interaction: discord.Interaction):
        log_code = self.tst.value
        response = get_token()
        store_token(response)
        log_parse = get_logs.log_character(log_code)
        character_list = log_parse['rankedCharacters']
        # 实例化时传入字符列表,不需要全局变量
        await interaction.response.send_message(view=Select_buyer(character_list))


class Select_buyer(discord.ui.View):
    def __init__(self, character_list):
        super().__init__()
        # 动态创建select组件,此时已经有了字符数据
        char_select = discord.ui.Select(
            placeholder="Choose buyer",
            min_values=0, max_values=20,
            options=[
                discord.SelectOption(label=char['name'], value=char['name']) 
                for char in character_list
            ]
        )
        # 绑定回调函数
        char_select.callback = self.buyer_select
        self.add_item(char_select)

    async def buyer_select(self, interaction: discord.Interaction, select: discord.ui.Select):
        selected_values = select.values
        print(selected_values)
        await interaction.response.send_message(selected_values)
核心改动说明
  • 删掉全局变量,直接把字符列表作为参数传给Select_buyer的构造函数,避免全局变量的时序问题。
  • 在Select_buyer的__init__方法里动态创建select组件,这样只有当用户提交Modal、拿到字符数据后,才会生成下拉选项,从根源上解决变量未定义的问题。
  • 修正了遍历列表的错误写法,直接遍历character_list即可获取每个字符字典。

这样调整后,代码就能正常生成基于用户输入的下拉选择框了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:03:27