【问题标题】:Reddit bot only fetches new posts when run, but doesnt actively fetch posts that are made while bot is already runningReddit bot 仅在运行时获取新帖子,但不会主动获取在 bot 已经运行时发布的帖子
【发布时间】:2019-02-02 12:10:12
【问题描述】:

不久前我开始使用 python,我为 Reddit 制作了一个简单的机器人。不幸的是,该机器人的功能仅适用于在该机器人在终端中运行之前发布的帖子。如果在机器人运行后向 subreddit 发布帖子,机器人不会评论或获取这些帖子。

另一件可能相关的事情是控制台输出“目前没有适用的帖子”。两次而不是一次。我不确定这是否相关。

这是我认为对此问题重要的代码,如果您需要更多上下文,请告诉我!:

def mainloop():
    counter1 = 0  # Counts submissions in new that have been crawled
    for submission in subreddit.new(limit=5):  # Get the 5 newest submissions
        counter1 = counter1 + 1

        callings = ['canada', 'canadian', '????????']  # Triggers
        normalized_title = submission.title.lower()
        normalized_text = submission.selftext.lower()

        while True:
            if submission.id not in posts_replied_to:  # If the post is new to the bot
                time.sleep(30)  # Keep spam low
                for canadian_mentions in callings:
                    if canadian_mentions in normalized_title:  # If trigger is in title
                        # Make the reply, print to console, then add the post to the replied storage
                        submission.reply(reply_text)
                        print("Bot replying to : ", submission.title, "\n")
                        posts_replied_to.append(submission.id)
                    elif canadian_mentions in normalized_text:  # If trigger is in text body
                        # Make the reply, print to console, then add the post to the replied storage
                        submission.reply(reply_text)
                        print("Bot replying to : ", submission.selftext, "\n")
                        posts_replied_to.append(submission.id)
                    else:
                        print("No applicable posts right now.")

【问题讨论】:

  • 你有一个无限循环while True:检查新帖子后:for submission in subreddit.new(limit=5):你进入无限循环后将永远不会再有新帖子。你需要重新排列你的代码。
  • 非常感谢,问题是这个,以及另一件事。删除 while 循环并没有改变它没有获得新帖子的事实,但它是问题的一半。我打印新帖子的代码没有else: 语句,并且程序在该语句处处于空闲状态。如果我解决了这个问题并离开了while True 循环,它仍然会有同样的问题!谢谢!

标签: python python-3.x bots reddit praw


【解决方案1】:

您可以使用stream 对象。

for post in reddit.subreddit(subreddit).stream.submissions(skip_existing=True):
    # Do stuff
    print(post.selftext)

这将在发布帖子时实时打印帖子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2020-08-11
    • 2017-08-01
    • 1970-01-01
    • 2020-02-17
    • 2013-05-14
    • 2020-11-08
    相关资源
    最近更新 更多