Advertisement
CrashARuntimeToday

VirtueTron9000 v0.3.2pre6

Jul 3rd, 2018
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.55 KB | None | 0 0
  1. #!/usr/bin/python
  2. LICENCE = "WTFPL", "http://www.wtfpl.net/about/"
  3. VERSION = "v0.3.2pre6"
  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=[], good_points=[], bad_points=[]):
  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 = current_flair
  45.         self.warned = warned
  46.         self.comments_eaten = comments_eaten
  47.         if len(good_points) == 0:
  48.             self.good_points = [good_karma]
  49.         else:
  50.             self.good_points = good_points
  51.         if len(bad_points) == 0:
  52.             self.bad_points = [bad_karma]
  53.         else:
  54.             self.bad_points = bad_points
  55.         self.best_post_karma = 0
  56.         self.worst_post_karma = 0
  57.         if new_user and not good_karma == 0 and bad_karma == 0:
  58.             self.update(good_karma, bad_karma)
  59.         else:
  60.             self.good_karma = good_karma
  61.             self.bad_karma = bad_karma
  62.  
  63.     @property
  64.     def score(self):
  65.         return sum(self.good_points) / len(self.good_points) + sum(self.bad_points) / len(self.bad_points)
  66.  
  67.     def update(self, good_karma, bad_karma):
  68.         self.good_karma = good_karma
  69.         self.bad_karma = bad_karma
  70.         self.good_points.insert(0, good_karma)
  71.         if len(self.good_points) > 8:
  72.             self.good_points.pop()
  73.             log.debug("Dropping oldest good karma sample for user: {0}".format(self.name))
  74.         self.bad_points.insert(0, bad_karma)
  75.         if len(self.bad_points) > 8:
  76.             self.bad_points.pop()
  77.             log.debug("Dropping oldest bad karma sample for user: {0}".format(self.name))
  78.         self.scan_count += 1
  79.         self.next_refresh = datetime.now() + timedelta(minutes=15)
  80.  
  81.  
  82. delay = 2
  83. last_fuckup = None
  84. def praw_fucked_up():
  85.     global delay
  86.     global last_fuckup
  87.     log.warning("Reddit API errored: waiting {0} seconds".format(delay))
  88.     try:
  89.         if delay > 128 or datetime.now() > last_fuckup + timedelta(minutes=2): delay = 2
  90.     except TypeError:
  91.         delay = 2
  92.     sleep(delay)
  93.     delay *= 2
  94.     last_fuckup = datetime.now()
  95.  
  96.  
  97. NICE_LIST = []
  98. NAUGHTY_LIST = "TheRedPill", "MarriedRedPill", "ChristianRedPill", "MGTOW", "Braincels", "AskTRP", "AskMRP", "RedPillWomen", "RedPillWives", "CringeAnarchy", "The_Donald", "RPChristians", "PussyPassDenied", "MensRights", "MillionDollarExtreme", "4chan"
  99. def calc_score(name):
  100.     good_karma, bad_karma, good_count, bad_count = 0, 0, 0, 0
  101.    
  102.     for comment in reddit.redditor(name).comments.new(limit=100):
  103.         sub = comment.subreddit.display_name
  104.         karma = comment.score
  105.         if sub == "TheBluePill":
  106.             good_karma += karma - 1
  107.             good_count += 1
  108.             if comment.score - 1 > users[name].best_post_karma:
  109.                 users[name].best_post_karma = comment.score - 1
  110.             if comment.score - 1 < users[name].worst_post_karma:
  111.                 users[name].worst_post_karma = comment.score - 1
  112.         elif sub in NICE_LIST:
  113.             good_karma += (karma - 1) / 2
  114.         elif sub in NAUGHTY_LIST and karma > 1:
  115.             bad_karma -= karma - 1
  116.             bad_count += 1
  117.    
  118.     if good_count > 0:
  119.         good_karma /= good_count
  120.  
  121.     # Assign an immutable flair (if appropriate)
  122.     if users[name].is_purged and not users[name].is_approved and not users[name].current_flair in GOOD_FLAIRS and any(tbp.banned(redditor=name)):
  123.         if users[name].current_flair != "purged":
  124.             log.info("Marking user: {0} purged".format(name))
  125.             tbp.flair.set(name, "PURGED", "purged")
  126.             users[name].current_flair = "purged"
  127.             users[name].is_purged = True
  128.         else:
  129.             log.info("User: {0} is purged".format(name))
  130.             #if not user.is_purged: #Only needed for format update, since I wasn't tracking that locally before
  131.             #    user.is_purged = True
  132.             #    log.debug("User: {0} is purged and flaired, but not marked locally".format(user.name))
  133.     elif bad_count > 0:
  134.         bad_karma /= bad_count
  135.         if bad_count > 10  and abs(bad_karma) > good_karma and name in users.keys() and not users[name].is_purged and not users[name].current_flair == "vexatious":
  136.             log.info("User: {0} is vexatious ({1} posts in NAUGHTY_LIST)".format(name, bad_count))
  137.             tbp.flair.set(name, "VEXATIOUS LITIGANT", "vexatious")
  138.             users[name].current_flair = "vexatious"
  139.  
  140.     # Keeping this around in case it happens again
  141.     #if users[name].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!)
  142.     #    log.warn("Clearing false purged flair on user: {0} you fucking idiot".format(user.name))
  143.     #    users[name].is_purged = False
  144.     #    users[name].current_flair = "hb5"
  145.     #    tbp.flair.set(name, "Hβ5", "hb5")
  146.  
  147.     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))
  148.     return good_karma, bad_karma
  149.  
  150.  
  151. IMMUTABLE_FLAIRS = "vanguard", "vexatious", "endorsedflair", "alpha", "betaasfuck", "feeemale", "purged"
  152. BAD_FLAIRS = ["purged", "vexatious"]
  153. GOOD_FLAIRS = ["endorsedflair", "vanguard", "alpha", "betaasfuck", "feeemale"]
  154.  
  155. def get_flair(name):
  156.     while True:
  157.         try:
  158.             for flair in tbp.flair(redditor=name):
  159.                 return flair["flair_css_class"]
  160.         except prawcore.PrawcoreException:
  161.             praw_fucked_up()
  162.  
  163. def update_flairs():
  164.     log.info("Recalculating SMV")
  165.     i = 0
  166.     total = len(users)
  167.     for user in sorted(users.values(), key=lambda x: x.score):
  168.         # Check if user deleted their account
  169.         try:
  170.             for x in reddit.redditor(user.name).new(limit=1):
  171.                 y = x
  172.  
  173.         except prawcore.exceptions.NotFound:
  174.             log.info("User: {0} is deleted, dropping from userlist".format(user.name))
  175.             del users[user.name]
  176.             total -= 1
  177.             continue
  178.  
  179.         i += 1
  180.         user.smv = ceil((i / total) * 10)
  181.  
  182.         if user.current_flair == None:
  183.             log.debug("No cached flair for user: {0}, checking Reddit".format(user.name))
  184.             user.current_flair = get_flair(user.name)
  185.             log.debug("Reddit says user: {0}'s flair is {1}".format(user.name, user.current_flair))
  186.  
  187.         log.debug("User: {0}, SMV: {1}, score: {2} (current flair {3})".format(user.name, user.smv, user.score, user.current_flair))
  188.  
  189.         if user.current_flair in IMMUTABLE_FLAIRS:
  190.             if user.current_flair == "vexatious" and user.smv > 2 and sum(user.good_points) > abs(sum(user.bad_points)):
  191.                 log.warn("Should user: {0} be vexatious? SMV: {1}, good_karma: {2}, bad_karma: {3}".format(user.name, user.smv, user.score, user.bad_karma))
  192.             else:
  193.                 log.debug("Not changing user: {0} (immutable flair {1})".format(user.name, user.current_flair))
  194.  
  195.         elif user.current_flair != "hb{0}".format(user.smv):
  196.             log.info("Updating user: {0} flair to hb{1}".format(user.name, user.smv))
  197.             tbp.flair.set(user.name, "Hβ{0}".format(user.smv), "hb{0}".format(user.smv))
  198.  
  199.             user.current_flair = "hb{0}".format(user.smv)
  200.            
  201.             if user.smv > 7 and not user.is_approved:
  202.                 if user.name not in tbp.contributor():
  203.                     log.info("Adding approved contributor: {0}".format(user.name))
  204.                     tbp.contributor.add(user.name)
  205.                     user.is_approved = True
  206.                 #if not user.is_approved: #Only needed for format update, since I wasn't tracking that locally before
  207.                 #    user.is_approved = True
  208.                 #    log.debug("User: {0} is approved, but not marked locally".format(user.name))
  209.             elif user.smv < 4 and user.is_approved:
  210.                 log.info("Removing approved contributor: {0}".format(user.name))
  211.                 tbp.contributor.remove(user.name)
  212.                 user.is_approved = False
  213.  
  214.         else:
  215.             log.debug("User: {0} still an HB{1}".format(user.name, user.smv))
  216.    
  217.     pickle.dump(users, open("users.pickle", "wb"))
  218.  
  219.  
  220. TODAYS_THREAT_LEVEL = {"tlsevere":"Severe", "tlhigh":"High", "tlelevated":"Elevated", "tlguarded":"Guarded", "tllow":"Low"}
  221. THREAT_MATRIX = {"tllow": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,7)],
  222.                  "tlguarded": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,5)],
  223.                  "tlelevated": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,3)],
  224.                  "tlhigh": BAD_FLAIRS,
  225.                  "tlsevere": []}
  226. FLAIR_EXEMPT = "sofcknwrong"
  227. def botloop(first_recalc):
  228.     next_recalc = first_recalc
  229.    
  230.     for comment in tbp.stream.comments():
  231.         if datetime.now() > next_recalc:
  232.             update_flairs()
  233.             next_recalc = datetime.now() + timedelta(minutes=15)
  234.             log.debug("Next refresh: {0}".format(next_recalc))
  235.  
  236.         threat_level = comment.submission.link_flair_css_class
  237.         if threat_level == None or comment.submission.link_flair_text == None or comment.submission.link_flair_text not in TODAYS_THREAT_LEVEL.values():
  238.             threat_selector = randint(0, len(TODAYS_THREAT_LEVEL) - 3) # Won't randomly assign the last two link flairs
  239.             if randint(0,1) == 0:
  240.                 threat_selector = 0 # Biasing random threat selection towards "Severe"
  241.             threat_level = list(TODAYS_THREAT_LEVEL.keys())[threat_selector]
  242.             log.info("Setting threat level for submission '{0}' [id: {1}] to {2}".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  243.             comment.submission.mod.flair(css_class=threat_level, text=TODAYS_THREAT_LEVEL[threat_level])
  244.         else:
  245.             log.debug("Threat level for submission '{0}' [id: {1}] is {2})".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  246.                
  247.         if comment.author != None:
  248.             name = comment.author.name
  249.             author_rank = comment.author_flair_css_class
  250.  
  251.             if not name in users.keys():
  252.                 users[name] = Tracker(name)
  253.                 good_karma, bad_karma = calc_score(name)
  254.                 users[name].update(good_karma, bad_karma)
  255.                 log.info("New user: {0}".format(name))
  256.             elif datetime.now() > users[name].next_refresh:
  257.                 good_karma, bad_karma = calc_score(name)
  258.                 users[name].update(good_karma, bad_karma)
  259.                 log.debug("User: {0} scanned {1} times".format(name, users[name].scan_count))
  260.             else:
  261.                 log.debug("Skipping user: {0}, next refresh {1}".format(name, users[name].next_refresh))
  262.  
  263.             if users[name].current_flair != author_rank:
  264.                 log.info("Updating tracked flair for user: {0} - was {1}, now {2}".format(name, users[name].current_flair, author_rank))
  265.                 users[name].current_flair = author_rank
  266.            
  267.             if (author_rank == None or author_rank == "") and users[name].scan_count > 4:
  268.                 if datetime.now() > users[name].warned + timedelta(hours=1):
  269.                     if name not in FLAIR_EXEMPT and (users[name].smv < 4 or comment.score < 1) and users[name].current_flair not in BAD_FLAIRS and comment.id not in users[name].comments_eaten:
  270.                         users[name].comments_eaten.append(comment.id)
  271.                         comment.mod.remove()
  272.                         log.info("Removed comment {0} by unflaired user: {1}".format(comment.id, name))
  273.                     else:
  274.                         log.info("Not removing comment {0} by unflaired user: {1} (exempt or too high value)".format(comment.id, name))
  275.                 else:
  276.                     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 flaired again.\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!*")
  277.                     reply.mod.distinguish()
  278.                     users[name].warned = datetime.now()
  279.                     log.info("Warned user: {0}, flairs are mandatory.".format(name))
  280.             else:
  281.                 if bool(users[name].warned) and len(users[name].comments_eaten) > 0:
  282.                     for comment in users[name].comments_eaten:
  283.                         reddit.comment(id=comment).mod.approve()
  284.                         log.info("Restoring comment {0} for user: {1} (is wearing flair now)".format(comment, name))
  285.                     users[name].comments_eaten = []
  286.  
  287.             if author_rank in THREAT_MATRIX[threat_level] and name != comment.submission.author:
  288.                 comment.mod.remove()
  289.                 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]))
  290.  
  291.  
  292. NEED_TO_UPDATE_OBJCLASS = False
  293. try:
  294.     users = pickle.load(open("users.pickle", "rb"))
  295.     log.info("Re-loading database")
  296.     if NEED_TO_UPDATE_OBJCLASS:
  297.         log.debug("Updating object format")
  298.         for user in users.values():
  299.             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, user.good_points, user.bad_points)
  300. except IOError:
  301.     users = {}
  302.     log.info("I/O error accessing database, starting fresh")
  303.  
  304.  
  305. try:
  306.     botloop(datetime.now())# + timedelta(minutes=5))
  307. except prawcore.PrawcoreException:
  308.     praw_fucked_up()
  309.     botloop(datetime.now())# + timedelta(minutes=5))
  310. except KeyboardInterrupt:
  311.     log.info("VirtuteTron going off-line")
  312.     pickle.dump(users, open("users.pickle", "wb"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement