首页 > 解决方案 > 而不是返回图像 praw 返回 r/memes/hot

问题描述

我希望我的 discord.py 机器人通过 PRAW 从 r/memes 的热门帖子中发送一个 meme。在这个问题之后,我尝试在网络和文档中搜索,但我没有找到任何查看图像的方法。这是我的代码:

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)

标签: python-3.xdiscord.pypraw

解决方案


你的代码说:

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

在这里,您将一个帖子的列表分配给submission。因为列表是一个包含一个提交而不是提交本身的可迭代(有点像列表)。与列表不同,您不能使用索引来访问特定项目,但还有其他方法可以获取它。获得提交的一种方法是

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

这使您可以更改限制并根据需要发送更多帖子。或者,您可以使用next()从帖子列表中获取下一个(也是唯一一个)项目:

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

这将始终只发送一个提交,即使您更改了limit参数。


推荐阅读