(discord.py) Get user's, last message from a JSON file without specifying the name/id

I have an users.json file which store the user's id and lmessage (current date,time) if he is write in a room.

{"5314934047066510132": {"lmessage": "2021-04-21 10:21:01"}}

How can I get all of these IDs and the lmessages which belongs to that ID without specify username or anything?

Currently I can get the user's lmessage with a command if I specify the username:

@client.command()
async def lastmess(ctx, member: discord.Member = None):
    id = member.id
    with open('users.json', 'r') as f:
        users = json.load(f)
    lastmessage = users[str(id)]['lmessage']
    await ctx.send(f'{member} Last message: {lastmessage}!')

2 answers

  • answered 2021-04-21 14:14 Jacob Lee

    If I understand your question correctly, you just want to iterate through all of the key-value pairs in the JSON data. If so, you can use the various dictionary methods available:

    with open("users.json") as file:
        data = json.load(file)
    
    # Get all keys (user IDs)
    user_ids = list(data.keys())   # OR list(data)
    
    # Get all values (last message dictionary)
    last_messages = list(data.values())
    
    # Get all keys and values tuples
    ids_and_last_messages = list(data.items())
    
    # Get all last message dates
    last_message_dates = [uid["lmessage"] for uid in data.values()]
    

  • answered 2021-04-21 14:16 HichamDz38

    i dont know how you would like to output the result, but this is how to can get all the IDs without specify the user and you can edit that to output or display the result as you want

    @client.command()
    async def lastmess(ctx, member: discord.Member = None):
      id = member.id
      with open('users.json', 'r') as f:
        users = json.load(f)
      for user in users:
        print(user, user['lmessage'])  # here you can print all the IDS/lmessage
      lastmessage = users[str(id)]['lmessage']
      await ctx.send(f'{member} Last message: {lastmessage}!')