Time.sleep()暂停执行-Python

时间:2018-10-04 04:44:05

标签: python reddit praw

因此,我使用此repository中的代码在Python中制作了Reddit Bot。

其工作正常。但是根据Reddit指南,我只能每10分钟发表评论。所以我在这里使用for循环,代码的最后一部分是这样的:

i=1
for submission in subreddit.hot(limit=10):
    if not os.path.isfile("posts_replied_to.txt"):
        posts_replied_to = []

    # Or load the list of posts we have replied to
    else:
        with open("posts_replied_to.txt", "r") as f:
            posts_replied_to = f.read()
            posts_replied_to = posts_replied_to.split("\n")
            posts_replied_to = list(filter(None, posts_replied_to))
# Pull the hottest 10 entries from a subreddit of your choosing
    #print(submission.title)
    if(i%5!=0):
    # Make sure you didn't already reply to this post
        if submission.id not in posts_replied_to:

            # Not case sensitive
            if re.search("backpacking", submission.title, re.IGNORECASE):
                # Reply
                foo=['Awesome','Pretty nice eh!','Cool','Very beautiful','I would love to go there',\
                    'I also want to try it out now', 'Really cool', 'Can\'t wait to go there', 'Nice']
                random_index = randrange(len(foo))
                submission.reply(foo[random_index])

                print("Bot replying to : ", submission.title)

                # Store id in list
                posts_replied_to.append(submission.id)
    else:
        if submission.id not in posts_replied_to:

            # Not case sensitive
            if re.search("backpacking", submission.title, re.IGNORECASE):
                # Reply
                foo=['https://****.in']
                random_index = randrange(len(foo))
                submission.reply(foo[random_index])

                print("Bot replying to : ", submission.title)

                # Store id in list
                posts_replied_to.append(submission.id)    
    i+=1
    with open("posts_replied_to.txt", "w") as f: # Write updated list to file
        for post_id in posts_replied_to:
            f.write(post_id + "\n")
    time.sleep(600) #10 minutes delay

因此,对于背包内排名前10的subreddit,我想每10分钟发布一次,而每5条评论中我想要发布一个链接,这就是为什么我使用if (i%5)!=0

现在在这里您可以看到我最后添加了time.sleep()。当我将其注释掉时,它执行得很好,并在进行第二次注释时显示API异常错误,尝试在9分钟后发布,这是根据Reddit准则确定的。

但是当我使用time.sleep()函数时,该函数不再执行了,我已经等待了十多分钟,大约半小时,但仍然没有执行,我不知道为什么!

没有限制。每天有多少评论?我还没有找到,所以如果有人知道的话!

P.S。我的主要动机是每10分钟执行一次发布功能,如果有其他合适的功能,则不必time.sleep()。请不要建议cronjob。

0 个答案:

没有答案