我的代码:
@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.teal())
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
with open("bank.json",'w') as f:
users = json.dump(users,f)
return True
async def get_bank_data():
with open("bank.json",'r') as f:
users = json.load(f)
return users
@client.command()
async def beg(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
earnings = random.randrange(101)
await ctx.send(f"Someone gave your {earnings} coins")
users[str(user.id)]["Wallet"] += earnings
with open("bank.json",'r') as f:
users = json.dump(users,f)
错误:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
所以我正在为我的不和谐机器人制作一个经济系统,并遇到了这个错误。我真的不知道如何解决这个问题,而做一些事情只会导致更多的错误。如果有人能改正,并可能解释我哪里出错了,那就太好了。
答案 0 :(得分:1)
您提供的代码在某些地方完全没有意义,例如:
users = json.dump(users,f)
users
不再使用,对代码没有影响。
此外,您的 beg
命令包含一个逻辑错误。您尝试同时读取 JSON (r
) 和 dump
,然后出现无法写入 JSON 文件的错误。
为了解决所有这些问题,我们使用以下代码:
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("bank.json", 'w') as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("bank.json", 'r') as f:
users = json.load(f)
return 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.teal())
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)
user = ctx.author
users = await get_bank_data()
earnings = random.randrange(101)
await ctx.send(f"Someone gave your {earnings} coins")
users[str(user.id)]["Wallet"] += earnings
with open("bank.json", 'w') as f:
json.dump(users, f)
答案 1 :(得分:1)
它只是 { } 写这个它有效 这是因为 json 将文件存储为字典 并在 beg 命令中使用这一行 with open("bank.json", 'r') as f: 用户 = json.dump(users, f) 将 R(读取模式)更改为 W(写入模式) 这就是存储你有多少硬币