【问题标题】:Discord.py if statements not workingDiscord.py if 语句不起作用
【发布时间】:2018-07-18 14:47:19
【问题描述】:

我有这段代码(Python 3.6),它应该这样做,如果用户有一个钱包,然后显示余额。如果他们没有钱包,请创建一个钱包并出示余额。

我有一个名为 amount.json 的文件,其中包含用户 ID。

代码总是跳转到它说用户没有帐户的语句,而实际上我有,并给我错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: BlockIoAPIError: Failed: Label already exists on your account for Network=DOGE.

我该如何解决它,使它不会在我每次执行余额命令时都尝试制作钱包?

代码:

@client.command(pass_context=True)
async def balance(ctx):
    user_id = ctx.message.author.id
    global amounts
    if user_id not in amounts:
        block_io.get_new_address(label=user_id)
        knee = block_io.get_address_balance(label=user_id)
        s1 = json.dumps(knee)
        d2 = json.loads(s1)
        d2['data']['available_balance']
        embed=discord.Embed(description="Bitcoin: btc here \n\nLitecoin: here\n\nDogecoin: {}".format(d2['data']['available_balance']), color=0x00ff00)
        await client.say(embed=embed)
        with open('amounts.json', 'w+') as f:
            json.dump(amounts, f)
    elif user_id in amounts:
        knee = block_io.get_address_balance(label=user_id)
        s1 = json.dumps(knee)
        d2 = json.loads(s1)
        d2['data']['available_balance']
        embed=discord.Embed(description="Bitcoin: btc here \n\nLitecoin: here\n\nDogecoin: {}".format(d2['data']['available_balance']), color=0x00ff00)
        await client.say(embed=embed)
        with open('amounts.json', 'w+') as f:
            json.dump(amounts, f)

Json 代码:

amounts = {}
@client.event
async def on_ready():
    global amounts
    try:
        with open('amounts.json') as f:
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}

【问题讨论】:

  • 显示将amounts.json 加载到amounts 变量中的代码。另外,block_io 是什么?这就是你的错误所在。
  • block_io 是一个区块链钱包 @PatrickHaugh 我现在用 json 代码更新它
  • 您能否也显示来自 amount.json 文件的条目?还要检查print(discord.__version__) 以查看您使用的是哪个版本的 discord.py。在某些版本中,ids 是字符串,但在最近的版本中,它们是整数。
  • 版本为 0.16.12
  • 输入为:

标签: python python-3.x discord.py


【解决方案1】:

您需要对您的 json 文件进行数据修复,使其具有您的代码所期望的结构。如果有重复的条目,下面将对它们的值求和。这不是你的机器人的一部分,你应该只需要运行一次。您还需要查看任何其他涉及或依赖amounts的代码

import json

with open('amounts.json') as f:
    old_amounts = json.load(f)

new_amounts = {}
for d in old_amounts:
    for k, v in d:
        new_amounts[k] = new_amounts.get(k, 0) + v

with open('amounts.json') as f:
    json.dump(new_amounts, f)

那些d2 = json.loads(s1) 行应该是d2 = json.load(s1)

【讨论】:

  • 非常感谢!很快就会测试它:D
  • 但如果我喜欢:如果 x 中的 user_id: 是旧金额还是新金额?
  • 运行此脚本后,amounts.json 文件应更改为字典结构,因此当您将load 放入您的机器人时,您将获得字典。所以下次你运行你的机器人时,它会使用新的金额。
猜你喜欢
  • 2019-01-10
  • 2021-09-04
  • 2012-07-16
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2017-10-22
  • 2018-05-11
相关资源
最近更新 更多