Home > Blockchain >  Discord Economy Bot Not Sending Messages
Discord Economy Bot Not Sending Messages

Time:04-11

Hey I've been trying to get this discord economy bot to work with no luck. When I launch the bot I don't get any errors until I run the wallet command. I've included the code and the error I'm receiving below. Any help would be much appreciated. I believe it has something to do with json and not being able to write to it.

The code:

import discord
from discord.ext import commands
import json
import os
import random

os.chdir("C:\\Users\\Nick\\Desktop\\Discord Bots\\EconomyManager")

client = commands.Bot(command_prefix = '!',intents=discord.Intents.all())


@client.event
async def on_ready():
    print("Ready!")

#user commands
@client.command(aliases=['w'])
async def wallet(ctx):
    await open_account(ctx.author)
    
    users = await get_bank_data()

    rs3_amt = users[str(user.id)]["RS3"]
    old_amt = users[str(user.id)]["07"]

    em = discord.Embed(title = f"{ctx.author.name}'s Balance",color = discord.Color.red())
    em.add_field(name = "RS3",value = rs3_amt)
    em.add_field(name = "07",value = old_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)]["RS3"] = 0
        users[str(user.id)]["07"] = 0

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


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

    return users

async def update_bank(user,change,mode = "wallet"):
    users = await get_bank_data()

    users[str(user.id)][mode]  = change

    with open("mainwallet.json","w") as f:
        json.dump(users,f)
    bal = [users[str(user.id)]["RS3"],users[str(user.id)]["07"]]
    return bal

client.run("")

The error:

Ignoring exception in command wallet:
Traceback (most recent call last):
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Nick\Desktop\Discord Bots\EconomyManager\main.py", line 19, in wallet
    await open_account(ctx.author)
  File "C:\Users\Nick\Desktop\Discord Bots\EconomyManager\main.py", line 38, in open_account
    users[str(user.id)]["RS3"] = 0
KeyError: '196468210344787968'

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

Traceback (most recent call last):
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '196468210344787968'

CodePudding user response:

If user doesn't exist then you have to create dictioniary with keys "RS3" and "07"

users[str(user.id)] = {"RS3": 0, "07": 0}

instead of assigning values

users[str(user.id)]["RS3"] = 0
users[str(user.id)]["07"] = 0

EDIT:

Next problem is that you forgot user = ctx.author in wallet()

@client.command(aliases=['w'])
async def wallet(ctx):

    user = ctx.author   # <---
        
    await open_account(user)
    
    users = await get_bank_data()

    rs3_amt = users[str(user.id)]["RS3"]
    old_amt = users[str(user.id)]["07"]

    # ... rest ...

If you don't have file .json then you should use try/except when you read file

async def get_bank_data():
    try:
        with open("mainwallet.json","r") as f:
            users = json.load(f)
    except FileNotFoundError as ex:
        print('FileNotFoundError:', ex)
        users = {}
   
    return users
  • Related