【问题标题】:'ListingGenerator' object is not iterable using ASYNCPRAW'ListingGenerator' 对象不可使用 ASYNCPRAW 进行迭代
【发布时间】:2021-05-15 14:27:39
【问题描述】:

我想从 subreddit 中获取模因。问题是当我尝试使用 subreddit('memes') 方法获取模因时,该方法返回一个不可迭代的“ListingGenerator”对象。

我想知道是否有任何方法可以将其转换为可迭代对象或任何其他方法来使用 ASYNCPRAW 从 reddit 获取 meme。

函数如下:

    async def meme(self, ctx):
    subreddit = await  reddit.subreddit('memes')
    print(type(subreddit))
    all_subs = []
    print(subreddit.hot(limit=50))
    for submission in subreddit.hot(limit=50):
        all_subs.append(submission)
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    embed = discord.Embed(title=name)
    embed.set_image(url=url)
    await ctx.send(embed=embed)

这是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\ansel\PycharmProjects\Transfer News\cogs\meme.py", line 48, in meme
    for submission in subreddit.hot(limit=50):
TypeError: 'ListingGenerator' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'ListingGenerator' object is not iterable

【问题讨论】:

    标签: python discord.py reddit praw


    【解决方案1】:

    在您的meme 命令中,您正在使用for 循环来迭代返回的ListingGenerator,这是一个异步源。在这种情况下,您将需要使用async for 循环来迭代异步源

    使用普通的for 循环,除非您尝试阻塞事件循环,否则不允许迭代异步源,因为for 调用__next__ 作为阻塞函数并且不会等待结果。

    有一些examples 介绍了如何在APRAW documentation 中迭代返回的ListingGenerators

    参考资料:

    【讨论】:

    • 是的,感谢您指出这一点。另一件事是,在添加async 之后它仍然有一个错误,所以我不得不在函数asyncpraw.Reddit() 中传递usernamepassword 变量(即使在文档中另有说明)。
    猜你喜欢
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多