Search code examples
pythonpython-3.xpraw

Praw script throws an error


import praw
import time

r = praw.Reddit(user_agent = "A bot by /u/")

r.login()
print("Logging in...")

cache = []

def run_bot():
    print("Grabbing subreddit...")
    subreddit = r.get_subreddit("test").get_new(limit=1)
    print("The subreddit selected was /r/Test")
    subreddit.add_comment('Cat.')

while True:
    run_bot()
    time.sleep(10)

I'm trying to make a bot that comments on new submissions with the phrase Cat., but I'm getting this error:

Traceback (most recent call last):
  File "C:\Users\Julian\Desktop\bot.py", line 19, in <module>
    run_bot()
  File "C:\Users\Julian\Desktop\bot.py", line 15, in run_bot
    subreddit.add_comment('Cat.')
AttributeError: 'generator' object has no attribute 'add_comment'

Solution

  • subredit 
    

    is a generator. That means you have to iterate over its results. By using a for loop you can access its results like this:

    for x in subreddit:
        x.add_comment('Cat.')