PK!redditsweeper/__init__.pyPK!Gredditsweeper/__version__.py__version__ = "1.0.0" PK!l redditsweeper/app.py"""This module contains application entrypoints for using the library from the command line. """ import colorama import configargparse import os from colorama import Fore, Style from redditsweeper.__version__ import __version__ as version from redditsweeper.sweeper import Sweeper from redditsweeper.exceptions import SweeperError def check_subreddits(subreddits): for sub in subreddits: if not sub.startswith("r/"): raise SweeperError("Subreddit entry \"{}\" must be of format r/subredditname".format(sub)) return subreddits def main(): colorama.init() parser = configargparse.ArgumentParser(description="Cleans up old reddit comments periodically.", default_config_files=["redditsweeper.cfg"], auto_env_var_prefix="redditsweeper_") parser.add("-c", "--config", is_config_file=True, help="Config path if not redditsweeper.cfg") parser.add("-d", "--dry", help="Dry run (don't delete messages)", action="store_true") parser.add("-e", "--exclude", nargs="*", help="Subreddits to exclude from deletion.") parser.add("-i", "--include", nargs="*", help="Subreddits to include for deletion. Leave blank to include all.") parser.add("-k", "--keep", help="Keep comments than the given number (in days)", type=int) parser.add("-m", "--mfa", help="MFA token, if MFA is enabled") parser.add("-s", "--savefile", help="If set, writes deleted items to a JSON file") parser.add("-t", "--types", help="Item type to delete (comment, submission, both)", default="both") parser.add("-u", "--user", help="User in praw.ini if not default", default="default") args = parser.parse_args() try: inclusions = check_subreddits(args.include or []) except SweeperError as err: print("{}Error:{} {}".format(Fore.RED, Style.RESET_ALL, err)) return try: exclusions = check_subreddits(args.exclude or []) except SweeperError as err: print("{}Error:{} {}".format(Fore.RED, Style.RESET_ALL, err)) return print(Style.BRIGHT + "Starting redditsweeper v{}".format(version) + Style.RESET_ALL) print("{}Dry run:{} {}".format(Style.BRIGHT, Style.RESET_ALL, "yes" if args.dry else "no")) print("{}Including:{} {}".format(Style.BRIGHT, Style.RESET_ALL, "all" if not inclusions else ", ".join(inclusions))) print("{}Excluding:{} {}".format(Style.BRIGHT, Style.RESET_ALL, ", ".join(exclusions) if exclusions else "none")) print("{}Item types:{} {}".format(Style.BRIGHT, Style.RESET_ALL, "comments and submissions" if args.types == "both" else args.types)) if args.savefile: print("{}Saving to:{} {}".format(Style.BRIGHT, Style.RESET_ALL, args.savefile)) # Since updates to the savefile need to start from scratch, check for its existence and delete if needed if os.path.isfile(args.savefile): os.unlink(args.savefile) print("") sweeper = Sweeper(args.types, inclusions, exclusions, args.dry, keep=args.keep, user=args.user, mfa=args.mfa, save=args.savefile) sweeper.run() if __name__ == "__main__": main() PK!Мredditsweeper/exceptions.pyclass SweeperError(Exception): def __init__(self, value=None): self.value = value or "" def __str__(self): return repr(self.value) PK!=redditsweeper/sweeper.pyimport json import os import praw import time from colorama import Fore, Style from datetime import datetime from praw.config import Config from praw.models import Comment, Submission from prawcore.exceptions import ResponseException, OAuthException from redditsweeper.__version__ import __version__ as version from redditsweeper.exceptions import SweeperError # Python 2 doesn't have JSONDecodeError in its json package try: from json import JSONDecodeError except ImportError: JSONDecodeError = ValueError class Sweeper(object): """This class contains state information about the reddit connection and configuration options and offers methods to perform deletion operations. """ def __init__(self, types, include, exclude, dry, user="default", keep=None, mfa=None, save=None): self._include = {s.lower() for s in include} self._exclude = {s.lower() for s in exclude} self._user = user self._dry = dry self._keep_after = time.time() - keep * 86400 if keep else None self._types = types self._mfa = mfa self._save = save def _connect(self): """Isolates the connection process, along with the user agent construction, which is prescribed strongly by reddit's developer guidelines. Connecting to an MFA-enabled account without supplying a token will return the same error as using wrong credentials. However, the password (which must be combined with the token) is loaded during the same process as the connection itself. So, if a token is given, use the Config class to peek at what the password would be, but stick the MFA token to the end and then pass it explicitly to the Reddit class constructor. """ user_agent = "python:redditsweeper:v{}".format(version) try: if self._mfa: config = Config(self._user) password = "{}:{}".format(config.password, self._mfa) self._reddit = praw.Reddit(self._user, check_for_updates=False, user_agent=user_agent, password=password) else: self._reddit = praw.Reddit(self._user, check_for_updates=False, user_agent=user_agent) except ResponseException: raise SweeperError("Application ID or secret not recognized") except OAuthException: raise SweeperError("Login failed") self._user = self._reddit.user.me() print(Style.BRIGHT + "Connected as {}\n".format(self._reddit.config.username) + Style.RESET_ALL) def _save_item(self, item): if not self._save: return save = {"comments": [], "submissions": []} if os.path.isfile(self._save): try: with open(self._save) as fh: save = json.load(fh) except JSONDecodeError: # This happens if the file is blank, for example. pass if isinstance(item, Comment): save["comments"].append({"permalink": item.permalink, "upvotes": item.ups, "body": item.body, "created_utc": item.created_utc}) elif isinstance(item, Submission): save["submissions"].append({"permalink": item.permalink, "upvotes": item.ups, "title": item.title, "selftext": item.selftext, "created_utc": item.created_utc}) with open(self._save, "w") as fh: json.dump(save, fh, sort_keys=True, indent=4) def _handle_item(self, item): if self._keep_after and item.created_utc >= self._keep_after: print(Style.DIM + Fore.GREEN + "\t\tSkipping due to too new" + Style.RESET_ALL) return sub = item.subreddit.display_name_prefixed.lower() if sub in self._exclude: print(Style.DIM + Fore.GREEN + "\t\tSkipping due to excluded subreddit" + Style.RESET_ALL) return if not self._include or sub in self._include: print(Style.BRIGHT + Fore.RED + "\t\tDeleted!" + Style.RESET_ALL) if not self._dry: item.delete() self._save_item(item) else: print(Style.DIM + Fore.GREEN + "\t\tSkipping due to subreddit not included" + Style.RESET_ALL) def _each_item(self): if self._types == "comments" or self._types == "both": print("Iterating over comments") for comment in self._user.comments.new(limit=1000): humantime = datetime.fromtimestamp(comment.created_utc).strftime("%Y-%m-%d %H:%M") summary = comment if len(comment.body) <= 50 else comment.body[:50].replace("\n", "") + "..." print("\t{}Comment{} {}:\n\t\tTime: {}\n\t\tSummary: {}".format(Style.BRIGHT, Style.RESET_ALL, comment, humantime, summary)) yield comment if self._types == "submissions" or self._types == "both": print("Iterating over submissions") for submission in self._user.submissions.new(limit=1000): humantime = datetime.fromtimestamp(submission.created_utc).strftime("%Y-%m-%d %H:%M") print("\t{}Submission{} {}:\n\t\tTime: {}\n\t\tSummary: {}".format(Style.BRIGHT, Style.RESET_ALL, submission, humantime, submission.title)) yield submission def run(self): try: self._connect() for item in self._each_item(): self._handle_item(item) except KeyboardInterrupt: print("Stopping due to user interrupt...") PK!HoK/8.redditsweeper-1.0.0.dist-info/entry_points.txtN+I/N.,()*JMI,).OM-H-E%X&fqqPK!A&%redditsweeper-1.0.0.dist-info/LICENSECopyright 2018 Scott Hand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!H9VWX#redditsweeper-1.0.0.dist-info/WHEEL A н#f."jm)!fb҅~ܴA,mTD}E n0H饹*|D[¬c i=0(q3PK!HZN&redditsweeper-1.0.0.dist-info/METADATAXko8_|&&}daL dt&>$ŢXi9D Is/)vM#qTALY~*>ZOei_kj'y\wuf":`kt]JڹUֵnoV-`cB''':_f9N|aC/US{A\taiDޓ Nv3xY~>?yip?^cqY)hHd"?ȋuvX'JwمSum|EI>FOg?*?*[ԯyiY\ŭr7S?_Ϗ/(SkzM"$E{?w6f֕3m M 5쏥]7B 3LtS_ tpje0uZjq$x,+X9R5R+;hLe†J+'mv*M &oT\me h=**/׺w" H(:砭Hߵun.5TV]/a#G!啮tCK wxj B_+ ~$`nG`Œ=/b:(ޒCMӫcn{(oa?(FqɅYAG3|Rm,oMK>ȵbMDΕQti=20.0NEkAD!vc߳9wr xbnlde o|5&/Jt"v ڻ^$g?%,7Z JNLL_VTjVirƸjJ*1y:4RfuB>)D0\_tŃL n/4sӘ+ D pو8=De؟D\(]0P H5!=Q:N:)iP<,`sE%(uCEKd|m`<n0yQƀû Sȁ`w]CB̷񸞫L`2Ub*M GߌѼ~TJO+zӦ&.yϤaV.X%oO7}pR1}hI4(Ch,H/O,V )KSIN{e䬋W;(g^$ E7g 8d8w\)i`$el׺d% .kR6g]eGӶn4W$Sk=1@%9Ӝ P'OQ:.˛01=|Bv;H|AGLL֠.Mn`y=V2`It<~_cCPx[LB'96h2Eg$c Hw6V4 0NN9 -9< *þhZBP{*ZA跋91Xiyx~<؍ӯ'[\I(w= dז,?ٴyğv? p)A=53  8xBK4eəl֙;,/)u΃ɴ~nSSU. ,C04t@A5)q 4M+FiL'v4]!^qd ԉ/%o,fۜ rG@xLi bg[Ioܻ,c.!8Dsy5u|x/C j79G9vfVw_@-O_m1>ŭfh\L#ۧ~5?PK!HF6$redditsweeper-1.0.0.dist-info/RECORDɒ@}} XL ֢$ 6&!MHomM/xso;7t-ĴT0祵RvpRߣNr4S;hf܀?Þٞ#F,(ॅ_|<ʚg30#SJ_4.)873%_9au"nU;FDe1Ǵ{k_L}2Vf}X({2\k am_BTe jpޢv :m[lVAZv)edN,WcISk&DkRugLx2S(&qB\l_Ye)X|a qm |QOxi]/ AݹB9$ $嵭r+]5s];= Qg|#{0Vu5V% F;T#Q/ᮤxIzÇPۄ:|PK!redditsweeper/__init__.pyPK!G7redditsweeper/__version__.pyPK!l redditsweeper/app.pyPK!М^ redditsweeper/exceptions.pyPK!=3redditsweeper/sweeper.pyPK!HoK/8.&redditsweeper-1.0.0.dist-info/entry_points.txtPK!A&%&redditsweeper-1.0.0.dist-info/LICENSEPK!H9VWX#*redditsweeper-1.0.0.dist-info/WHEELPK!HZN&+redditsweeper-1.0.0.dist-info/METADATAPK!HF6$4redditsweeper-1.0.0.dist-info/RECORDPK 6