mercredi 23 mars 2022

Discord.py - random post from subreddit using asyncpraw

I need to display a 1 random submission from the most 100 hot reddit submissions after entering the command. This is my code without randomness, it's just send me 100 posts:

@bot.command()
async def picture(ctx, name):
    picture_submission = await reddit.subreddit("Genshin_Impact")
    post_to_pick = random.randint(1, 100)
    async for submission in picture_submission.search(f"{name}", params={'include_over_18': 'on'}, limit=100):
        url = submission.url
        title = submission.title
        embed = discord.Embed(title=f'__{title}__', colour=discord.Colour.light_gray(),
                              timestamp=ctx.message.created_at, url=url)
        embed.set_image(url=url)

        await ctx.send(embed=embed)

I've tried random.choice(), but it didn't worked:

    async for submission in picture_submission.search(f"{name}", params={'include_over_18': 'on'}, limit=100):
        random.choice(submission)
    url = submission.url
    title = submission.title
    embed = discord.Embed(title=f'__{title}__', colour=discord.Colour.light_gray(),
                              timestamp=ctx.message.created_at, url=url)
    embed.set_image(url=url)
    await ctx.send(embed=embed)

Error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Submission' has no len()

Before I moved from PRAW to AsyncPRAW I've used this and it worked fine:

@bot.command()
async def picture(ctx, name):
    picture_submission = reddit.subreddit("Genshin_Impact").search(f"{name}", sort="hot", params={'include_over_18': 'on'})
    post_to_pick = random.randint(1, 100)
    for i in range(0, post_to_pick):
        submission = next(x for x in picture_submission if not x.stickied)
    url = submission.url
    title = submission.title
    embed = discord.Embed(title=f'__{title}__', colour=discord.Colour.light_gray(), timestamp=ctx.message.created_at, url=url)
    embed.set_image(url=url)

    await ctx.send(embed=embed)



Aucun commentaire:

Enregistrer un commentaire