繁体   English   中英

"如何在 Python 中为我的不和谐机器人制作购买功能?"

[英]How do I make the buy function for my discord bot in Python?

我正在制作一个不和谐的机器人,它有一个可以购买商品的商店,但是 update_bank 功能存在问题。

当我运行我的代码时,我收到一个控制台错误,提示未定义 update_bank。 我知道如何定义一个函数,但我不确定如何让这个函数更改 .json 中玩家的银行数据。

我的代码是:

from discord.ext import commands
import json
import os 

os.chdir("C:\\users\\CENSORED\\Desktop\\PTFS BOT")

client = commands.Bot(command_prefix="$")

# shop for planes

mainshop = [{"name":"A320","price":400,"description":"test description"},
            {"name":"A330","price":500,"description":"an a330"}]

@client.event
async def on_ready():
    print("Bot Online")

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"] = 40000
        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(aliases = ["bal"])
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 shop(ctx):
    em = discord.Embed(title = "Dealership")

    for item in mainshop:
        name = item["name"]
        price = item["price"]
        desc = item["description"]
        em.add_field(name = name, value = f"${price} | {desc}")

    await ctx.send(embed =em)


@client.command()
async def buy(ctx,item_name,amount = 1):
    await open_account(ctx.author)

    res = await buy_this(ctx.author,item_name,amount)

    if not res[0]:
        if res[1]==1:
            await ctx.send("That item does not exist!")
            return
        if res[1]==2:
            await ctx.send(f"You do not have enough money!")
            return


    await ctx.send(f"you just bought {amount} {item}")

async def buy_this(user,item_name,amount):
    item_name = item_name.lower()
    name_ = None
    for item in mainshop:
        name = item["name"].lower()
        if name == item_name:
            name_ = name
            price = item["price"]
            break

    if name_ ==None:
        return [False,0]

    cost = price*amount

    users = await get_bank_data()

    bal = await update_bank(user)

    if bal[0]<cost:
        return [False,0]


    try:
        index = 0
        t = None
        for thing in users[str(user.id)]["bag"]:
            n = thing["item"]
            if n == item_name:
                old_amt = thing["amount"]
                new_amt = old_amt + amount
                users[str(user.id)]["bag"][index]["amount"] = new_amt
                t = 1
                break
            index+=1
        if t == None:
            obj = {"item":item_name , "amount" : amount}
            users[str(user.id)]["bag"].append(obj)
    except:
        obj = {"item":item_name , "amount" : amount}
        users[str(user.id)]["bag"] =[obj]

    with open("bank.json",'w') as f:
        json.dump(users,f)

    await update_bank(user,cost*-1,"Wallet")

    return [True,1]


@client.command()
async def bag(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()
    try:
        bag = users[str(user.id)]["bag"]
    except:
        bag = []


    em = discord.Embed(title = "bag")
    for item in bag:
        name = item["item"]
        amount =item["amount"]

        em.add_field(name = name, value = amount)

    await ctx.send(embed = em)






@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
    users = await get_bank_data()
    leader_board = {}
    total = []
    for user in users:
        name = int(user)
        total_amount = users[user]["Wallet"] + users[user]["Bank"]
        leader_board[total_amount] = name
        total.append(total_amount)

    total = sorted(total,reverse=True)    

    em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = discord.Color(0xfa43ee))
    index = 1
    for amt in total:
        id_ = leader_board[amt]
        member = await client.fetch_user(id_)
        name = member.name
        em.add_field(name = f"{index}. {name}" , value = f"{amt}",  inline = False)
        if index == x:
            break
        else:
            index += 1

    await ctx.send(embed = em)


client.run("CENSORED")

您只需打开 json 文件并更新银行余额并将购买的商品添加到用户的库存中即可。

async def update_bank(item):
    with open("your.json") as db:
        data = json.loads(db)

    item_price = await data["cost"]["item"]
    data["userid"]["bank_bal"] -= item_price
    data["userid"]["inventory"].append("item")

    with open("your.json", "w") as db:
        db.write(json.dumps(data))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM