如何为discord.py机器人实现随机Subreddit图片发送功能?
Solution for Fetching Random Subreddit Images in Your Discord Bot
Hey there! Let's get that meme command up and running smoothly. Here's how to implement the random image fetch using PRAW, with fixes for outdated Discord.py syntax and proper Reddit API integration:
First, make sure you've created a Reddit developer app (head to Reddit's settings under "Apps" to set this up) to get your client_id, client_secret, and define a user_agent (something like "Discord Meme Bot by /u/yourredditusername").
Then, update your code with these key steps:
- Initialize the PRAW Reddit instance with your credentials.
- In the
memecommand, pull a pool of posts from your target subreddit. - Filter out non-image posts to ensure we only send valid media.
- Send the random image URL to the Discord channel.
Here's the complete, updated code:
import discord import praw from discord.ext import commands import random # Set up PRAW with your Reddit app credentials reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_agent="YOUR_USER_AGENT" # Example: "DiscordMemeBot/1.0 by u/YourRedditHandle" ) bot = commands.Bot(description="test", command_prefix="!") @bot.command() async def meme(ctx): # Target subreddit - change this to any sub you want subreddit = reddit.subreddit("memes") # Grab 50 hot posts to pick from (adjust limit or use 'top'/'new' if preferred) hot_posts = list(subreddit.hot(limit=50)) # Filter to only keep image posts (skip text, links, etc.) image_posts = [ post for post in hot_posts if post.url.endswith(('.png', '.jpg', '.jpeg', '.gif', '.gifv')) ] # Pick a random image post and send it if image_posts: random_post = random.choice(image_posts) await ctx.send(random_post.url) else: await ctx.send("Oops, couldn't find any images right now!") # Run the bot with your Discord token bot.run("YOUR_DISCORD_BOT_TOKEN")
Quick Notes:
- Replace all placeholder values (
YOUR_CLIENT_ID, etc.) with your actual credentials. - Using
hot(limit=50)gives you a pool of recent popular posts—tweak the limit or switch totop/newfor different content. bot.say()is deprecated in newer Discord.py versions, so we usectx.send()instead (which requires thectxparameter in the command function).- Don't forget to install required packages:
pip install discord.py praw
内容的提问来源于stack exchange,提问作者Alex Wollan
相关产品推荐
相关产品推荐

