Advertisement
CrashARuntimeToday

VirtueTron9000 v0.3.2_pre16

Jul 6th, 2018
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.67 KB | None | 0 0
  1. #!/usr/bin/python
  2. LICENCE = "WTFPL", "http://www.wtfpl.net/about/"
  3. VERSION = "v0.3.2_pre16"
  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. IMMUTABLE_FLAIRS = ["vanguard", "vexatious", "endorsedflair", "alpha", "betaasfuck", "feeemale", "purged"]
  36. BAD_FLAIRS = ["purged", "vexatious"]
  37. GOOD_FLAIRS = ["endorsedflair", "vanguard", "alpha", "betaasfuck", "feeemale"]
  38.  
  39. delay = 2
  40. last_fuckup = None
  41. def praw_fucked_up():
  42. global delay
  43. global last_fuckup
  44. log.warning("Reddit API error: waiting {0} seconds".format(delay))
  45. try:
  46. if delay > 128 or datetime.now() > last_fuckup + timedelta(minutes=2): delay = 2
  47. except TypeError:
  48. delay = 2
  49. sleep(delay)
  50. delay *= 2
  51. last_fuckup = datetime.now()
  52.  
  53. def get_flair(name):
  54. while True:
  55. try:
  56. for flair in tbp.flair(redditor=name):
  57. return flair["flair_css_class"]
  58. except prawcore.PrawcoreException:
  59. praw_fucked_up()
  60.  
  61.  
  62. class Tracker:
  63. NICE_LIST = []
  64. NAUGHTY_LIST = ["theredpill", "marriedredpill", "mgtow", "braincels", "asktrp", "askmrp", "redpillwomen", "redpillwives", "cringeanarchy", "the_donald", "rpchristians", "pussypassdenied", "mensrights", "milliondollarextreme", "4chan", "whereareallthegoodmen"]
  65. # For some reason VSCode eats the indents on blank lines and this gives the python interpreter fits when I copy/paste, so empty comments at the correct indent level it is!
  66. def __init__(self, name, new_user=True, good_points=[0], bad_points=[0], scan_count=0, next_refresh=(datetime.now()+timedelta(minutes=15)), is_approved=False, is_purged=False, current_flair=None, warned=None, comments_eaten=[], current_shittest=None, last_seen=datetime.now()):
  67. self.name = name
  68. self.smv = 0
  69. self.scan_count = scan_count
  70. self.next_refresh = next_refresh
  71. self.is_approved = is_approved
  72. self.is_purged = is_purged
  73. self.current_flair = current_flair
  74. self.warned = warned
  75. self.comments_eaten = comments_eaten
  76. self.good_points = good_points
  77. self.bad_points = bad_points
  78. self.best_post_karma = 0
  79. self.best_post_id = None
  80. self.worst_post_karma = 0
  81. self.worst_post_id = None
  82. self.current_shittest = current_shittest
  83. self.last_seen = last_seen
  84. if new_user:
  85. self.update()
  86. #
  87. @property
  88. def good_karma(self):
  89. return sum(self.good_points) / len(self.good_points)
  90. @property
  91. def bad_karma(self):
  92. return sum(self.bad_points) / len(self.bad_points)
  93. @property
  94. def score(self):
  95. return self.good_karma + self.bad_karma
  96. #
  97. def update(self):
  98. good, bad, good_count, bad_count = 0, 0, 0, 0
  99. for comment in reddit.redditor(self.name).comments.new(limit=100):
  100. sub = comment.subreddit.display_name.lower()
  101. karma = comment.score - 1
  102. if sub == "thebluepill":
  103. good += karma
  104. good_count += 1
  105. if karma > self.best_post_karma:
  106. self.best_post_karma = karma
  107. self.best_post_id = comment.id
  108. if karma < self.worst_post_karma:
  109. self.worst_post_karma = karma
  110. self.worst_post_id = comment.id
  111. elif sub in Tracker.NICE_LIST:
  112. good += (karma) / 2
  113. elif sub in Tracker.NAUGHTY_LIST and karma > 1:
  114. bad -= karma
  115. bad_count += 1
  116. #
  117. if good_count > 0:
  118. good /= good_count
  119. if bad_count > 0:
  120. bad /= bad_count
  121. bad *= bad_count / 5 # Every 10 posts in NAUGHTY_LIST doubles your bad karma
  122. # Are they vexatious? (Of course they are!)
  123. if self.current_flair != "vexatious" and bad_count > 10 and abs(bad) > good:
  124. log.info("User: {0} is vexatious ({1} posts in NAUGHTY_LIST)".format(self.name, bad_count))
  125. tbp.flair.set(self.name, "VEXATIOUS LITIGANT", "vexatious")
  126. self.current_flair = "vexatious"
  127. #
  128. log.info("Scanned user: {0}, good_karma: {1:.2f} ({2} comments), bad_karma: {3:.2f} ({4} comments)".format(self.name, good, good_count, bad, bad_count))
  129. self.good_points.insert(0, good)
  130. if len(self.good_points) > 8:
  131. self.good_points.pop()
  132. log.debug("Dropping oldest good karma sample for user: {0}".format(self.name))
  133. self.bad_points.insert(0, bad)
  134. if len(self.bad_points) > 8:
  135. self.bad_points.pop()
  136. log.debug("Dropping oldest bad karma sample for user: {0}".format(self.name))
  137. self.scan_count += 1
  138. self.next_refresh = datetime.now() + timedelta(minutes=15)
  139.  
  140. def update_flairs():
  141. log.info("Recalculating SMV")
  142. i = 0
  143. total = len(users)
  144. # I'm so fuckin' dumb, we should've been doing it this way from the beginning
  145. purged_users = list(tbp.banned())
  146. approved_users = list(tbp.contributor())
  147. #
  148. for user in sorted(users.values(), key=lambda x: x.score):
  149. if user.is_approved and user.name not in approved_users:
  150. log.debug("Clearing approved flag on user: {0}".format(user.name))
  151. user.is_approved = False
  152. #
  153. if not user.is_purged and user.name in purged_users:
  154. if user.current_flair != "purged":
  155. log.info("Marking user: {0} purged".format(user.name))
  156. tbp.flair.set(user.name, "PURGED", "purged")
  157. user.current_flair = "purged"
  158. user.is_purged = True
  159. else:
  160. log.debug("User: {0} remains purged".format(user.name))
  161. elif user.is_purged and user.name not in purged_users:
  162. if user.current_flair == "purged":
  163. log.info("User: {0} was unbanned, clearing flair")
  164. tbp.flair.set(user.name, "VEXATIOUS LITIGANT", "vexatious")
  165. #
  166. i += 1
  167. user.smv = ceil((i / total) * 10)
  168. log.debug("User: {0}, SMV: {1}, score: {2:.2f} (current flair {3})".format(user.name, user.smv, user.score, user.current_flair))
  169. #
  170. if user.current_flair == None:
  171. # Check if user deleted their account
  172. try:
  173. for x in reddit.redditor(user.name).new(limit=1):
  174. y = x
  175. except (prawcore.exceptions.NotFound, prawcore.exceptions.Forbidden):
  176. log.info("User: {0} is deleted, dropping from userlist".format(user.name))
  177. del users[user.name]
  178. total -= 1
  179. continue
  180. log.debug("No cached flair for user: {0}, checking Reddit".format(user.name))
  181. user.current_flair = get_flair(user.name)
  182. log.debug("Reddit says user: {0}'s flair is {1}".format(user.name, user.current_flair))
  183. #
  184. if user.current_flair in IMMUTABLE_FLAIRS:
  185. if user.current_flair == "vexatious" and user.smv > 2 and user.good_karma > abs(user.bad_karma):
  186. log.warn("Should user: {0} be vexatious? SMV: {1}, good_karma: {2:.2f}, bad_karma: {3:.2f}".format(user.name, user.smv, user.good_karma, user.bad_karma))
  187. else:
  188. log.debug("Not changing user: {0} (immutable flair {1})".format(user.name, user.current_flair))
  189.  
  190. elif user.current_flair != "hb{0}".format(user.smv):
  191. log.info("Updating user: {0} flair to hb{1}".format(user.name, user.smv))
  192. tbp.flair.set(user.name, "Hβ{0}".format(user.smv), "hb{0}".format(user.smv))
  193.  
  194. user.current_flair = "hb{0}".format(user.smv)
  195. #
  196. else:
  197. log.debug("User: {0} still an Hβ{1}".format(user.name, user.smv))
  198. #
  199. if (user.smv > 7 or user.current_flair in GOOD_FLAIRS) and not user.is_approved:
  200. if user.name not in approved_users:
  201. log.info("Theoretically adding approved contributor: {0} (fuckin' rate limits)".format(user.name))
  202. #tbp.contributor.add(user.name)
  203. #user.is_approved = True
  204. #sleep(2) # Transitional, I've got so many people that should be approved but my data was fucked
  205. elif user.name in approved_users:
  206. user.is_approved = True
  207. log.debug("Marking user: {0} approved".format(user.name))
  208. elif user.smv < 4 and user in approved_users:
  209. log.info("Removing approved contributor: {0}".format(user.name))
  210. tbp.contributor.remove(user.name)
  211. user.is_approved = False
  212. #
  213. pickle.dump(users, open("users.pickle", "wb"))
  214.  
  215.  
  216. TODAYS_THREAT_LEVEL = {"tlsevere":"Severe", "tlhigh":"High", "tlelevated":"Elevated", "tlguarded":"Guarded", "tllow":"Low"}
  217. THREAT_MATRIX = {"tllow": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,7)],
  218. "tlguarded": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,5)],
  219. "tlelevated": BAD_FLAIRS + ["hb{0}".format(x) for x in range(1,3)],
  220. "tlhigh": BAD_FLAIRS,
  221. "tlsevere": []}
  222. FLAIR_EXEMPT = "sofcknwrong"
  223. def botloop(first_recalc=datetime.now()):
  224. next_recalc = first_recalc
  225. #
  226. for comment in tbp.stream.comments():
  227. if datetime.now() > next_recalc:
  228. update_flairs()
  229. next_recalc = datetime.now() + timedelta(minutes=15)
  230. log.debug("Next refresh: {0:%Y/%m/%d %I:%M:%S%p}".format(next_recalc))
  231. #
  232. threat_level = comment.submission.link_flair_css_class
  233. if threat_level == None or comment.submission.link_flair_text == None or comment.submission.link_flair_text not in TODAYS_THREAT_LEVEL.values():
  234. if randint(0,1) == 0: # 50-50 shot of getting "Severe"
  235. threat_selector = 0
  236. else:
  237. threat_selector = randint(1, len(TODAYS_THREAT_LEVEL) - 3) # Won't randomly assign the last two link flairs
  238. threat_level = list(TODAYS_THREAT_LEVEL.keys())[threat_selector]
  239. log.info("Setting threat level for submission '{0}' [id: {1}] to {2}".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  240. comment.submission.mod.flair(css_class=threat_level, text=TODAYS_THREAT_LEVEL[threat_level])
  241. else:
  242. log.debug("Threat level for submission '{0}' [id: {1}] is {2})".format(comment.submission.title, comment.submission.id, TODAYS_THREAT_LEVEL[threat_level]))
  243. #
  244. if comment.author != None:
  245. name = comment.author.name
  246. author_rank = comment.author_flair_css_class
  247. #
  248. if not name in users.keys():
  249. users[name] = Tracker(name)
  250. log.info("New user: {0}".format(name))
  251. elif datetime.now() > users[name].next_refresh:
  252. users[name].update()
  253. log.debug("User: {0} scanned {1} times".format(name, users[name].scan_count))
  254. users[name].last_seen = datetime.now()
  255. else:
  256. log.debug("Skipping user: {0}, next refresh {1:%Y/%m/%d %I:%M:%S%p}".format(name, users[name].next_refresh))
  257. users[name].last_seen = datetime.now()
  258.  
  259. if users[name].current_flair != author_rank:
  260. log.info("Updating tracked flair for user: {0} - was {1}, now {2}".format(name, users[name].current_flair, author_rank))
  261. users[name].current_flair = author_rank
  262. #
  263. if (author_rank == None or author_rank == "") and users[name].scan_count > 4:
  264. if datetime.now() > users[name].warned + timedelta(minutes=30):
  265. 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:
  266. users[name].comments_eaten.append(comment.id)
  267. comment.mod.remove()
  268. log.info("Removed comment {0} by unflaired user: {1}".format(comment.id, name))
  269. else:
  270. log.info("Not removing comment {0} by unflaired user: {1} (exempt or too high value)".format(comment.id, name))
  271. else:
  272. 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!*")
  273. reply.mod.distinguish()
  274. users[name].warned = datetime.now()
  275. log.info("Warned user: {0}, flairs are mandatory.".format(name))
  276. else:
  277. if bool(users[name].warned) and len(users[name].comments_eaten) > 0:
  278. for comment in users[name].comments_eaten:
  279. reddit.comment(id=comment).mod.approve()
  280. log.info("Restoring comment {0} for user: {1} (is wearing flair now)".format(comment, name))
  281. users[name].comments_eaten = []
  282.  
  283. if author_rank in THREAT_MATRIX[threat_level] and name != comment.submission.author:
  284. comment.mod.remove()
  285. 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]))
  286.  
  287.  
  288. NEED_TO_UPDATE_OBJCLASS = False
  289. try:
  290. users = pickle.load(open("users.pickle", "rb"))
  291. log.info("Re-loading database")
  292. if NEED_TO_UPDATE_OBJCLASS:
  293. log.debug("Updating object format")
  294. for user in users.values():
  295. users[user.name] = Tracker(user.name, False, user.good_points, user.bad_points, user.scan_count, user.next_refresh, user.is_approved, user.is_purged, user.current_flair, user.warned, user.comments_eaten, user.current_shittest, user.last_seen)
  296. except IOError:
  297. users = {}
  298. log.info("I/O error accessing database, starting fresh")
  299.  
  300.  
  301. try:
  302. botloop()
  303. except prawcore.PrawcoreException:
  304. praw_fucked_up()
  305. botloop()
  306. except KeyboardInterrupt:
  307. log.info("VirtuteTron going off-line")
  308. pickle.dump(users, open("users.pickle", "wb"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement