所以我遵循了这个 youtube 教程,并做到了这一点"
@client.command()
@commands.cooldown(1, 6.0, commands.BucketType.user)
async def work(ctx):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
earnings = random.randrange(1000)
await ctx.send(f"You worked on cleaning a toilet, got yourself covered with toilet water and poo, but you managed to get $ `{earnings}`")
wallet_amount = users[str(user.id)]["Wallet"] + earnings
with open("bank.json", "w") as f:
json.dump(users,f)
这曾经有一个 "+="
,但它不起作用,我的朋友说它会像 x = a + x
,这是有道理的,我决定把它变成一个 +
,但是,现在它不会添加收入金额。我需要改变什么?我的很多其他类似的代码都有同样的问题。
答案 0 :(得分:2)
编辑:
似乎 json
将字典中的整数键作为字符串保留,所以我不得不将 str()
放回 users[str(user.id)]
我无法测试您的代码,但它应该只需要
users[str(user.id)]["Wallet"] += earnings
但是这个user.id
在users
中可能不存在所以你应该检查它并使用0
创建钱包
if user.id not in users:
users[str(user.id)] = {"Wallet": 0}
users[str(user.id)]["Wallet"] += earnings
编辑:
问题也是您在 get_bank_data()
中所做的,因为它会为 users = ...
赋值,并且它可能会替换数据并且可能会删除新值。
编辑:
使用命令 !work
和 !wallet
的最小工作示例。
如果它在开始时找不到 bank.json
则创建它。
import os
import random
import json
import discord
from discord.ext import commands, tasks
TOKEN = os.getenv('DISCORD_TOKEN')
client = commands.Bot(command_prefix="!")
@client.event
async def on_connect():
print("Connected as", client.user.name)
@client.event
async def on_ready():
print("Ready as", client.user.name)
async def get_bank_data():
with open("bank.json", "r") as f:
users = json.load(f)
return users
@client.command()
@commands.cooldown(1, 6.0, commands.BucketType.user)
async def work(ctx):
#user = ctx.author
user_id = str(ctx.author.id)
users = await get_bank_data()
earnings = random.randrange(1000)
await ctx.send(f"You worked on cleaning a toilet, got yourself covered with toilet water and poo, but you managed to get $ `{earnings}`")
if user_id not in users:
print('[work] Create wallet for:', user_id)
users[user_id] = {"Wallet": 0}
users[user_id]["Wallet"] += earnings
with open("bank.json", "w") as f:
json.dump(users, f)
@client.command()
async def wallet(ctx):
#user = ctx.author
user_id = str(ctx.author.id)
users = await get_bank_data()
if user_id not in users:
await ctx.send("You don't have wallet. Try !work")
else:
wallet_amount = users[user_id]["Wallet"]
await ctx.send(f"You have $ {wallet_amount} in wallet")
# --- start ---
if not os.path.exists( "bank.json"):
print("[START] Create empty 'bank.json'")
users = dict()
with open("bank.json", "w") as f:
json.dump(users, f)
client.run(TOKEN)