钱不能增加不和谐的收入。py

2024-06-01 09:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我按照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,它是有意义的,我决定把它变成一个+,但是,现在它不增加收入金额。我必须改变什么?我的许多其他类似代码都有同样的问题


Tags: jsongetyoutubewith教程openawaitusers
1条回答
网友
1楼 · 发布于 2024-06-01 09:28:27

编辑:

似乎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)

相关问题 更多 >