Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # kwikstat.py ============================================ 2018 January 8
- #
- # Searches inbox for username mentions and replies to properly formatted
- # comments.
- #
- # Comment syntax: /u/kwikstat redditor
- #
- # Replies with comment containing tables of user's most active subreddits
- # by total comments and posts.
- #
- # Tested with Python 2.7.13 =============================================
- import time
- import operator
- import logging
- import praw
- import antiabuse as aa
- from prawcore import exceptions
- # Script loop delay
- delay = 300
- # Blacklisted subreddits
- blacklist = ['depression', 'suicidewatch']
- # Reddit Authentication information:
- clientId = "" # String
- clientSecret = "" # String
- userAgent = "" # String
- bot_name = "" # String
- password = "" # String
- # Search depth and list length values
- list_length = 5
- search_depth = 1000
- def aa_scan_ok(reddit, comment, bot_name):
- # Check and address anti-abuse issues
- if aa.is_summon_chain(reddit, comment, bot_name):
- msg = "ANTI-ABUSE: Summon chain - skipped"
- print msg
- logging.info(msg)
- return False
- if aa.comment_limit_reached(comment, 5):
- msg = "ANTI-ABUSE: Comment limit reached - skipped"
- print msg
- logging.info(msg)
- return False
- if aa.is_already_done(comment, bot_name):
- msg = "ANTI-ABUSE: Already done - skipped"
- print msg
- logging.info(msg)
- return False
- return True
- def search_and_post(comment, redditor, list_length, search_depth):
- # Create and post reply; append blacklist if necessary; handle errors
- global blacklist
- if not aa_scan_ok(reddit, comment, bot_name):
- comment.mark_read()
- return
- try:
- post_list = list(redditor.submissions.new(limit=search_depth))
- comment_list = list(redditor.comments.new(limit=search_depth))
- posts_dict = get_subreddit_tallies(post_list)
- comments_dict = get_subreddit_tallies(comment_list)
- reply_msg = "RECENT USER ACTIVITY: %s\n\n" % target_user
- reply_msg += "TOP SUBREDDITS BY POST:\n\n"
- reply_msg += build_table(posts_dict, list_length)
- reply_msg += "\n\nTOP SUBREDDITS BY COMMENT:\n\n"
- reply_msg += build_table(comments_dict, list_length)
- sent,status = aa.post_reply(reply_msg, comment, bot_name)
- if sent:
- msg = "REPLY SUCCESS @ %s" % comment.subreddit
- print msg
- logging.info(msg)
- logging.info(reply_msg)
- comment.mark_read()
- else:
- if status == "403 Client Error: Forbidden":
- msg = "BANNED: %s" % comment.subreddit
- print msg
- logging.info(msg)
- sub = str(comment.subreddit.display_name)
- append_blacklist(sub)
- comment.mark_read()
- else:
- msg = "REPLY FAILURE @ %s: %s" % (comment.subreddit, status)
- print msg
- logging.info(msg)
- except Exception as e:
- msg = "UNEXPECTED ERROR: %s" % str(e)
- print msg
- logging.error(msg)
- def build_table(tally_dict, list_length):
- # Create sorted list from tally dict in descending order by tally
- sorted_list = sorted(tally_dict.items(),
- key=operator.itemgetter(1),
- reverse=True)
- # Shrink post list size if necessary to avoid index error
- list_len = list_length
- if list_len > len(sorted_list):
- list_len = len(sorted_list)
- if list_len == 0:
- return None
- else:
- message = "total | subreddit\n-:|:-"
- for item in sorted_list[:list_len]:
- message += "\n%d | %s" % (item[1], item[0])
- return message
- def get_subreddit_tallies(contrib_list):
- # Tally number of contributions by subreddit; return dict
- contrib_dict = {}
- for contrib in contrib_list:
- subreddit = contrib.subreddit
- if subreddit not in contrib_dict.keys():
- contrib_dict[subreddit] = 1
- else:
- contrib_dict[subreddit] += 1
- return contrib_dict
- def append_blacklist(sub):
- # Append blacklist and modify script for future execution
- global blacklist
- bl_old = "blacklist = [%s]" % str(blacklist)[1:-1]
- blacklist.append(sub)
- bl_new = "blacklist = [%s]" % str(blacklist)[1:-1]
- with open("kwikstat.py", "r") as f:
- old_text = f.read()
- new_text = old_text.replace(bl_old, bl_new)
- with open("kwikstat.py", "w") as f:
- f.write(new_text)
- msg = "BLACKLIST Appended: %s" % sub
- print msg
- logging.info(msg)
- # Log file setup
- log_name = raw_input("Log file: ")
- if not log_name.endswith(".log"):
- log_name += ".log"
- log_format = "%(asctime)s\t%(levelname)s \t%(message)s" # DEBUG
- logging.basicConfig(level=logging.DEBUG, # INFO
- datefmt="%Y-%m-%d %H:%M:%S", # WARNING
- format=log_format, # ERROR
- filename=log_name) # CRITICAL
- logging.info("Logging started")
- # Create Reddit instance
- reddit = praw.Reddit(client_id=clientId,
- client_secret=clientSecret,
- user_agent=userAgent,
- username=bot_name,
- password=password)
- # MAIN LOOP -------------------------------------------------------------
- while True:
- # Try to reply to new inbox messages if they are username mentions
- for item in reddit.inbox.unread(limit=None):
- target_user = item.body.split(" ")[1]
- msg = "REQUESTER: %s | TARGET: %s | SUBREDDIT: %s" % \
- (item.author, target_user, item.subreddit)
- print msg
- logging.info(msg)
- target = reddit.redditor(target_user)
- if isinstance(item, praw.models.Comment):
- if item.subreddit in blacklist:
- msg = "BLACKLIST - request from %s" % item.subreddit
- print msg
- logging.info(msg)
- item.mark_read()
- else:
- search_and_post(item, target, list_length,
- search_depth)
- for i in range(delay):
- time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement