'ListingGenerator' 对象不可使用 ASYNCPRAW 迭代

'ListingGenerator' object is not iterable using ASYNCPRAW

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

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

函数如下:

    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

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

使用正常的 for 循环,您不能迭代 异步源 除非您尝试阻止事件循环,因为 for 调用 __next__ 作为阻塞函数,不等待其结果。

还有一些examples of how to iterate over the returned ListingGenerators in APRAW documentation.

参考文献: