【问题标题】:instead of returning an image praw returns r/memes/hot而不是返回图像 praw 返回 r/memes/hot
【发布时间】:2020-06-16 19:46:07
【问题描述】:

我希望我的 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)

【问题讨论】:

  • 有人可以删除客户端 ID 和密码吗?

标签: python-3.x discord.py praw


【解决方案1】:

你的代码说:

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 参数,这也将始终只发送一个提交。

【讨论】:

    【解决方案2】:

    PRAW 是阻塞的,aiohttp 不是,坦率地说,discord.py 带有 aiohttp。 Reddit 提供了一个端点来返回 json 数据,您可以使用 json.loads() 方法来获取原始 json。 这是我写的从 subreddits 获取图像的东西

    from aiohttp import ClientSession
    from random import choice as c
    from json import loads
    
    async def get(session: object, url: object) -> object:
        async with session.get(url) as response:
            return await response.text()
    
    
    async def reddit(sub: str):
        type = ['new', 'top', 'hot', 'rising']
        url = f"https://www.reddit.com/r/{sub}/{c(type)}.json?sort={c(type)}&limit=10"
        async with ClientSession() as session:
            data = await get(session, url)
            data = loads(data)
            data = data['data']['children']
            url = [d['data']['url'] for d in data]
            return c(url)
    

    您只需await reddit(sub= 'memes') 即可获取所需的网址。

    【讨论】:

    • 这似乎没有解决 OP 的问题。这可能是关于异步编程的好建议,但这不是问题所在。但是,我并不完全清楚这个问题首先要问什么。
    猜你喜欢
    • 2013-08-15
    • 2013-11-14
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多