Search code examples
python-3.xdiscord.pypraw

instead of returning an image praw returns r/memes/hot


I want my discord.py bot to send a meme from hot posts of r/memes via PRAW. After this issue, I tried searching in the web and in the documentations, but I didn't find any method to view the image. Here is my code:

import praw
import discord
from discord.ext import commands
from discord import client



reddit = praw.Reddit(client_id="d",
                     client_secret="d",
                     user_agent="automoderatoredj by /u/taskuratik")

#boot

print("il bot si sta avviando... ")
token = "token"
client = commands.Bot(command_prefix=("/"))

#bot online

@client.event

async def on_ready():
    print("il bot e' ora online")



@client.command()
async def meme(submission):
        if reddit:
            channel = client.get_channel(722491234991472742)
            submission = reddit.subreddit("memes").hot(limit=1)
            await channel.send(submission.url)

client.run(token)

Solution

  • Your code says:

    submission = reddit.subreddit("memes").hot(limit=1)
    await channel.send(submission.url)
    

    Here, you assign a listing of one post to submission. As listing is an iterable (somewhat like a list) that contains one submission, rather than the submission itself. Unlike a list, you can't use an index to access a specific item, but there are other ways to get it. One way to get the submission is

    for submission in reddit.subreddit("memes").hot(limit=1):
        await channel.send(submission.url)
    

    This allows you to change the limit and send more posts if you want. Or, you could use next() to get the next (and only) item from the post listing:

    submission = next(reddit.subreddit("memes").hot(limit=1))
    await channel.send(submission.url)
    

    This will always send just one submission, even if you change the limit parameter.