Advertisement
Guest User

Untitled

a guest
May 27th, 2015
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1.  
  2. import praw
  3. import sys
  4. import os
  5. from time import gmtime, strftime
  6. try:
  7.     from flair_list import flairs
  8. except ImportError as e:
  9.     print("Flairs file can't be accessed\n")
  10.     print(e)
  11.     sys.exit()
  12. except SyntaxError as e:
  13.     print("There is a syntax error in the flair list\n")
  14.     print(e)
  15.     sys.exit()
  16.  
  17.  
  18. class FlairBot:
  19.  
  20.     USER_AGENT = 'FlairBot'
  21.     USER_NAME = ''
  22.     PASSWD = ''
  23.     SUBJECT = 'flair'
  24.     TARGET_SUB = ''
  25.     LOGGING = True
  26.  
  27.     # Class variable to hold the PRAW instance
  28.     r = None
  29.  
  30.     # Class variable to hold the unread pms
  31.     pms = None
  32.  
  33.     def init(self):
  34.         if self.LOGGING:
  35.             os.chdir(os.path.dirname(os.path.abspath(__file__)))
  36.         self.login()
  37.  
  38.     def login(self):
  39.         """ Log in to the account being used for the bot """
  40.         try:
  41.             self.r = praw.Reddit(user_agent=self.USER_AGENT)
  42.             self.r.login(self.USER_NAME, self.PASSWD)
  43.             self.fetch_pms()
  44.         except:
  45.             raise
  46.  
  47.     def fetch_pms(self):
  48.         """ Get a listing of all unread PMs for the user account """
  49.         self.pms = self.r.get_unread(limit=None)
  50.         if self.pms is not None:
  51.             self.process_pms()
  52.  
  53.     def process_pms(self):
  54.         for pm in self.pms:
  55.             if str(pm.subject) == self.SUBJECT:
  56.                 author = str(pm.author)  # Author of the PM
  57.                 content = str(pm.body)  # Content of the PM
  58.                 subreddit = self.r.get_subreddit(self.TARGET_SUB)
  59.                 if content in flairs:
  60.                     # Get the flair text that corresponds with the class name
  61.                     flair_text = str(flairs[content])
  62.                     subreddit.set_flair(author, flair_text, content)
  63.                     if self.LOGGING:
  64.                         self.log(author, content, flair_text)
  65.                 pm.mark_as_read()  # Mark processed PM as read
  66.  
  67.     def log(self, author, content, flair_text):
  68.         with open('log.txt', 'a') as logfile:
  69.             time_now = strftime("%Y-%m-%d %H:%M:%S", gmtime())
  70.             log_text = 'Added: ' + author + ' : ' \
  71.                         + flair_text + ' : ' \
  72.                         + content + ' @ ' + time_now + '\n'
  73.             logfile.write(log_text)
  74.  
  75. FlairBot().init()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement