Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.12 KB | None | 0 0
  1. import praw
  2. import config
  3. import json
  4.  
  5. ignored_subreddits = ["legaladvice",
  6.                       "bestoflegaladvice",
  7.                       "legaladviceofftopic"]
  8.  
  9.  
  10. class load(object):
  11.     def __init__(self, filename):
  12.         self.filename = filename
  13.  
  14.         with open(self.filename, 'r') as f:
  15.             self.data = json.load(f)
  16.  
  17.     def __enter__(self):
  18.         return self.data
  19.  
  20.     def __exit__(self, type, value, tb):
  21.         with open(self.filename, 'w') as f:
  22.             json.dump(self.data, f, indent=4)
  23.  
  24.  
  25. class URLError(Exception):
  26.     pass
  27.  
  28.  
  29. def login():
  30.     """
  31.    Returns a reddit instance using your bot login information in config.py
  32.    Usage example: r = login()
  33.    """
  34.     return praw.Reddit(username=config.username,
  35.                        password=config.password,
  36.                        client_id=config.client_id,
  37.                        client_secret=config.client_secret,
  38.                        user_agent=config.user_agent)
  39.  
  40.  
  41. def is_comment(thread, title, url):
  42.     final_element = url[-1].split("_")[0]
  43.     return final_element != str(thread) and final_element not in title.lower()
  44.  
  45.  
  46. def post_comment_thread(reddit_instance, title, submission_obj):
  47.     print("Comment thread!")
  48.  
  49.  
  50. def post_thread(reddit_instance, title, submission_obj):
  51.     body = submission_obj.selftext
  52.     print("Title: " + title)
  53.     print("Body: " + body)
  54.  
  55.  
  56. def add_thread(thread):
  57.     """
  58.    Takes a submissionID and adds it to list of completed threads (set in config).
  59.    """
  60.     with load(config.filename) as subreddit_data:
  61.         if thread not in subreddit_data["ThreadID"]:
  62.             subreddit_data["ThreadID"].append(thread)
  63.  
  64.  
  65. def url_splitter(url):
  66.     """
  67.    :param url: Reddit URL
  68.    :return: Subreddit as string
  69.             Target post as string
  70.             Comment_thread as a boolean: True if comment thread
  71.    """
  72.     print(url)
  73.     if "reddit" not in url:
  74.         raise URLError("URL passed into function not from reddit.")
  75.  
  76.     # Split's URL on slashes, breaking the URL into its components.
  77.     split_url = url.split("/")
  78.  
  79.     # Removes underscores
  80.     split_url = list(filter(lambda x: x != '_', split_url))
  81.  
  82.     # Removes empty values
  83.     url_components = list(filter(None, split_url))
  84.  
  85.     # Removes last element where it's a query - not useful for parsing data.
  86.     while '?' in url_components[-1]:
  87.         url_components.pop()
  88.  
  89.     return url_components
  90.  
  91.  
  92. def clear_json():
  93.     with load(config.filename) as jsondata:
  94.         print("Are you sure you want to clear all previously worked threads?")
  95.         print("WARNING: THIS COULD POST TWICE ON THE SAME COMMENT, WHICH BREAKS REDDIT TOS")
  96.         if input("Please type 'I understand.': ") == "I understand.":
  97.             jsondata["ThreadID"] = []
  98.             print("Threads reset.")
  99.         else:
  100.             print("Threads not reset.")
  101.  
  102.  
  103. def work_thread(submission, reddit_instance):
  104.     url = url_splitter(submission.url)
  105.  
  106.     # The subreddit name is always immediately following /r/ in a reddit URL.
  107.     subreddit = url[url.index("r")+1].lower()
  108.     if subreddit not in ignored_subreddits:
  109.         target_thread = url[url.index("comments")+1]
  110.         target_thread_obj = reddit_instance.submission(target_thread)
  111.         title = target_thread_obj.title
  112.  
  113.         if is_comment(target_thread, title, url):
  114.             post_comment_thread(reddit_instance, title, target_thread_obj)
  115.         else:
  116.             post_thread(reddit_instance, title, target_thread_obj)
  117.  
  118.  
  119. def main(reddit_instance):
  120.     bola = reddit_instance.subreddit("bestoflegaladvice")
  121.     for submission in bola.stream.submissions():
  122.         threadID = str(submission)
  123.  
  124.         with open(config.filename, 'r') as f:
  125.             jsondata = json.load(f)
  126.             # Checks to see if thread has already been worked. If it has, skips.
  127.             if threadID not in jsondata["ThreadID"]:
  128.                 add_thread(str(submission))
  129.                 try:
  130.                     work_thread(submission, reddit_instance)
  131.                 except URLError:
  132.                     pass
  133.  
  134.  
  135. clear_json()
  136. if __name__ == "__main__":
  137.     main(login())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement