Advertisement
CrashARuntimeToday

VirtueTron9000 v0.2.7a

Jun 30th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.25 KB | None | 0 0
  1. #!/usr/bin/python
  2. LICENCE = "WTFPL", "http://www.wtfpl.net/about/"
  3. VERSION = "v0.2.7a"
  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, new_user=True, scan_count=0, next_refresh=None, is_approved=False, is_purged=False, current_flair=None, warned=None, comments_eaten=[]):
  38.         self.name = name
  39.         self.smv = None
  40.         self.scan_count = scan_count
  41.         self.next_refresh = next_refresh
  42.         self.is_approved = is_approved
  43.         self.is_purged = is_purged
  44.         self.current_flair = None
  45.         self.warned = warned
  46.         self.comments_eaten = comments_eaten
  47.         if new_user:
  48.             self.update(good_karma, bad_karma)
  49.         else:
  50.             self.good_karma = good_karma
  51.             self.bad_karma = bad_karma
  52.    
  53.     def update(self, good_karma, bad_karma):
  54.         self.good_karma = good_karma
  55.         self.bad_karma = bad_karma
  56.         self.scan_count += 1
  57.         self.next_refresh = datetime.now() + timedelta(minutes=15)
  58.  
  59.  
  60. delay = 2
  61. last_fuckup = None
  62. def praw_fucked_up():
  63.     global delay
  64.     log.warning("Reddit API errored: waiting {0} seconds".format(delay))
  65.     try:
  66.         if delay > 128 or datetime.now() > last_fuckup + timedelta(minutes=2): delay = 2
  67.     except TypeError:
  68.         delay = 2
  69.     sleep(delay)
  70.     delay *= 2
  71.     last_fuckup = datetime.now()
  72.  
  73. NICE_LIST = []
  74. NAUGHTY_LIST = "TheRedPill", "MarriedRedPill", "ChristianRedPill", "MGTOW", "Braincels", "AskTRP", "AskMRP", "RedPillWomen", "RedPillWives", "CringeAnarchy", "The_Donald", "RPChristians", "PussyPassDenied", "MensRights"
  75. def calc_score(name):
  76.     good_karma, bad_karma, good_count, bad_count = 0, 0, 0, 0
  77.    
  78.     for comment in reddit.redditor(name).comments.new(limit=100):
  79.         sub = comment.subreddit.display_name
  80.         karma = comment.score
  81.         if sub == "TheBluePill":
  82.             good_karma += karma - 1
  83.             good_count += 1
  84.         elif sub in NICE_LIST:
  85.             good_karma += (karma - 1) / 2
  86.         elif sub in NAUGHTY_LIST and karma > 1:
  87.             bad_karma -= karma - 1
  88.             bad_count += 1
  89.    
  90.     if good_count > 0:
  91.         good_karma /= good_count
  92.    
  93.     if bad_count > 0:
  94.         bad_karma /= bad_count
  95.         if bad_count > 5 and not any(tbp.banned(redditor=name)):
  96.             log.info("User: {0} is vexatious ({1} posts in NAUGHTY_LIST)".format(name, bad_count))
  97.             tbp.flair.set(name, "VEXATIOUS LITIGANT", "vexatious")
  98.  
  99.     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))
  100.     return good_karma, bad_karma
  101.  
  102. IMMUTABLE_FLAIRS = "vanguard", "vexatious", "endorsedflair", "alpha", "betaasfuck", "feeemale", "purged"
  103. def update_flairs():
  104.     log.info("Recalculating SMV")
  105.     i = 0
  106.     total = len(users)
  107.     for user in sorted(users.values(), key=lambda x: x.good_karma + x.bad_karma):
  108.         i += 1
  109.         user.smv = ceil((i / total) * 10)
  110.        
  111.         # Not sure why Reddit doesn't like this bit and too lazy to run Wireshark
  112.         if user.current_flair == None:
  113.             log.debug("No cached flair for user: {0}, checking Reddit".format(user.name))
  114.             try:      
  115.                 for flair in tbp.flair(redditor=user.name):
  116.                     user.current_flair = flair["flair_css_class"]
  117.             except prawcore.PrawcoreException:
  118.                 praw_fucked_up()
  119.                 pass
  120.  
  121.         if not user.is_purged and any(tbp.banned(redditor=user.name)):
  122.             if user.current_flair != "purged":
  123.                 log.info("Marking user: {0} purged".format(user.name))
  124.                 tbp.flair.set(user.name, "PURGED", "purged")
  125.                 user.is_approved = True
  126.             else:
  127.                 log.info("User: {0} is purged".format(user.name))
  128.                 if not user.is_purged: #Only needed for format update, since I wasn't tracking that locally before
  129.                     user.is_purged = True
  130.                     log.debug("User: {0} is purged and flaired, but not marked locally")
  131.         else:
  132.             log.info("User: {0}, SMV: {1}, score: {2} (current flair {3})".format(user.name, user.smv, user.good_karma + user.bad_karma, user.current_flair))
  133.  
  134.             if user.current_flair in IMMUTABLE_FLAIRS:
  135.                 log.info("Not changing user: {0} (immutable flair {1})".format(user.name, user.current_flair))
  136.             elif user.current_flair != "hb{0}".format(user.smv):
  137.                 log.info("Updating user: {0} flair to hb{1}".format(user.name, user.smv))
  138.                 tbp.flair.set(user.name, "Hβ{0}".format(user.smv), "hb{0}".format(user.smv))
  139.                
  140.                 if user.smv > 7 and not user.is_approved:
  141.                     if user.name not in tbp.contributor():
  142.                         log.info("Adding approved contributor: {0}".format(user.name))
  143.                         tbp.contributor.add(user.name)
  144.                         user.is_approved = True
  145.                     if not user.is_approved: #Only needed for format update, since I wasn't tracking that locally before
  146.                         user.is_approved = True
  147.                         log.debug("User: {0} is approved, but not marked locally")
  148.                 elif user.smv < 4 and user.is_approved:
  149.                     log.info("Removing approved contributor: {0}".format(user.name))
  150.                     tbp.contributor.remove(user.name)
  151.                        
  152.  
  153.             else:
  154.                 log.info("User: {0} still an HB{1}".format(user.name, user.smv))
  155.    
  156.     pickle.dump(users, open("users.pickle", "wb"))
  157.  
  158. BAD_FLAIRS = ["purged", "vexatious"]
  159. TODAYS_THREAT_LEVEL = {"tlsevere":"Severe", "tlhigh":"High", "tlelevated":"Elevated"}
  160. threat_matrix = {"tllow": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,7)],
  161.                  "tlguarded": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,5)],
  162.                  "tlelevated": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,3)],
  163.                  "tlhigh": BAD_FLAIRS }
  164. def botloop(first_recalc):
  165.     next_recalc = first_recalc
  166.    
  167.     for comment in tbp.stream.comments():
  168.         threat_level = comment.submission.link_flair_css_class
  169.  
  170.         if threat_level == None or comment.submission.link_flair_text == None:
  171.             threat_level = list(TODAYS_THREAT_LEVEL.keys())[randint(0, len(TODAYS_THREAT_LEVEL) - 1)]
  172.             log.info("Setting threat level for Submission '{0}' [{1}] to {2}".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  173.             comment.submission.mod.flair(css_class=threat_level, text=TODAYS_THREAT_LEVEL[threat_level])
  174.         author_rank = comment.author_flair_css_class
  175.        
  176.         try:
  177.             if author_rank in threat_matrix["threat_level"]:
  178.                 #comment.remove()
  179.                 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))
  180.         except KeyError:
  181.             pass
  182.        
  183.         if datetime.now() > next_recalc:
  184.             update_flairs()
  185.             next_recalc = datetime.now() + timedelta(minutes=10)
  186.             log.info("Next refresh: {0}".format(next_recalc))
  187.        
  188.         if comment.author != None:
  189.             name = comment.author.name
  190.            
  191.             if not name in users.keys():
  192.                 good_karma, bad_karma = calc_score(name)
  193.                 users[name] = Tracker(name, good_karma, bad_karma)
  194.                 log.info("New user: {0}".format(name))
  195.             elif datetime.now() > users[name].next_refresh:
  196.                 good_karma, bad_karma = calc_score(name)
  197.                 users[name].update(good_karma, bad_karma)
  198.                 log.info("User: {0} scanned {1} times".format(name, users[name].scan_count))
  199.             else:
  200.                 log.info("Skipping user: {0}, next refresh {1}".format(name, users[name].next_refresh))
  201.         #if comment.author_flair_css_class == None:
  202.             #if users[comment.author].warned:
  203.             #   if TimeDelta(users[comment.author].warned_on, datetime.now()) > TimeDelta(days=1):
  204.             #       users[comment.author].comments_eaten.append(comment.id)
  205.             #       comment.remove()
  206.             #else:
  207.             #   Send PM to comment.author:
  208.             #       "To whom it may concern:
  209.             #  
  210.             #           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!
  211.             #    
  212.             #       etc. etc.
  213.             #       -Management"
  214.             #   users[comment.author].warned = datetime.now()
  215.         #else:
  216.             #if users[comment.author].warned = True and len(users[comment.author].comments_eaten) > 0:
  217.             #   for comment in users[comment.author].comments_eaten:
  218.             #       reddit.comment(id=comment).approve()        <-- might be pseudocode
  219.             #       users[comment.author].comments_eaten = []
  220.  
  221. NEED_TO_UPDATE_OBJCLASS = False
  222. try:
  223.     users = pickle.load(open("users.pickle", "rb"))
  224.     log.info("Re-loading database")
  225.     if NEED_TO_UPDATE_OBJCLASS:
  226.         log.debug("Updating object format")
  227.         for user in users.values():
  228.             users[user.name] = Tracker(user.name, user.good_karma, user.bad_karma, False, user.scan_count, user.next_refresh, user.is_approved, user.is_purged, user.current_flair, user.warned, user.comments_eaten)
  229.        
  230.  
  231. except IOError:
  232.     users = {}
  233.     log.info("I/O error accessing database, starting fresh")
  234.  
  235.  
  236. try:
  237.     botloop(datetime.now())
  238.  
  239. except prawcore.PrawcoreException:
  240.     praw_fucked_up()
  241.     botloop(datetime.now())
  242.  
  243. except KeyboardInterrupt:
  244.     log.info("VirtuteTron going off-line")
  245.     pickle.dump(users, open("users.pickle", "wb"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement