我是python的新手,我正在尝试创建一个排行榜

时间:2020-06-18 21:40:58

标签: discord.py

我想以管理员身份为特定会员的余额添加积分 了解如何使用某人的所有“要点”创建JSON文件。

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


# this line of code gives the bot a comand prefix
bot = commands.Bot(command_prefix="/")

# This line of code tells the bot to start up
@bot.event
async def on_ready():
  print("The bot is now online!")

@bot.command(pass_context=True)
async def leaderboard(ctx):
  await ctx.send("This is a work in progress, this will dieplay the leaderboard")
amounts = {}

@bot.command(pass_context=True)
async def balance(ctx):
    id = str(ctx.message.author.id)
    if id in amounts:
        await ctx.send("You have {} ben points".format(amounts[id]))
    else:
        await ctx.send("You do not have an account")

@bot.command(pass_context=True)
async def register(ctx):
    id = str(ctx.message.author.id)
    if id not in amounts.keys:
        amounts[id] = 100
        await ctx.send("You are now registered")
        _save()
    else:
        await ctx.send("You already have an account")

@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = str(ctx.message.author.id)
    other_id = str(other.id)
    if primary_id not in amounts:
        await ctx.send("You do not have an account")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await ctx.send("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await ctx.send("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

@bot.command()
async def save():
    _save()

#This line of code tells the bot to run
bot.run("Token")

我不确定从这里开始我打算做什么。

如果有人可以提高代码效率,我可能会过于复杂,我将非常感激。

1 个答案:

答案 0 :(得分:1)

这是基本用法,以及您需要了解JSON基础知识的所有内容:

# Creating a dictionary with some values
>>> data = {"foo": "bar", "key": "value"}

# Opening a file and writing to it
>>> with open("db.json", "w+") as fp:
...     json.dump(data, fp, sort_keys=True, indent=4) # Kwargs for beautification

# Loading in data from a file
>>> with open("db.json", "r") as fp:
...     data = json.load(fp)

# Accessing the values
>>> data["foo"]
'bar'
>>> data["key"]
'value'

这可以适合您的需求,例如:

# Let's say the JSON has the following structure:
# {"users": {112233445566778899: {"points": 0}, 224466881133557799: {"points": 0}}}
# The "users" key is a bit redundant if you're only gonna store users in the file.
# It's down to what you'll be storing in the file and readability etc.
import json
import random
import typing

def add_points(member_id: str, amount: int):
    # Open the file first as to load in all the users' data
    # Making a new dict would just overwrite the current file's contents
    with open("file.json", "r") as fp:
        data = json.load(fp)
    data["users"][member_id]["points"] += amount
    # Write the updated data to the file
    with open("file.json", "w+") as fp:
        json.dump(data, fp, sort_keys=True, indent=4)
    return data["users"][user_id]["points"]

@bot.command()
async def give(ctx, member: typing.Optional[discord.Member]=None, points:typing.Optional[int]=None):
    if not member:
        member = ctx.author
    if not points:
        points = random.randint(10, 50)

    # Have a separate getter for the points - this was just for the sake of concise code
    total_points = add_points(member.id, points)
    await ctx.send(f"Successfully gave {member.mention} {points} points! Total: {total_points}")

如有需要,我很乐意澄清。


参考: