You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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:

  1. Initialize the PRAW Reddit instance with your credentials.
  2. In the meme command, pull a pool of posts from your target subreddit.
  3. Filter out non-image posts to ensure we only send valid media.
  4. 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 to top/new for different content.
  • bot.say() is deprecated in newer Discord.py versions, so we use ctx.send() instead (which requires the ctx parameter in the command function).
  • Don't forget to install required packages: pip install discord.py praw

内容的提问来源于stack exchange,提问作者Alex Wollan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:21:13