Skip to content
Advertisement

(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}!')

Advertisement

Answer

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()]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement