Search code examples
pythondiscord.pycommand

I tried to make a balance command in discord.py but it didn't worked and gives unexpected errors


I was trying to make a balance checking command for my bot but when I tried it, it doesn't works the other command of bot works but not the bal command.

Changes made : defined user and added {} to json file.

Also this is the new error I'm getting:

Traceback (most recent call last):
  File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 21, in balance
    await open_account(ctx.author)
  File "main.py", line 36, in open_account
    users[str(user.id)]["wallet"]=0
KeyError: '774126913664188416'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '774126913664188416' 

Code below :

import discord
import discord.ext
import webserver
import json
from webserver import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix='.')

@client.event
async def on_ready():
  print('{0.user}'.format(client) , 'is now online')
  await client.change_presence(activity=discord.Game(name="with pokemons"))

@client.command(name='fact')
async def facts(ctx):
  await ctx.send("elon musk is the richest person in world")

@client.command(name='bal')
async def balance(ctx):
  await open_account(ctx.author)
  users = await get_bank_data()
  wallet_amt = users[str(user.id)]["wallet"]
  em = discord.Embed(title = f"{ctx.author}'s balance",color = discord.Color.blue())
  em.add_field(name = "Wallet balance", value = wallet_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)]["wallet"]=0
      
    with open("mainbank.json","w") as f:
      users = json.dump(users,f)
      return True

async def get_bank_data():
  with open("mainbank.json","r") as f:
    users = json.load(f)
    
  return users

keep_alive()
client.run('token')

Solution

  • Your code contains an error at one point. You forgot to define the user. The following code would be correct for the command:

    @client.command()
    async def balance(ctx):
        await open_account(ctx.author)
        user = ctx.author # Defined user
        users = await get_bank_data()
        wallet_amt = users[str(user.id)]["wallet"] # We need the user here
        em = discord.Embed(title=f"{ctx.author}'s balance", color=discord.Color.blue())
        em.add_field(name="Wallet balance", value=wallet_amt)
    
        await ctx.send(embed=em)
    

    Your async events are not wrong in themselves, but we don't need to define user there, it doesn`t do any good. So the correct thing would be:

    async def open_account(user):
        users = await get_bank_data()
    
        if str(user.id) in users:
            return False
        else:
            users[str(user.id)]["wallet"] = 0
    
        with open("mainbank.json", "w") as f:
            json.dump(users, f)
        return True
    

    Please make sure that your JSON file looks like this:

    {}
    

    To sum it up:

    • We defined user as it is needed
    • Removed unnecessary/useless definitions