0
votes

I started with python a little while ago, and I made a simple bot for Reddit. Unfortunately, the functionality of the bot only works on posts that are made before the bot is run in terminal. If a post is made to the subreddit after the bot has been run, the bot does not comment on or fetch these posts.

One other thing that may be related is that the console outputs "No applicable posts right now." twice instead of once. I'm not sure if that is related.

Here is the code I think is import for this issue, if you need more context let me know!:

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.")
1
You have an infinite loop while True: after the check for new posts: for submission in subreddit.new(limit=5): You will never get new posts again after you enter the infinite loop. You need to rearrange your code.abc
thanks so much, the issue was this, as well as another thing. Removing the while loop did not change the fact that it wasn't getting new posts, but it was half the problem. My code for printing new posts did not have an else: statement, and the program was sitting idle at that statement. if i had fixed that and left the while True loop as well, it would have still had the same issue! thanks!Bryn

1 Answers

0
votes

You could use a stream object.

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

This will print posts in realtime as they are made.