简体   繁体   中英

Discord.py if statements not working

I have this code (Python 3.6), and its supposed to do, if the user has a wallet with them, then show the balance. If they don't have a wallet, crate a wallet and show the balance.

I have a file called amounts.json with the users id.

The code always jumps to the statement where it says the user does not have a account, when in fact I do, and gives me the error:

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

How can I fix it so it does not try and make a wallet every single time I do the balance command?

Code:

@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 code:

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 = {}

You need to datafix your json file so it has the structure your code expects. If there are duplicate entries the below will sum their values. This isn't part of your bot and you should only have to run this once. You'll also want to go over any other code that touches or relies on 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)

Those d2 = json.loads(s1) lines should probably be d2 = json.load(s1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM