Advertisement
CrashARuntimeToday

VirtueTron9000 v0.2.9h

Jun 30th, 2018
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.52 KB | None | 0 0
  1. #!/usr/bin/python
  2. LICENCE = "WTFPL", "http://www.wtfpl.net/about/"
  3. VERSION = "v0.2.9h"
  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=0, bad_karma=0, 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 = 0
  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.     global last_fuckup
  65.     log.warning("Reddit API errored: waiting {0} seconds".format(delay))
  66.     try:
  67.         if delay > 128 or datetime.now() > last_fuckup + timedelta(minutes=2): delay = 2
  68.     except TypeError:
  69.         delay = 2
  70.     sleep(delay)
  71.     delay *= 2
  72.     last_fuckup = datetime.now()
  73.  
  74.  
  75. NICE_LIST = []
  76. NAUGHTY_LIST = "TheRedPill", "MarriedRedPill", "ChristianRedPill", "MGTOW", "Braincels", "AskTRP", "AskMRP", "RedPillWomen", "RedPillWives", "CringeAnarchy", "The_Donald", "RPChristians", "PussyPassDenied", "MensRights", "MillionDollarExtreme"
  77. def calc_score(name):
  78.     good_karma, bad_karma, good_count, bad_count = 0, 0, 0, 0
  79.    
  80.     for comment in reddit.redditor(name).comments.new(limit=100):
  81.         sub = comment.subreddit.display_name
  82.         karma = comment.score
  83.         if sub == "TheBluePill":
  84.             good_karma += karma - 1
  85.             good_count += 1
  86.         elif sub in NICE_LIST:
  87.             good_karma += (karma - 1) / 2
  88.         elif sub in NAUGHTY_LIST and karma > 1:
  89.             bad_karma -= karma - 1
  90.             bad_count += 1
  91.    
  92.     if good_count > 0:
  93.         good_karma /= good_count
  94.    
  95.     if bad_count > 0:
  96.         bad_karma /= bad_count
  97.         if bad_count > 5  and bad_karma > good_karma and name in users.keys() and not users[name].is_purged:
  98.             log.info("User: {0} is vexatious ({1} posts in NAUGHTY_LIST)".format(name, bad_count))
  99.             tbp.flair.set(name, "VEXATIOUS LITIGANT", "vexatious")
  100.             users[name].current_flair = "vexatious"
  101.  
  102.     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))
  103.     return good_karma, bad_karma
  104.  
  105.  
  106. IMMUTABLE_FLAIRS = "vanguard", "vexatious", "endorsedflair", "alpha", "betaasfuck", "feeemale", "purged"
  107. def update_flairs():
  108.     log.info("Recalculating SMV")
  109.     i = 0
  110.     total = len(users)
  111.     for user in sorted(users.values(), key=lambda x: x.good_karma + x.bad_karma):
  112.         i += 1
  113.         user.smv = ceil((i / total) * 10)
  114.        
  115.         # Not sure why Reddit doesn't like this bit and too lazy to run Wireshark
  116.         if user.current_flair == None:
  117.             log.debug("No cached flair for user: {0}, checking Reddit".format(user.name))
  118.             try:      
  119.                 for flair in tbp.flair(redditor=user.name):
  120.                     user.current_flair = flair["flair_css_class"]
  121.             except prawcore.PrawcoreException:
  122.                 praw_fucked_up()
  123.                 pass
  124.  
  125.         if user.current_flair == "purged" and not any(tbp.banned(redditor=user.name)): #Should only be needed transitionally since I fucked up and marked everyone PURGED (again!)
  126.             log.warn("Clearing false purged flair on user: {0} you fucking idiot".format(user.name))
  127.             user.is_purged = False
  128.             user.current_flair = "hb5"
  129.             tbp.flair.set(user.name, "Hβ5", "hb5")
  130.  
  131.         if not user.is_purged and any(tbp.banned(redditor=user.name)):
  132.             if user.current_flair != "purged":
  133.                 log.info("Marking user: {0} purged".format(user.name))
  134.                 tbp.flair.set(user.name, "PURGED", "purged")
  135.                 user.current_flair = "purged"
  136.                 user.is_purged = True
  137.             else:
  138.                 log.info("User: {0} is purged".format(user.name))
  139.                 if not user.is_purged: #Only needed for format update, since I wasn't tracking that locally before
  140.                     user.is_purged = True
  141.                     log.debug("User: {0} is purged and flaired, but not marked locally".format(user.name))
  142.         else:
  143.             log.debug("User: {0}, SMV: {1}, score: {2} (current flair {3})".format(user.name, user.smv, user.good_karma + user.bad_karma, user.current_flair))
  144.  
  145.             if user.current_flair in IMMUTABLE_FLAIRS:
  146.                 if user.current_flair == "vexatious" and user.smv > 2 and user.good_karma > abs(user.bad_karma):
  147.                     log.warn("Should user: {0} be vexatious? SMV: {1}, good_karma: {2}, bad_karma: {3}".format(user.name, user.smv, user.good_karma, user.bad_karma))
  148.                 else:
  149.                     log.debug("Not changing user: {0} (immutable flair {1})".format(user.name, user.current_flair))
  150.  
  151.             elif user.current_flair != "hb{0}".format(user.smv):
  152.                 log.info("Updating user: {0} flair to hb{1}".format(user.name, user.smv))
  153.                 tbp.flair.set(user.name, "Hβ{0}".format(user.smv), "hb{0}".format(user.smv))
  154.  
  155.                 user.current_flair = "hb{0}".format(user.smv)
  156.                
  157.                 if user.smv > 7 and not user.is_approved:
  158.                     if user.name not in tbp.contributor():
  159.                         log.info("Adding approved contributor: {0}".format(user.name))
  160.                         tbp.contributor.add(user.name)
  161.                         user.is_approved = True
  162.                     if not user.is_approved: #Only needed for format update, since I wasn't tracking that locally before
  163.                         user.is_approved = True
  164.                         log.debug("User: {0} is approved, but not marked locally".format(user.name))
  165.                 elif user.smv < 4 and user.is_approved:
  166.                     log.info("Removing approved contributor: {0}".format(user.name))
  167.                     tbp.contributor.remove(user.name)
  168.  
  169.             else:
  170.                 log.debug("User: {0} still an HB{1}".format(user.name, user.smv))
  171.    
  172.     pickle.dump(users, open("users.pickle", "wb"))
  173.  
  174.  
  175. BAD_FLAIRS = ["purged", "vexatious"]
  176. THREAT_MATRIX = {"tllow": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,7)],
  177.                  "tlguarded": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,5)],
  178.                  "tlelevated": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,3)],
  179.                  "tlhigh": BAD_FLAIRS,
  180.                  "tlsevere": []}
  181. TODAYS_THREAT_LEVEL = {"tlsevere":"Severe", "tlhigh":"High", "tlelevated":"Elevated", "tlguarded":"Guarded", "tllow":"Low"}
  182. def botloop(first_recalc):
  183.     next_recalc = first_recalc
  184.    
  185.     for comment in tbp.stream.comments():
  186.         if datetime.now() > next_recalc:
  187.             update_flairs()
  188.             next_recalc = datetime.now() + timedelta(minutes=15)
  189.             log.debug("Next refresh: {0}".format(next_recalc))
  190.  
  191.         threat_level = comment.submission.link_flair_css_class
  192.         if threat_level == None or comment.submission.link_flair_text == None or comment.submission.link_flair_text not in TODAYS_THREAT_LEVEL.values():
  193.             threat_level = list(TODAYS_THREAT_LEVEL.keys())[randint(0, len(TODAYS_THREAT_LEVEL) - 3)] # Won't randomly assign the last two link flairs
  194.             log.info("Setting threat level for submission '{0}' [id: {1}] to {2}".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  195.             comment.submission.mod.flair(css_class=threat_level, text=TODAYS_THREAT_LEVEL[threat_level])
  196.         else:
  197.             log.debug("Threat level for submission '{0}' [id: {1}] is {2})".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  198.                
  199.         if comment.author != None:
  200.             name = comment.author.name
  201.             author_rank = comment.author_flair_css_class
  202.  
  203.             if not name in users.keys():
  204.                 good_karma, bad_karma = calc_score(name)
  205.                 users[name] = Tracker(name, good_karma, bad_karma)
  206.                 log.info("New user: {0}".format(name))
  207.             elif datetime.now() > users[name].next_refresh:
  208.                 good_karma, bad_karma = calc_score(name)
  209.                 users[name].update(good_karma, bad_karma)
  210.                 log.debug("User: {0} scanned {1} times".format(name, users[name].scan_count))
  211.             else:
  212.                 log.debug("Skipping user: {0}, next refresh {1}".format(name, users[name].next_refresh))
  213.  
  214.             if users[name].current_flair != author_rank:
  215.                 log.info("Updating tracked flair for user: {0} - was {1}, now {2}".format(name, users[name].current_flair, author_rank))
  216.                 users[name].current_flair = author_rank
  217.            
  218.             if (author_rank == None or author_rank == "") and users[name].scan_count > 2:
  219.                 if bool(users[name].warned):
  220.                     # if datetime.now() > users[name].warned + timedelta(hours=1)
  221.                     if name == "FailAShitTestToday":
  222.                         users[name].comments_eaten.append(comment.id)
  223.                         comment.mod.remove()
  224.                         log.info("Removed comment {0} by unflaired user: {1}".format(comment.id, name))
  225.                 else:
  226.                     reply = comment.reply("Apologies for the inconvenience, but user flairs are mandatory on /r/TheBluePill. Please toggle your user flair back on at your earliest convenience (if you've opted out of the redesign, you'll need to disable this Subreddit's custom CSS to do so.) Your comments will be automatically filtered until you've re-enabled your flair, but the filtered comments will be restored when you're properly wearing your flair.\n\nThanks for choosing r/TheBluePill!\n\netc. etc., -Management\n\n*NOTE: This is an automated action, but this account is also attached to a human operator if you have any concerns. We appreciate your continued business!*")
  227.                     reply.mod.distinguish()
  228.                     users[name].warned = datetime.now()
  229.                     log.info("Warned user: {0}, flairs are mandatory.".format(name))
  230.             else:
  231.                 if bool(users[name].warned) and len(users[name].comments_eaten) > 0:
  232.                     for comment in users[name].comments_eaten:
  233.                         reddit.comment(id=comment).mod.approve()
  234.                         log.info("Restoring comment {0} for user: {1} (is wearing flair now)")
  235.                     users[name].comments_eaten = []
  236.  
  237.             if author_rank in THREAT_MATRIX[threat_level] and name != comment.submission.author:
  238.                 if name == "FailAShitTestToday" or name == "geneticwaste43":
  239.                     comment.mod.remove()
  240.                     log.info("Removing comment by user: {0} ({1}) on submission '{2}' [id: {3}] ({4}), SMV too low!".format(name, author_rank, comment.submission.title, comment.id, TODAYS_THREAT_LEVEL[threat_level]))
  241.                 log.info("Theoretically removing comment by user: {0} ({1}) on submission '{2}' [id: {3}] ({4}), SMV too low!".format(name, author_rank, comment.submission.title, comment.id, TODAYS_THREAT_LEVEL[threat_level]))
  242.  
  243.  
  244. NEED_TO_UPDATE_OBJCLASS = False
  245. try:
  246.     users = pickle.load(open("users.pickle", "rb"))
  247.     log.info("Re-loading database")
  248.     if NEED_TO_UPDATE_OBJCLASS:
  249.         log.debug("Updating object format")
  250.         for user in users.values():
  251.             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)
  252. except IOError:
  253.     users = {}
  254.     log.info("I/O error accessing database, starting fresh")
  255.  
  256.  
  257. try:
  258.     botloop(datetime.now()) #+ timedelta(minutes=15))
  259. except prawcore.PrawcoreException:
  260.     praw_fucked_up()
  261.     botloop(datetime.now()) #+ timedelta(minutes=15))
  262. except KeyboardInterrupt:
  263.     log.info("VirtuteTron going off-line")
  264.     pickle.dump(users, open("users.pickle", "wb"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement