py 线 | UnboundLocalError:赋值前引用的局部变量“embed”

问题描述 投票:0回答:1
@bot.slash_command(name = "redeem", description = "Redeem your Key")
async def redeem(ctx, key):
    with open('order_data.txt', 'r') as file:
        lines = file.readlines()
        for line in lines:
            product, order_key = line.strip().split(':')
            if order_key == key:
                with open('consumed_keys.txt', 'r') as consumed_file:
                    consumed_keys = consumed_file.readlines()
                    if key in consumed_keys:
                        await ctx.send(f"Duplicate key sent by {ctx.author.mention}: {key}")
                    else:
                        with open('consumed_keys.txt', 'a') as consumed_file:
                            consumed_file.write(f'{key}\n')
                        print(f'Successfully verified {ctx.author.name}\'s key: {key}')
                        role = discord.utils.get(ctx.guild.roles, name='Customer')
                        await ctx.author.add_roles(role)
                        ##  EMBED++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                        embed = discord.Embed(
                 title="Order Verification",
        description=f"{ctx.author.mention}, Key Verified",
        color=discord.Colour.green(),
                        )
            embed.add_field(name="Product Name", value=product, inline=True)
            embed.add_field(name="Product Key", value=key, inline=True)
            embed.set_footer(text="Test Footer")
            await ctx.respond(embed=embed)
            break
        else:
            print(f'Verification failed by {ctx.author.name}')
            await ctx.send(f"Invalid order id, {ctx.author.mention}")

完整错误

Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\Desktop\dc bot\redeem bot  rewrite\bot.py", line 38, in redeem
    embed.add_field(name="Product Name", value=product, inline=True)
UnboundLocalError: local variable 'embed' referenced before assignment

尝试使用具有正常响应(无嵌入)的命令并且有效 我认为它说该功能未关闭嵌入,但不知道如何解决它

python discord discord.py bots pycord
1个回答
0
投票

embed = ...
线移动到
embed.add_field()
的同一缩进处,或将所有
embed.add_field()
移动到
embed = ...

的同一缩进处
© www.soinside.com 2019 - 2024. All rights reserved.