首页 > 解决方案 > Python从字符串中检查json文件Python中的用户ID

问题描述

我真的不知道如何解释,所以我将解释我将要做什么。

  1. .profile <GrowID>, 插入 json 文件中的 GrowID。
  2. 如果文件中有GrowID,则打开用户数据

这是我现在拥有的

命令模板

@client.command(aliases=["p"])
async def profile(ctx, GrowID=None):
  with open('account.json', 'r') as f:
    account = json.load(f)

  if GrowID == None:
    user = ctx.author

  elif not GrowID == None:
    user = client.get_user(GrowID.user_id)

  if str(user.id) in account:
    # <Codes>

我的数据在account.json

{
    "811510359289495572": {
        "Premium": false,
        "GrowID": "Dec7h7alker",
        "Character": "Default",
        "Level": 1,
        "XP": 0,
        "XPLevel": 150,
        "Gems": 0,
        "World Locks": 0,
        "Diamond Locks": 0,
        "Growtokens": 0
    }
}

添加数据的命令

@client.command()
async def start(ctx):
        with open('account.json', 'r') as f:
          account = json.load(f)
        user = ctx.author

        if str(user.id) in account:
                await ctx.send("Your account has already existed!")

        elif str(user.id) not in account:
                account[str(user.id)] = {}
                account[str(user.id)]["Premium"] = False
                account[str(user.id)]["GrowID"] = user.name
                account[str(user.id)]["Character"] = "Default"
                account[str(user.id)]["Level"] = 1
                account[str(user.id)]["XP"] = 0
                account[str(user.id)]["XPLevel"] = 150
                account[str(user.id)]["Gems"] = 0
                account[str(user.id)]["World Locks"] = 0
                account[str(user.id)]["Diamond Locks"] = 0
                account[str(user.id)]["Growtokens"] = 0

                with open('account.json', 'w') as f:
                        json.dump(account, f, indent=4)

    # <codes (not needed cuz its just sending message)>

给你

标签: pythonjsondiscord.py

解决方案


我真的不明白问题出在哪里,因为正如评论中已经提到的,您可以使用现有代码从用户那里检索数据。

但是为此,我们首先假设GrowID取决于discord.Member,否则它将不起作用。

然后我们在此之上构建我们的命令:

@client.command(aliases=["p"])
async def profile(ctx, GrowID: discord.Member = None):
    with open('channel.json', 'r') as f:
        account = json.load(f) # Load account

        if GrowID == None:
            user = ctx.author
            await ctx.send(account[str(user.id)]) # Retrieve and send data

        else:
            user1 = client.get_user(GrowID.id) # Get the ID of the named user.
            await ctx.send(account[str(user1.id)]) # Send data of the account

然后,您将收到有关该用户的以下信息:

{'Premium': False, 'GrowID': 'Dec7h7alker', 'Character': 'Default', 'Level': 1, 'XP': 0, 'XPLevel': 150, 'Gems': 0, 'World Locks': 0, 'Diamond Locks': 0, 'Growtokens': 0}

为了使这对用户更友好,那么您需要您的知识,因为这与问题无关了。

该命令的工作原理:

在此处输入图像描述


推荐阅读