Advertisement
CrashARuntimeToday

VirtueTron9000 v0.2.6

Jun 30th, 2018
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.49 KB | None | 0 0
  1. #!/usr/bin/python
  2. LICENCE = "WTFPL", "http://www.wtfpl.net/about/"
  3. VERSION = "v0.2.6"
  4.  
  5. import logging
  6. import pickle
  7. import praw
  8. import prawcore
  9. import sys
  10. from datetime import datetime, timedelta
  11. from math import ceil
  12. from time import sleep
  13. from random import randint
  14.  
  15. log = logging.getLogger("VirtueTron")
  16. log.setLevel(logging.DEBUG)
  17. formatter = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y/%m/%d %I:%M:%S%p")
  18. file_log = logging.FileHandler(filename="VirtueTron.log", mode="a")
  19. file_log.setLevel(logging.INFO)
  20. file_log.setFormatter(formatter)
  21. log.addHandler(file_log)
  22. console_log = logging.StreamHandler(stream=sys.stdout)
  23. console_log.setLevel(logging.DEBUG)
  24. console_log.setFormatter(formatter)
  25. log.addHandler(console_log)
  26.  
  27. log.info("Hello, Reddit!")
  28. log.info("VirtueTron® 9000™ {0} © CrashARuntimeToday@outlook.com".format(VERSION))
  29.  
  30. credentials = pickle.load(open("credentials.pickle", "rb")) # {client_id:"VirtueTron9000", client_secret:"🤖🤡🍆💯™", username:"SignalAVirtueToday", password:"https://youtu.be/RCVJ7bujnSc"}
  31. credentials["user_agent"] = "VirtueTron 9000 {0}".format(VERSION)
  32. reddit = praw.Reddit(**credentials)
  33. tbp = reddit.subreddit("TheBluePill")
  34.  
  35.  
  36. class Tracker:
  37.     def __init__(self, name, good_karma, bad_karma):
  38.         self.name = name
  39.         self.smv = None
  40.         self.scan_count = 0
  41.         self.next_refresh = None
  42.         self.update(good_karma, bad_karma)
  43.         self.is_approved = False
  44.         self.is_purged = False
  45.         self.warned = False
  46.         self.warned_on = None
  47.         self.comments_eaten = []
  48.    
  49.     def update(self, good_karma, bad_karma):
  50.         self.good_karma = good_karma
  51.         self.bad_karma = bad_karma
  52.         self.scan_count += 1
  53.         self.next_refresh = datetime.now() + timedelta(minutes=15)
  54.  
  55.  
  56. delay = 2
  57. def praw_fucked_up():
  58.     global delay
  59.     log.warning("Reddit API errored: waiting {0} seconds".format(delay))
  60.     if delay > 128: delay = 2
  61.     sleep(delay)
  62.     delay *= 2
  63.  
  64. NICE_LIST = []
  65. NAUGHTY_LIST = "TheRedPill", "MarriedRedPill", "ChristianRedPill", "MGTOW", "Braincels", "AskTRP", "AskMRP", "RedPillWomen", "RedPillWives", "CringeAnarchy", "The_Donald", "RPChristians", "PussyPassDenied", "MensRights"
  66. def calc_score(name):
  67.     good_karma, bad_karma, good_count, bad_count = 0, 0, 0, 0
  68.    
  69.     for comment in reddit.redditor(name).comments.new(limit=100):
  70.         sub = comment.subreddit.display_name
  71.         karma = comment.score
  72.         if sub == "TheBluePill":
  73.             good_karma += karma - 1
  74.             good_count += 1
  75.         elif sub in NICE_LIST:
  76.             good_karma += (karma - 1) / 2
  77.         elif sub in NAUGHTY_LIST and karma > 1:
  78.             bad_karma -= karma - 1
  79.             bad_count += 1
  80.    
  81.     if good_count > 0:
  82.         good_karma /= good_count
  83.    
  84.     if bad_count > 0:
  85.         bad_karma /= bad_count
  86.         if bad_count > 5 and not any(tbp.banned(redditor=name)):
  87.             log.info("User: {0} is vexatious ({1} posts in NAUGHTY_LIST)".format(name, bad_count))
  88.             tbp.flair.set(name, "VEXATIOUS LITIGANT", "vexatious")
  89.  
  90.     log.info("Scanned user: {0}, good_karma: {1} ({2} comments), bad_karma: {3} ({4} comments)".format(name, good_karma, good_count, bad_karma, bad_count))
  91.     return good_karma, bad_karma
  92.  
  93. IMMUTABLE_FLAIRS = "vanguard", "vexatious", "endorsedflair", "alpha", "betaasfuck", "feeemale", "purged"
  94. def update_flairs():
  95.     log.info("Recalculating SMV")
  96.     i = 0
  97.     total = len(users)
  98.     for user in sorted(users.values(), key=lambda x: x.good_karma + x.bad_karma):
  99.         i += 1
  100.         user.smv = ceil((i / total) * 10)
  101.         current_flair = None
  102.        
  103.         # Not sure why Reddit doesn't like this bit and too lazy to run Wireshark
  104.         try:      
  105.             for flair in tbp.flair(redditor=user.name):
  106.                 current_flair = flair["flair_css_class"]
  107.         except prawcore.PrawcoreException:
  108.             praw_fucked_up()
  109.             pass
  110.  
  111.         if not user.is_purged and any(tbp.banned(redditor=user.name)):
  112.             if current_flair != "purged":
  113.                 log.info("Marking user: {0} purged".format(user.name))
  114.                 tbp.flair.set(user.name, "PURGED", "purged")
  115.                 user.is_approved = True
  116.             else:
  117.                 log.info("User: {0} is purged".format(user.name))
  118.                 if not user.is_purged: user.is_purged = True #Only needed for format update, since I wasn't tracking that locally before
  119.                 log.debug("User: {0} is banned and flaired, but not marked purged locally")
  120.         else:
  121.             log.info("User: {0}, SMV: {1}, score: {2} (current flair {3})".format(user.name, user.smv, user.good_karma + user.bad_karma, current_flair))
  122.  
  123.             if current_flair in IMMUTABLE_FLAIRS:
  124.                 log.info("Not changing user: {0} (immutable flair {1})".format(user.name, current_flair))
  125.             elif current_flair != "hb{0}".format(user.smv):
  126.                 log.info("Updating user: {0} flair to hb{1}".format(user.name, user.smv))
  127.                 tbp.flair.set(user.name, "Hβ{0}".format(user.smv), "hb{0}".format(user.smv))
  128.                
  129.                 if user.smv > 7 and not user.is_approved:
  130.                     if user.name not in tbp.contributor():
  131.                         log.info("Adding approved contributor: {0}".format(user.name))
  132.                         tbp.contributor.add(user.name)
  133.                         user.is_approved = True
  134.                     if not user.is_approved: user.is_approved = True #Only needed for format update, since I wasn't tracking that locally before
  135.                 elif user.smv < 4 and user.is_approved:
  136.                     log.info("Removing approved contributor: {0}".format(user.name))
  137.                     tbp.contributor.remove(user.name)
  138.                        
  139.  
  140.             else:
  141.                 log.info("User: {0} still an HB{1}".format(user.name, user.smv))
  142.    
  143.     pickle.dump(users, open("users.pickle", "wb"))
  144.  
  145. BAD_FLAIRS = ["purged", "vexatious"]
  146. TODAYS_THREAT_LEVEL = {"tlsevere":"Severe", "tlhigh":"High", "tlelevated":"Elevated"}
  147. threat_matrix = {"tllow": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,7)],
  148.                  "tlguarded": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,5)],
  149.                  "tlelevated": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,3)],
  150.                  "tlhigh": BAD_FLAIRS }
  151. def botloop(first_recalc):
  152.     next_recalc = first_recalc
  153.    
  154.     for comment in tbp.stream.comments():
  155.         threat_level = comment.submission.link_flair_css_class
  156.  
  157.         if threat_level == None or comment.submission.link_flair_text == None:
  158.             threat_level = list(TODAYS_THREAT_LEVEL.keys())[randint(0, len(TODAYS_THREAT_LEVEL) - 1)]
  159.             log.info("Setting threat level for Submission '{0}' [{1}] to {2}".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  160.             comment.submission.mod.flair(css_class=threat_level, text=TODAYS_THREAT_LEVEL[threat_level])
  161.         author_rank = comment.author_flair_css_class
  162.        
  163.         try:
  164.             if author_rank in threat_matrix["threat_level"]:
  165.                 #comment.remove()
  166.                 log.info("Removing comment by {0} ({1}) on post '{2}' ({3}), SMV too low!".format(comment.author.name, comment.author_css_class, comment.submission.title, threat_level))
  167.         except KeyError:
  168.             pass
  169.        
  170.         if datetime.now() > next_recalc:
  171.             update_flairs()
  172.             next_recalc = datetime.now() + timedelta(minutes=10)
  173.             log.info("Next refresh: {0}".format(next_recalc))
  174.        
  175.         if comment.author != None:
  176.             name = comment.author.name
  177.            
  178.             if not name in users.keys():
  179.                 good_karma, bad_karma = calc_score(name)
  180.                 users[name] = Tracker(name, good_karma, bad_karma)
  181.                 log.info("New user: {0}".format(name))
  182.             elif datetime.now() > users[name].next_refresh:
  183.                 good_karma, bad_karma = calc_score(name)
  184.                 users[name].update(good_karma, bad_karma)
  185.                 log.info("User: {0} scanned {1} times".format(name, users[name].scan_count))
  186.             else:
  187.                 log.info("Skipping user: {0}, next refresh {1}".format(name, users[name].next_refresh))
  188.         #if comment.author_flair_css_class == None:
  189.             #if users[comment.author].warned:
  190.             #   if TimeDelta(users[comment.author].warned_on, datetime.now()) > TimeDelta(days=1):
  191.             #       users[comment.author].comments_eaten.append(comment.id)
  192.             #       comment.remove()
  193.             #else:
  194.             #   Send PM to comment.author:
  195.             #       "To whom it may concern:
  196.             #  
  197.             #           Apologies for the inconvenience, but user flairs are mandatory on r/TheBluePill. Please disable the subreddit's CSS, and toggle your user flair back on. You have 24 hours to comply. After which, all of your posts will be automatically removed (posts automatically removed will be restored when you have re-enabled your flair.) This action was performed automatically, but this account is also attached to a human operator if you have any concerns. We appreciate your continued business!
  198.             #    
  199.             #       etc. etc.
  200.             #       -Management"
  201.             #   users[comment.author].warned = True
  202.             #   users[comment.author].warned_on = datetime.now()
  203.         #else:
  204.             #if users[comment.author].warned = True and len(users[comment.author].comments_eaten) > 0:
  205.             #   for comment in users[comment.author].comments_eaten:
  206.             #       reddit.comment(id=comment).approve()        <-- might be pseudocode
  207.             #       users[comment.author].comments_eaten = []
  208.  
  209. NEED_TO_UPDATE_OBJCLASS = False
  210. try:
  211.     users = pickle.load(open("users.pickle", "rb"))
  212.     log.info("Re-loading database")
  213.     if NEED_TO_UPDATE_OBJCLASS:
  214.         log.debug("Updating object format")
  215.         for user in users.values():
  216.             users[user.name] = Tracker(user.name, user.good_karma, user.bad_karma)
  217.        
  218.  
  219. except IOError:
  220.     users = {}
  221.     log.info("I/O error accessing database, starting fresh")
  222.  
  223.  
  224. try:
  225.     botloop(datetime.now() + timedelta(minutes=10))
  226.  
  227. except prawcore.PrawcoreException:
  228.     praw_fucked_up()
  229.     botloop(datetime.now() + timedelta(minutes=10))
  230.  
  231. except KeyboardInterrupt:
  232.     log.info("VirtuteTron going off-line")
  233.     pickle.dump(users, open("users.pickle", "wb"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement