Alex Wollan
Alex Wollan

Reputation: 55

How do I get a random subreddit image to my discord.py bot?

I am making a discord bot in async python. I want the bot to post a random picture when I do a command (prefix !) example !meme. This would bring up a random picture from a subreddit, in this case the memes subreddit. I have made the start to what I want, but I need help with the random subreddit bit.

import discord
import praw
from discord.ext import commands

bot = commands.Bot(description="test", command_prefix="!")

@bot.command()
async def meme():
    await bot.say(---)   
    #--- WOULD BE THE REDDIT URL
    bot.run("TOKEN")

How would I do this, using discord.py and PRAW?

Upvotes: 0

Views: 16219

Answers (2)

ZambieD
ZambieD

Reputation: 11

@client.command(aliases=['Meme'])
async def meme(ctx):
    reddit = praw.Reddit(client_id='XXXX',
                        client_secret='XXXX',
                        user_agent='XXXX')

    submission = reddit.subreddit("memes").random()
    await ctx.send(submission.url)

Upvotes: -1

Benjin
Benjin

Reputation: 3497

The below code will fetch a random post from the memes subreddit. Currently it picks a random submission from the top 10 posts from the hot section.

import praw
import random
from discord.ext import commands

bot = commands.Bot(description="test", command_prefix="!")

reddit = praw.Reddit(client_id='CLIENT_ID HERE',
                     client_secret='CLIENT_SECRET HERE',
                     user_agent='USER_AGENT HERE')

@bot.command()
async def meme():
    memes_submissions = reddit.subreddit('memes').hot()
    post_to_pick = random.randint(1, 10)
    for i in range(0, post_to_pick):
        submission = next(x for x in memes_submissions if not x.stickied)

    await bot.say(submission.url)

bot.run('TOKEN')

Upvotes: 2

Related Questions