无法使用 PRAW 从某些 subreddits 中随机获得 post

Unable to get a random post from some subreddits with PRAW

我正在尝试使用此代码让一个 disord 机器人从 reddit 发送图像(只是为了抓取而不是发送)

def random_post(subreddit):
while True:
    post = reddit.subreddit(subreddit).random()
    if not post.stickied:
        return post

它通常工作正常,但偶尔我会收到此错误

AttributeError: 'NoneType' object has no attribute 'stickied'

它只发生在某些 subreddits 上。

这是 Reddit 端的一个已知问题。

一些 subreddits 会拒绝给你一个随机提交。请参阅 GitHub 上的 praw-dev/praw#885

关于那个问题,我went in depth about the cause. My findings were: When a subreddit's moderators uncheck the "allow this subreddit to be exposed to users in /r/all, /r/popular, default, and trending lists" checkbox in their subreddit settings, it prevents the subreddit from being able to provide a random submission. For example, at the time of this writing, https://reddit.com/r/wallpapers/random just redirects to https://www.reddit.com/r/wallpapers/而不是提交一些。

在我个人看来,这是一个 Reddit 错误,由 /r/random(重定向到随机 subreddit)和 /r/{subreddit}/random(重定向到 subreddit 中的随机提交)之间的混淆引起。就目前而言,该复选框会影响这两个设置,而在我看来,它只影响 /r/random.

才有意义

在同一个 GitHub 问题中,一位 Reddit 开发人员插话确认 "the two behaviors are connected" and said that this behavior "isn't a bug per se." 那是两年多以前的事了,自那以后 Reddit 端没有任何变化。


那么这对你意味着什么?

不幸的是,没有解决这个问题的好方法。正如您所发现的,对于某些 subreddits,subreddit.random() returns None。这是 noted in the documentation of the method. In your code, you should check that post is not None. In the case that it is None, it's up to you how to handle that. You could just return None, or perhaps you could use an alternate method to get a random submission, such as (for instance) getting 25 submissions from the hot listing and using random.choice() 到 select 之一。