Discord bot 回溯密钥错误:'736458231848894534'

时间:2021-05-13 22:52:52

标签: python discord.py bots

我正在尝试使用经济型机器人的 YouTube 教程制作 Discord 机器人,但出现以下错误:

<块引用>

忽略命令平衡中的异常:回溯(最近调用 最后):文件 “C:\Python39\lib\site-packages\discord\ext\commands\core.py”,第 85 行, 在包裹 ret = await coro(*args, **kwargs) 文件“C:\Users\polly\OneDrive\Documents\HACK\Discord Bot\Python\currency.py”,第 22 行,平衡 wallet_amt = users[str(user.id)]["wallet"] KeyError: '736458231848894534'

上述异常是以下异常的直接原因:

回溯(最近一次调用最后一次):文件 “C:\Python39\lib\site-packages\discord\ext\commands\bot.py”,第 939 行, 在调用 等待 ctx.command.invoke(ctx) 文件“C:\Python39\lib\site-packages\discord\ext\commands\core.py”,行 863,在调用中 等待注入(*ctx.args,**ctx.kwargs)文件“C:\Python39\lib\site-packages\discord\ext\commands\core.py”,第94行, 在包裹 从 exc discord.ext.commands.errors.CommandInvokeError 引发 CommandInvokeError(exc):命令引发了一个 异常:KeyError:'736458231848894534'

这是有错误的部分:

@client.command()
async def balance(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()

    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]

    em = discord.Embed(title = f"{ctx.author.name}'s balance", color = discord.color.red())
    em.add_field(name = "Wallet balance", value = wallet_amt)
    em.add_field(name = "Bank balance", value = bank_amt)
    await ctx.send(embed = em)


async def open_account(user):
    users = await get_bank_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0

有人可以帮忙吗?如果此错误未解决,我将无法继续。 谢谢!

1 个答案:

答案 0 :(得分:0)

你搞砸了自己的命名方案!据我所知,user 是一个 discord.Member 对象(不可分配,这是您的错误的来源)和 users,这是一个列表discord.Member。确保针对每种情况使用正确的方法。您只能索引一个列表,但您正在尝试索引 user 对象。在相关位置用user替换你的单个users

@client.command()
async def balance(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()

    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]

    em = discord.Embed(title = f"{ctx.author.name}'s balance", color = discord.color.red())
    em.add_field(name = "Wallet balance", value = wallet_amt)
    em.add_field(name = "Bank balance", value = bank_amt)
    await ctx.send(embed = em)


@client.command()
async def beg(ctx):
    await open_account(ctx.author)

    users = await get_bank_data()
    user = ctx.author

    earnings = random.randrange(101)


    await ctx.send("Someone gave you {earnings} kash")



    users[str(user.id)]["wallet"] += earnings

    with open("mainback.json", "w") as f:
        json.dump(users, f)


async def open_account(user):
    users = await get_bank_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0


    with open("mainback.json", "w") as f:
        json.dump(users, f)
    return True