0

I'm trying to create a command where a random meme is shown from a json. Unfortunately I can't do it ... I can do it using random.choice normally but since I'm a lazy person to update the code I always created a command that would allow me to add them in a json. So I have to be able to randomly extract the main key of my json. How could I do?

code:

@client.command(aliases=["Meme","MEME"])
async def meme(ctx):
    await ctx.message.delete()
    meme_data_dict = meme_data.json
    url = random.choice(list(meme_data_dict.keys))
    print(url)
    author = meme_data_dict[url]["autore"]
    title = meme_data_dict[url]["titolo"]
    channel = client.get_channel(638016878589116416)
    if ctx.channel.id == channel.id:
        embed = discord.Embed(
            title=f'{title}',
            color=0x003399
        )
        embed.set_author(name=f'fatto da {author}')
        embed.set_footer(text=f'Richiesto da {ctx.author.name}')
        embed.set_image(url=url)
        await ctx.send(embed=embed)
    else:
        embed = discord.Embed(
            color=0xa61022
        )
        embed.set_author(
            name=f"Per questo comando devi usare {channel.name}!",
        )
        await ctx.send(embed=embed, delete_after=10.0)
        return

Json (your name is meme_data.json):

{"https://cdn.discordapp.com/avatars/491769129318088714/f23fd300d377ab133db1d6ac7db5d10b.webp?size=1024": {"autore": "10", "titolo": "sesso pazzoide"}, "https://cdn.discordapp.com/attachments/638016878589116416/839977460384923659/soviet_soldier_2.jpg": {"autore": "pene", "titolo": "ciaociao"}}

This is how my json is active:

@client.event
async def on_ready():
    global meme_data
    try:
        with open('meme_data.json') as f:
            meme_data = json.load(f)
    except FileNotFoundError:
        print("Impossibile caricare meme_data.json")
        meme_data = {}

error:

Ignoring exception in command meme:
Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/PC GIUSEPPE/PycharmProjects/LMIIBot Development/LMIIBot Development.py", line 2235, in meme
    meme_data_dict = meme_data.json
AttributeError: 'dict' object has no attribute 'json'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'json'
2
  • Try renaming your variable meme to something like meme_data, because there is this function called meme. Also what exactly is your error? Commented May 6, 2021 at 19:25
  • i updated the post, my error is discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'json' Commented May 6, 2021 at 21:59

1 Answer 1

1

To get a random object of a dictionary (imported json file), you use url = random.choice(list(meme_data_dict.keys)). That in your code would be:

@client.command(aliases=["Meme","MEME"])
async def meme(ctx):
    await ctx.message.delete()
    meme_data_dict = meme_data #you have to rename your variable meme, for example to meme_data, because there is already the function called meme
    url = random.choice(list(meme_data_dict.keys()))
    print(url)
    author = meme_data_dict[url]["autore"]
    title = meme_data_dict[url]["titolo"]
    #the rest of your code can stay the same

If this doesn't answer your question, clarify more what the problem is.

Sign up to request clarification or add additional context in comments.

4 Comments

I have updated the post by clarifying (I hope) every point. I tried the code and now it gives me a different error (which I wrote in the post)
Ok, then I read your code wrong. You can simple remove .json after meme_data_dict = meme_data I updated my post now aswell @peppewarrior1
hi, I tried and now it gives me this error : 'builtin_function_or_method' object is not iterable when it comes up url = random.choice(list(meme_data_dict.keys))
My bad, there have to be () after keys @peppewarrior1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.