Legend1989 Legend1989 - 1 month ago 14
Python Question

Why is my code not compiling

I am just learning Python and decided to write a really simple Python bot to reply on Reddit.

On compiling I am getting the following error:


File "C:\Python35\Scripts\RedditBot\Reddit.py", line 28
except attributeerror:
^ SyntaxError: invalid syntax


I am unable to see what is causing this as the code looks correct to me.

import praw

USERAGENT = "BOT Name"
USERNAME = "Username"
PASSWORD = "Password"
SUBREDDIT = "Subreddit"
MAXPOSTS = 100

SETPHRASES = ["Phrase", "PhraseOne"]
SETRESPONSE = "This is the response."

print('Logging in to Reddit')
r = praw.Reddit(USERAGENT)
r.login (USERNAME, PASSWORD)

def replybot():
print('Fetching Subreddit ' + SUBREDDIT)
subreddit = r.get_subreddit(SUBREDDIT)
print('Fetching comments')
comments = subreddit.get_comments(limit=MAXPOSTS)
for comment in comments:
try:
cauthor = comment.author.name
cbody = comment.body.lower()
if any(key.lower() in cbody for key in SETPHRASES):
print("Replying to " + cauthor)
comment.reply(SETRESPONSE)
except attributeerror:
pass
replybot()

Answer

You are having two problems.

  • First one, which is displayed in traceback, is the indentation. "try" and "except" must be on the same level of indentation.
  • Second one is the reference to attributeerror. It need's to be camelcased as in AttributeError.

So the inside of your for loop should look as follows:

try:
   cauthor = comment.author.name
   cbody = comment.body.lower()
   if any(key.lower() in cbody for key in SETPHRASES):
      print("Replying to " + cauthor)
      comment.reply(SETRESPONSE)
except AttributeError:
   pass
Comments