├── .gitignore ├── BotSkeleton ├── .gitignore ├── BotSkeleton.py ├── README.md └── oauth_template.txt ├── BulletPointCollector ├── .gitignore ├── BulletPointCollector.py └── README.md ├── ChangeFlairBot ├── .gitignore ├── ChangeFlairBot.py ├── README.md └── oauth_template.txt ├── ELOBot ├── .gitignore ├── ELOBot.py ├── README.md └── oauth_template.txt ├── EMailNotification ├── .gitignore ├── EMailNotification.py ├── README.md ├── oauth_template.txt └── rules.txt ├── EvoCreoBot ├── .gitignore ├── EvoCreoBot.py ├── README.md └── oauth_template.txt ├── ForwardOrangered ├── .gitignore ├── ForwardOrangered.py ├── README.md └── oauth_template.txt ├── HeaderChangeBot ├── .gitignore ├── HeaderChangeBot.py ├── README.md ├── headers.txt └── oauth_template.txt ├── LICENSE ├── ProxyBot ├── .gitignore ├── ProxyBot.py ├── README.md └── oauth_template.txt ├── README.md ├── RSSBot ├── .gitignore ├── README.md ├── RSSBot.py ├── RSSReader.py ├── html2text.py ├── html2text_LICENSE ├── oauth_template.txt └── sources.txt ├── RandomUserSelector ├── .gitignore ├── README.md ├── RandomUserSelector.py └── oauth_template.txt ├── RespondQuest ├── .gitignore ├── README.md ├── RespondQuest.py └── oauth_template.txt ├── ScheduleBot ├── .gitignore ├── README.md ├── ScheduleBot.py ├── ScheduledPost.py └── oauth_template.txt └── UserListKeeper ├── .gitignore ├── README.md ├── UserListKeeper.py ├── oauth_template.txt └── userlist.txt /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | bot.py 3 | bot.log 4 | oauth.txt 5 | oauth.ini 6 | -------------------------------------------------------------------------------- /BotSkeleton/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt 2 | done.txt -------------------------------------------------------------------------------- /BotSkeleton/BotSkeleton.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | An empty bot to be able to start a new bot fast. 5 | Written by /u/SmBe19 6 | """ 7 | 8 | import praw 9 | import time 10 | import logging 11 | import logging.handlers 12 | import OAuth2Util 13 | 14 | # ### USER CONFIGURATION ### # 15 | 16 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 17 | USERAGENT = "" 18 | 19 | # The name of the subreddit to post to. e.g. "funny" 20 | SUBREDDIT = "" 21 | 22 | # The time in seconds the bot should sleep until it checks again. 23 | SLEEP = 60*60 24 | 25 | # ### END USER CONFIGURATION ### # 26 | 27 | # ### BOT CONFIGURATION ### # 28 | DONE_CONFIGFILE = "done.txt" 29 | # ### END BOT CONFIGURATION ### # 30 | 31 | # ### LOGGING CONFIGURATION ### # 32 | LOG_LEVEL = logging.INFO 33 | LOG_FILENAME = "bot.log" 34 | LOG_FILE_BACKUPCOUNT = 5 35 | LOG_FILE_MAXSIZE = 1024 * 256 36 | # ### END LOGGING CONFIGURATION ### # 37 | 38 | # ### EXTERNAL CONFIG FILE ### # 39 | try: 40 | # A file containing data for global constants. 41 | import bot 42 | for k in dir(bot): 43 | if k.upper() in globals(): 44 | globals()[k.upper()] = getattr(bot, k) 45 | except ImportError: 46 | pass 47 | # ### END EXTERNAL CONFIG FILE ### # 48 | 49 | # ### LOGGING SETUP ### # 50 | log = logging.getLogger("bot") 51 | log.setLevel(LOG_LEVEL) 52 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 53 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 54 | log_stderrHandler = logging.StreamHandler() 55 | log_stderrHandler.setFormatter(log_formatter) 56 | log.addHandler(log_stderrHandler) 57 | if LOG_FILENAME is not None: 58 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 59 | log_fileHandler.setFormatter(log_formatter_file) 60 | log.addHandler(log_fileHandler) 61 | # ### END LOGGING SETUP ### # 62 | 63 | # ### DONE CONFIG FILE ### # 64 | def read_config_done(): 65 | done = set() 66 | try: 67 | with open(DONE_CONFIGFILE, "r") as f: 68 | for line in f: 69 | if line.strip(): 70 | done.add(line.strip()) 71 | except OSError: 72 | log.info("%s not found.", DONE_CONFIGFILE) 73 | return done 74 | 75 | def write_config_done(done): 76 | with open(DONE_CONFIGFILE, "w") as f: 77 | for d in done: 78 | if d: 79 | f.write(d + "\n") 80 | # ### END DONE CONFIG FILE ### # 81 | 82 | # ### MAIN PROCEDURE ### # 83 | def run_bot(): 84 | r = praw.Reddit(USERAGENT) 85 | o = OAuth2Util.OAuth2Util(r) 86 | o.refresh() 87 | sub = r.get_subreddit(SUBREDDIT) 88 | 89 | log.info("Start bot for subreddit %s", SUBREDDIT) 90 | 91 | done = read_config_done() 92 | 93 | while True: 94 | try: 95 | pass 96 | 97 | # Allows the bot to exit on ^C, all other exceptions are ignored 98 | except KeyboardInterrupt: 99 | break 100 | except Exception as e: 101 | log.error("Exception %s", e, exc_info=True) 102 | 103 | write_config_done(done) 104 | log.info("sleep for %s s", SLEEP) 105 | time.sleep(SLEEP) 106 | 107 | write_config_done(done) 108 | # ### END MAIN PROCEDURE ### # 109 | 110 | # ### START BOT ### # 111 | if __name__ == "__main__": 112 | if not USERAGENT: 113 | log.error("missing useragent") 114 | elif not SUBREDDIT: 115 | log.error("missing subreddit") 116 | else: 117 | run_bot() 118 | # ### END START BOT ### # 119 | -------------------------------------------------------------------------------- /BotSkeleton/README.md: -------------------------------------------------------------------------------- 1 | # Bot Skeleton 2 | An empty bot to be able to start a new bot fast. -------------------------------------------------------------------------------- /BotSkeleton/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=identity,submit,read 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /BulletPointCollector/.gitignore: -------------------------------------------------------------------------------- 1 | list.txt -------------------------------------------------------------------------------- /BulletPointCollector/BulletPointCollector.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot that collects all bullet points of a thread. 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import re 8 | import sys 9 | import time 10 | 11 | # ### USER CONFIGURATION ### # 12 | 13 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 14 | USERAGENT = "" 15 | 16 | # The time in seconds the bot should sleep until it checks again. 17 | SLEEP = 60*60 18 | 19 | # ### END USER CONFIGURATION ### # 20 | 21 | # ### BOT CONFIGURATION ### # 22 | LIST_OUTPUTFILE = "list.txt" 23 | 24 | LIST_RE = re.compile(r"^( *)[-+*] (.*?)$") 25 | LIST_LINESTART_RE = re.compile(r"^( *)([-+*])( +)") 26 | # ### END BOT CONFIGURATION ### # 27 | 28 | try: 29 | # A file containing data for global constants. 30 | import bot 31 | for k in dir(bot): 32 | if k.upper() in globals(): 33 | globals()[k.upper()] = getattr(bot, k) 34 | except ImportError: 35 | pass 36 | 37 | def collect_points(url): 38 | r = praw.Reddit(USERAGENT) 39 | 40 | thread = r.get_submission(url=url) 41 | 42 | if thread is None: 43 | print("Thread not found") 44 | return 45 | 46 | comments = praw.helpers.flatten_tree(thread.comments) 47 | 48 | result = [] 49 | 50 | for comment in comments: 51 | isInList = False 52 | wasEmpty = True 53 | for line in comment.body.splitlines(): 54 | if wasEmpty: 55 | isInList = LIST_RE.match(line) 56 | wasEmpty = line == "" 57 | if not wasEmpty and isInList: 58 | result.append(LIST_LINESTART_RE.sub(r"\1* ", line)) 59 | 60 | with open(LIST_OUTPUTFILE, "w") as f: 61 | f.write("\n".join(result)) 62 | 63 | 64 | if __name__ == "__main__": 65 | if not USERAGENT: 66 | print("missing useragent") 67 | elif len(sys.argv) < 2: 68 | print("usage: python", sys.argv[0], "url [outputfile]") 69 | else: 70 | if len(sys.argv) > 2: 71 | LIST_OUTPUTFILE = sys.argv[2] 72 | collect_points(sys.argv[1]) 73 | -------------------------------------------------------------------------------- /BulletPointCollector/README.md: -------------------------------------------------------------------------------- 1 | # Bullet Point Collector 2 | A bot that collects all bullet points of a thread. 3 | 4 | Call `python BulletPointCollector.py url` where `url` is the url to the thread you would like to collect the bullet points from. -------------------------------------------------------------------------------- /ChangeFlairBot/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt -------------------------------------------------------------------------------- /ChangeFlairBot/ChangeFlairBot.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to change the flair of all posts in a subreddit 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import OAuth2Util 8 | 9 | # ### USER CONFIGURATION ### # 10 | 11 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 12 | USERAGENT = "" 13 | 14 | # The name of the subreddit to operate on. The bot has to be a mod there. 15 | SUBREDDIT = "" 16 | 17 | # The old and new flair text and css class. Set to None to use a wildcard. 18 | OLD_FLAIR_TEXT = "Question" 19 | OLD_FLAIR_CSS = "question" 20 | NEW_FLAIR_TEXT = "Question | Answered" 21 | NEW_FLAIR_CSS = "questionan" 22 | 23 | # Set to True if you only want to see how many posts would be altered 24 | ONLY_TEST = False 25 | 26 | # ### END USER CONFIGURATION ### # 27 | 28 | try: 29 | # A file containing data for global constants. 30 | import bot 31 | for k in dir(bot): 32 | if k.upper() in globals(): 33 | globals()[k.upper()] = getattr(bot, k) 34 | except ImportError: 35 | pass 36 | 37 | # main procedure 38 | def run_bot(): 39 | r = praw.Reddit(USERAGENT) 40 | o = OAuth2Util.OAuth2Util(r) 41 | o.refresh() 42 | 43 | sub = r.get_subreddit(SUBREDDIT) 44 | 45 | print("Start bot for subreddit", SUBREDDIT) 46 | print("Will replace flair \"{0}\" with \"{1}\"".format(OLD_FLAIR_TEXT, NEW_FLAIR_TEXT)) 47 | 48 | try: 49 | last_element = None 50 | posts = sub.get_new(limit=100) 51 | found_new_post = True 52 | changed = 0 53 | active_page = 0 54 | while found_new_post: 55 | active_page += 1 56 | print("Search Page", active_page) 57 | found_new_post = False 58 | 59 | for post in posts: 60 | found_new_post = True 61 | 62 | if (post.link_flair_css_class == OLD_FLAIR_CSS or not OLD_FLAIR_CSS) and (post.link_flair_text == OLD_FLAIR_TEXT or not OLD_FLAIR_TEXT): 63 | if ONLY_TEST: 64 | print ("would change flair") 65 | else: 66 | print("change flair") 67 | post.set_flair(NEW_FLAIR_TEXT, NEW_FLAIR_CSS) 68 | 69 | changed += 1 70 | last_element = post.name 71 | posts = sub.get_new(limit=100, params={"after" : last_element}) 72 | 73 | print("changed", changed, "posts") 74 | 75 | except KeyboardInterrupt: 76 | pass 77 | except Exception as e: 78 | print("Exception", e) 79 | 80 | 81 | if __name__ == "__main__": 82 | if not USERAGENT: 83 | print("missing useragent") 84 | elif not SUBREDDIT: 85 | print("missing subreddit") 86 | elif not OLD_FLAIR_CSS and not OLD_FLAIR_TEXT: 87 | print("old flair not set") 88 | else: 89 | run_bot() 90 | -------------------------------------------------------------------------------- /ChangeFlairBot/README.md: -------------------------------------------------------------------------------- 1 | # Change Flair Bot 2 | A bot to change all link flairs from an old flair to a new flair in a subreddit. -------------------------------------------------------------------------------- /ChangeFlairBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=modflair 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /ELOBot/.gitignore: -------------------------------------------------------------------------------- 1 | elo.txt 2 | done.txt 3 | progress.txt 4 | oauth.txt -------------------------------------------------------------------------------- /ELOBot/ELOBot.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to track elo ratings. 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import logging 9 | import logging.handlers 10 | import re 11 | import OAuth2Util 12 | 13 | # ### USER CONFIGURATION ### # 14 | 15 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 16 | USERAGENT = "" 17 | 18 | # The name of the subreddit to post to. e.g. "funny" 19 | SUBREDDIT = "" 20 | 21 | # The time in seconds the bot should sleep until it checks again. 22 | SLEEP = 60 23 | 24 | # The string the bot looks for 25 | BOTCALLSTRING = "!elo" 26 | 27 | # The commands the bot understands. 0: report game result; 1: confirm game result 28 | BOTACTIONS = ["game", "confirm"] 29 | 30 | # The text that should be used to ask for confirmation. {0} will be replaced by the users name 31 | PLEASE_CONFIRM_TEXT = "/u/{0}, please confirm that this result is correct by replying \"" + BOTCALLSTRING + " " + BOTACTIONS[1] + "\" to the original comment." 32 | 33 | # The text that should be used to confirm the elo change. {0} will be the name of the winner, {1} his new elo. {2} will be the name of the loser, {3} his new elo. 34 | CONFIRMATION_TEXT = "ELO ranking changed.\n\n/u/{0}: {1}\n\n/u/{2}: {3}" 35 | 36 | # The text the bot should post if a user wants to play with itself 37 | BOT_ERROR_SAME_USER = "You can't play with yourself. Well yeah, not here." 38 | 39 | # The signature the bot adds to every comment he makes 40 | BOT_SIGNATURE = "\n\n---\n\n^I'm ^a ^bot. ^Use ^\"" + BOTCALLSTRING + " ^" + BOTACTIONS[0] + " ^winner_name ^loser_name\" ^to ^report ^a ^finished ^game." 41 | 42 | #The flair the users get. {0} is replaced by the actual elo rating 43 | FLAIR_TEXT = "rating: {0}" 44 | 45 | # ### END USER CONFIGURATION ### # 46 | 47 | # ### ELO CONFIGURATION ### # 48 | # based on http://en.wikipedia.org/wiki/Elo_rating_system#Theory 49 | 50 | ELO_INITIAL_SCORE = 1000 51 | ELO_MAX_DIFFERENCE = 400 52 | ELO_MAX_ADJUSTMENT = 20 53 | 54 | # ### END ELO CONFIGURATION ### # 55 | 56 | # ### BOT CONFIGURATION ### # 57 | ELO_CONFIGFILE = "elo.txt" 58 | PROGRESS_CONFIGFILE = "progress.txt" 59 | DONE_CONFIGFILE = "done.txt" 60 | # ### END BOT CONFIGURATION ### # 61 | 62 | # ### LOGGING CONFIGURATION ### # 63 | LOG_LEVEL = logging.INFO 64 | LOG_FILENAME = "bot.log" 65 | LOG_FILE_BACKUPCOUNT = 5 66 | LOG_FILE_MAXSIZE = 1024 * 256 67 | # ### END LOGGING CONFIGURATION ### # 68 | 69 | # ### EXTERNAL CONFIG FILE ### # 70 | try: 71 | # A file containing data for global constants. 72 | import bot 73 | for k in dir(bot): 74 | if k.upper() in globals(): 75 | globals()[k.upper()] = getattr(bot, k) 76 | except ImportError: 77 | pass 78 | # ### END EXTERNAL CONFIG FILE ### # 79 | 80 | # ### LOGGING SETUP ### # 81 | log = logging.getLogger("bot") 82 | log.setLevel(LOG_LEVEL) 83 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 84 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 85 | log_stderrHandler = logging.StreamHandler() 86 | log_stderrHandler.setFormatter(log_formatter) 87 | log.addHandler(log_stderrHandler) 88 | if LOG_FILENAME is not None: 89 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 90 | log_fileHandler.setFormatter(log_formatter_file) 91 | log.addHandler(log_fileHandler) 92 | # ### END LOGGING SETUP ### # 93 | 94 | BOTCALLRE = re.compile(re.escape(BOTCALLSTRING.lower()) + " (" + "|".join([re.escape(a.lower()) for a in BOTACTIONS]) + ")(?: (?:\/u\/)?(\S*) (?:\/u\/)?(\S*))?") 95 | 96 | def read_config_elo(): 97 | elo = {} 98 | try: 99 | with open(ELO_CONFIGFILE, "r") as f: 100 | for line in f: 101 | parts = line.split("\t") 102 | elo[parts[0].strip()] = int(parts[1]) 103 | except OSError: 104 | log.info("%s not found.", ELO_CONFIGFILE) 105 | return elo 106 | 107 | def write_config_elo(elo): 108 | with open(ELO_CONFIGFILE, "w") as f: 109 | for key in elo: 110 | f.write("{0}\t{1}\n".format(key, str(elo[key]))) 111 | 112 | def read_config_progress(): 113 | progress = {} 114 | try: 115 | with open(PROGRESS_CONFIGFILE, "r") as f: 116 | for line in f: 117 | parts = line.strip().split("\t") 118 | progress[parts[0]] = [[parts[1], parts[2].lower() == "true"], [parts[3], parts[4].lower() == "true"]] 119 | except OSError: 120 | log.info("%s not found.", PROGRESS_CONFIGFILE) 121 | return progress 122 | 123 | def write_config_progress(progress): 124 | with open(PROGRESS_CONFIGFILE, "w") as f: 125 | for key in progress: 126 | f.write("{0}\t{1}\t{2}\t{3}\t{4}\n".format(key, progress[key][0][0], str(progress[key][0][1]), progress[key][1][0], str(progress[key][1][1]))) 127 | 128 | def read_config_done(): 129 | done = set() 130 | try: 131 | with open(DONE_CONFIGFILE, "r") as f: 132 | for line in f: 133 | if line.strip(): 134 | done.add(line.strip()) 135 | except OSError: 136 | log.info("%s not found.", DONE_CONFIGFILE) 137 | return done 138 | 139 | def write_config_done(done): 140 | with open(DONE_CONFIGFILE, "w") as f: 141 | for d in done: 142 | if d: 143 | f.write(d + "\n") 144 | 145 | def write_all_config(elo, progress, done): 146 | write_config_done(done) 147 | write_config_elo(elo) 148 | write_config_progress(progress) 149 | 150 | def get_new_elo(winner_elo, loser_elo): 151 | diff = (loser_elo - winner_elo) 152 | if abs(diff) > ELO_MAX_DIFFERENCE: 153 | diff = ELO_MAX_DIFFERENCE * (1 if diff > 0 else -1) 154 | e_a = 1/(1+10**(diff/ELO_MAX_DIFFERENCE)) 155 | e_b = 1/(1+10**(-diff/ELO_MAX_DIFFERENCE)) 156 | new_winner_elo = winner_elo + ELO_MAX_ADJUSTMENT * (1 - e_a) 157 | new_loser_elo = loser_elo + ELO_MAX_ADJUSTMENT * (0 - e_b) 158 | return (int(new_winner_elo), int(new_loser_elo)) 159 | 160 | def set_new_elo(winner, loser, elo, sub): 161 | if winner == loser: 162 | return 163 | if winner not in elo: 164 | elo[winner] = ELO_INITIAL_SCORE 165 | if loser not in elo: 166 | elo[loser] = ELO_INITIAL_SCORE 167 | elo[winner], elo[loser] = get_new_elo(elo[winner], elo[loser]) 168 | try: 169 | sub.set_flair(winner, FLAIR_TEXT.format(str(elo[winner]))) 170 | sub.set_flair(loser, FLAIR_TEXT.format(str(elo[loser]))) 171 | except praw.errors.ModeratorRequired: 172 | log.warning("You have to be mod to set flair") 173 | 174 | # main procedure 175 | def run_bot(): 176 | r = praw.Reddit(USERAGENT) 177 | o = OAuth2Util.OAuth2Util(r) 178 | o.refresh() 179 | 180 | sub = r.get_subreddit(SUBREDDIT) 181 | 182 | log.info("Start bot for subreddit %s", SUBREDDIT) 183 | 184 | done = read_config_done() 185 | elo = read_config_elo() 186 | progress = read_config_progress() 187 | 188 | while True: 189 | try: 190 | o.refresh() 191 | sub.refresh() 192 | log.info("check comments") 193 | for comment in sub.get_comments(): 194 | if comment.author.name == r.get_me().name: 195 | continue 196 | match = BOTCALLRE.search(comment.body.lower()) 197 | if match: 198 | # game finished 199 | if match.group(1).lower() == BOTACTIONS[0]: 200 | if comment.name not in progress and comment.name not in done: 201 | log.info("register new game: %s", match.group(0)) 202 | if match.group(2).lower() == match.group(3).lower(): 203 | comment.reply(BOT_ERROR_SAME_USER + BOT_SIGNATURE) 204 | done.add(comment.name) 205 | log.info("Same user!") 206 | continue 207 | 208 | progress[comment.name] = [[match.group(2).lower(), match.group(2).lower() == comment.author.name.lower()], [match.group(3).lower(), match.group(3).lower() == comment.author.name.lower()]] 209 | 210 | for i in range(2): 211 | if not progress[comment.name][i][1]: 212 | comment.reply(PLEASE_CONFIRM_TEXT.format(progress[comment.name][i][0]) + BOT_SIGNATURE) 213 | log.info("%s has to confirm", progress[comment.name][i][0]) 214 | 215 | # confirmation 216 | if match.group(1).lower() == BOTACTIONS[1]: 217 | if comment.parent_id in progress: 218 | for i in range(2): 219 | if comment.author.name.lower() == progress[comment.parent_id][i][0]: 220 | progress[comment.parent_id][i][1] = True 221 | log.info("found confirmation for %s", comment.author.name) 222 | 223 | if progress[comment.parent_id][0][1] and progress[comment.parent_id][1][1]: 224 | set_new_elo(progress[comment.parent_id][0][0], progress[comment.parent_id][1][0], elo, sub) 225 | conf = CONFIRMATION_TEXT.format(progress[comment.parent_id][0][0], elo[progress[comment.parent_id][0][0]], progress[comment.parent_id][1][0], elo[progress[comment.parent_id][1][0]]) 226 | done.add(comment.parent_id) 227 | del progress[comment.parent_id] 228 | parent = r.get_info(thing_id=comment.parent_id) 229 | parent.reply(conf + BOT_SIGNATURE) 230 | 231 | log.info("updated elo") 232 | 233 | write_all_config(elo, progress, done) 234 | 235 | # Allows the bot to exit on ^C, all other exceptions are ignored 236 | except KeyboardInterrupt: 237 | break 238 | except Exception as e: 239 | log.error("Exception %s", e, exc_info=True) 240 | 241 | write_all_config(elo, progress, done) 242 | log.info("sleep for %s s", SLEEP) 243 | time.sleep(SLEEP) 244 | 245 | write_all_config(elo, progress, done) 246 | 247 | 248 | if __name__ == "__main__": 249 | if not USERAGENT: 250 | log.error("missing useragent") 251 | elif not SUBREDDIT: 252 | log.error("missing subreddit") 253 | else: 254 | run_bot() 255 | -------------------------------------------------------------------------------- /ELOBot/README.md: -------------------------------------------------------------------------------- 1 | # ELO Bot 2 | A bot to keep track of users elo in game subreddits. 3 | 4 | Usage: 5 | 6 | * Two user play against each other a game 7 | * Once they finished, one of them makes somewhere in the subreddit a comment with `!elo game /u/winner_name /u/loser_name` 8 | * The bot will answer with a message, asking the other player for confirmation 9 | * The other user replies to the original message with `!elo confirm` 10 | * The bot will calculate the new elo and change the flair accordingly -------------------------------------------------------------------------------- /ELOBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=identity,read,submit,modflair 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /EMailNotification/.gitignore: -------------------------------------------------------------------------------- 1 | done.txt 2 | oauth.txt -------------------------------------------------------------------------------- /EMailNotification/EMailNotification.py: -------------------------------------------------------------------------------- 1 | """ 2 | Writes an email if some rule is satisfied 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import smtplib 9 | import logging 10 | import logging.handlers 11 | import OAuth2Util 12 | 13 | # ### USER CONFIGURATION ### # 14 | 15 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 16 | USERAGENT = "" 17 | 18 | # The time in seconds the bot should sleep until it checks again. 19 | SLEEP = 60 20 | 21 | # The number of seconds the age of a post can be off and is still seen as within the timespan (e.g. if 20 ups in 20 minutes are searched, with a buffer of 5 minutes a post with 20 ups which is 25 minutes old will still be considered) 22 | AGE_BUFFER = 10*60 23 | 24 | # Hostname of the smtp server to use 25 | SMTP_HOST = "smtp.gmail.com" 26 | 27 | # Port of the smtp server to use 28 | SMTP_PORT = 587 29 | 30 | # EMail address to use as sender 31 | SMTP_FROM = "me@example.com" 32 | 33 | # Username to login on the smtp server 34 | SMTP_USERNAME = "me@example.com" 35 | 36 | # Password to login on the smtp server 37 | SMTP_PASSWORD = "123" 38 | 39 | # Subject line of the message for the SubNewPost rule. {0} will be replaced by the Subreddit name 40 | SUBJECT_SUBNEWPOST_TEXT = "New Post in {0}" 41 | 42 | # Subject line of the message for the UserNewPost rule. {0} will be replaced by the user name 43 | SUBJECT_USERNEWPOST_TEXT = "New Post from {0}" 44 | 45 | # Subject line of the message for the UserInSubNewPost rule. {0} will be replaced by the Subreddit name, {1} by the user name 46 | SUBJECT_USERINSUBNEWPOST_TEXT = "New Post in {0} from {1}" 47 | 48 | # Subject line of the message for the SubNewComment rule. {0} will be replaced by the Subreddit name 49 | SUBJECT_SUBNEWCOMMENT_TEXT = "New Comment in {0}" 50 | 51 | # Subject line of the message for the UserNewComment rule. {0} will be replaced by the user name 52 | SUBJECT_USERNEWCOMMENT_TEXT = "New Comment from {0}" 53 | 54 | # Subject line of the message for the UserInSubNewComment rule. {0} will be replaced by the Subreddit name, {1} by the user name 55 | SUBJECT_USERINSUBNEWCOMMENT_TEXT = "New Comment in {0} from {1}" 56 | 57 | # Subject line of the message for the VotesInTime rule. {0} will be replaced by the Subreddit name 58 | SUBJECT_VOTESINTIME_TEXT = "New Post in {0} satisfying rule" 59 | 60 | # Body of the message. {0} will be replaced by the permalink, {1} by the title, {2} will be replaced by the URL, {3} by selftext 61 | BODY_TEXT = "Comments: {0}\n\nTitle: {1}\n\nURL: {2}\n\nSelftext: {3}" 62 | 63 | # If true, no messages will be sent. Used to initialize a new Subreddit / User so you don't get a message for every post already existing. 64 | BUILD_DONE_LIST = False 65 | # ### END USER CONFIGURATION ### # 66 | 67 | # ### BOT CONFIGURATION ### # 68 | DONE_CONFIGFILE = "done.txt" 69 | RULES_CONFIGFILE = "rules.txt" 70 | # ### END BOT CONFIGURATION ### # 71 | 72 | # ### LOGGING CONFIGURATION ### # 73 | LOG_LEVEL = logging.INFO 74 | LOG_FILENAME = "bot.log" 75 | LOG_FILE_BACKUPCOUNT = 5 76 | LOG_FILE_MAXSIZE = 1024 * 256 77 | # ### END LOGGING CONFIGURATION ### # 78 | 79 | # ### EXTERNAL CONFIG FILE ### # 80 | try: 81 | # A file containing data for global constants. 82 | import bot 83 | for k in dir(bot): 84 | if k.upper() in globals(): 85 | globals()[k.upper()] = getattr(bot, k) 86 | except ImportError: 87 | pass 88 | # ### END EXTERNAL CONFIG FILE ### # 89 | 90 | # ### LOGGING SETUP ### # 91 | log = logging.getLogger("bot") 92 | log.setLevel(LOG_LEVEL) 93 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 94 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 95 | log_stderrHandler = logging.StreamHandler() 96 | log_stderrHandler.setFormatter(log_formatter) 97 | log.addHandler(log_stderrHandler) 98 | if LOG_FILENAME is not None: 99 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 100 | log_fileHandler.setFormatter(log_formatter_file) 101 | log.addHandler(log_fileHandler) 102 | # ### END LOGGING SETUP ### # 103 | 104 | def read_config_rules(): 105 | rules = [] 106 | try: 107 | with open(RULES_CONFIGFILE, "r") as f: 108 | for line in f: 109 | if line.startswith("#"): 110 | continue 111 | rules.append([w.strip().lower() for w in line.split("\t")]) 112 | except OSError: 113 | log.error("%s not found.", RULES_CONFIGFILE) 114 | return rules 115 | 116 | 117 | def read_config_done(): 118 | done = set() 119 | try: 120 | with open(DONE_CONFIGFILE, "r") as f: 121 | for line in f: 122 | if line.strip(): 123 | done.add(line.strip()) 124 | except OSError: 125 | log.info("%s not found.", DONE_CONFIGFILE) 126 | return done 127 | 128 | def write_config_done(done): 129 | with open(DONE_CONFIGFILE, "w") as f: 130 | for d in done: 131 | if d: 132 | f.write(d + "\n") 133 | 134 | def send_email(recipient, subject, message): 135 | smtp = smtplib.SMTP(host=SMTP_HOST, port=SMTP_PORT) 136 | smtp.starttls() 137 | if SMTP_USERNAME and SMTP_PASSWORD: 138 | try: 139 | smtp.login(SMTP_USERNAME, SMTP_PASSWORD) 140 | except smtplib.SMTPAuthenticationError: 141 | log.error("Wrong email password") 142 | 143 | try: 144 | smtp.sendmail(SMTP_FROM, recipient, "Subject: {0}\n\n{1}".format(subject, message)) 145 | except Exception as e: 146 | log.error("Error while sending mail, %s", e, exc_info=True) 147 | smtp.quit() 148 | 149 | def send_message(r, recipient, subject, message): 150 | if recipient.startswith("/u/"): 151 | if not r.is_oauth_session(): 152 | log.warning("Recipient is Reddit user, but you are not logged in. Rule ignored.") 153 | return 154 | r.send_message(r.get_redditor(recipient[3:]), subject, message) 155 | else: 156 | send_email(recipient, subject, message) 157 | 158 | # main procedure 159 | def run_bot(): 160 | r = praw.Reddit(USERAGENT) 161 | o = OAuth2Util.OAuth2Util(r) 162 | o.refresh() 163 | 164 | log.info("Start bot") 165 | 166 | done = read_config_done() 167 | 168 | while True: 169 | try: 170 | o.refresh() 171 | rules = read_config_rules() 172 | old_done = done[:] 173 | for rule in rules: 174 | log.info("process rule %s", rule[1]) 175 | if rule[0].startswith("/u/") and not r.is_oauth_session(): 176 | log.warning("Recipient is Reddit user, but you are not logged in. Rule ignored.") 177 | continue 178 | if rule[1] == "votesintime": 179 | sub = r.get_subreddit(rule[2]) 180 | age = int(rule[3]) 181 | ups = int(rule[4]) 182 | 183 | for post in sub.get_new(limit=100): 184 | diff = abs((time.time() - post.created_utc) - age) 185 | if diff <= AGE_BUFFER and post.score >= ups: 186 | if post.name in old_done: 187 | continue 188 | if not BUILD_DONE_LIST: 189 | send_message(r, rule[0], SUBJECT_VOTESINTIME_TEXT.format(sub.display_name), BODY_TEXT.format(post.permalink, post.title, post.url, post.selftext)) 190 | done.add(post.name) 191 | log.info("found new post for rule %s", rule[1]) 192 | 193 | elif rule[1] == "usernewpost": 194 | redditor = r.get_redditor(rule[2]) 195 | for post in redditor.get_submitted(limit=100): 196 | if post.name in old_done: 197 | continue 198 | if not BUILD_DONE_LIST: 199 | send_message(r, rule[0], SUBJECT_USERNEWPOST_TEXT.format(redditor.name), BODY_TEXT.format(post.permalink, post.title, post.url, post.selftext)) 200 | done.add(post.name) 201 | log.info("found new post for rule %s", rule[1]) 202 | 203 | elif rule[1] == "subnewpost": 204 | sub = r.get_subreddit(rule[2]) 205 | for post in sub.get_new(limit=100): 206 | if post.name in old_done: 207 | continue 208 | if not BUILD_DONE_LIST: 209 | send_message(r, rule[0], SUBJECT_SUBNEWPOST_TEXT.format(sub.display_name), BODY_TEXT.format(post.permalink, post.title, post.url, post.selftext)) 210 | done.add(post.name) 211 | log.info("found new post for rule %s", rule[1]) 212 | 213 | elif rule[1] == "userinsubnewpost": 214 | redditor = r.get_redditor(rule[2]) 215 | for post in redditor.get_submitted(limit=100): 216 | if post.subreddit.display_name.lower() != rule[3] or post.name in old_done: 217 | continue 218 | if not BUILD_DONE_LIST: 219 | send_message(r, rule[0], SUBJECT_USERINSUBNEWPOST_TEXT.format(post.subreddit.display_name, redditor.name), BODY_TEXT.format(post.permalink, post.title, post.url, post.selftext)) 220 | done.add(post.name) 221 | log.info("found new post for rule %s", rule[1]) 222 | 223 | elif rule[1] == "usernewcomment": 224 | redditor = r.get_redditor(rule[2]) 225 | for comment in redditor.get_comments(limit=100): 226 | if comment.name in old_done: 227 | continue 228 | if not BUILD_DONE_LIST: 229 | send_message(r, rule[0], SUBJECT_USERNEWCOMMENT_TEXT.format(redditor.name), BODY_TEXT.format(comment.permalink, comment.link_title, comment.link_url, comment.body)) 230 | done.add(comment.name) 231 | log.info("found new comment for rule %s", rule[1]) 232 | 233 | elif rule[1] == "subnewcomment": 234 | sub = r.get_subreddit(rule[2]) 235 | for comment in sub.get_comments(limit=100): 236 | if comment.name in old_done: 237 | continue 238 | if not BUILD_DONE_LIST: 239 | send_message(r, rule[0], SUBJECT_SUBNEWCOMMENT_TEXT.format(sub.display_name), BODY_TEXT.format(comment.permalink, comment.link_title, comment.link_url, comment.body)) 240 | done.add(comment.name) 241 | log.info("found new comment for rule %s", rule[1]) 242 | 243 | elif rule[1] == "userinsubnewcomment": 244 | redditor = r.get_redditor(rule[2]) 245 | for comment in redditor.get_comments(limit=100): 246 | if comment.subreddit.display_name.lower() != rule[3] or comment.name in old_done: 247 | continue 248 | if not BUILD_DONE_LIST: 249 | send_message(r, rule[0], SUBJECT_USERINSUBNEWCOMMENT_TEXT.format(comment.subreddit.display_name, redditor.name), BODY_TEXT.format(comment.permalink, comment.link_title, comment.link_url, comment.body)) 250 | done.add(comment.name) 251 | log.info("found new comment for rule %s", rule[1]) 252 | 253 | write_config_done(done) 254 | 255 | # Allows the bot to exit on ^C, all other exceptions are ignored 256 | except KeyboardInterrupt: 257 | break 258 | except Exception as e: 259 | log.error("Exception %s", e, exc_info=True) 260 | 261 | write_config_done(done) 262 | log.info("sleep for %s s", SLEEP) 263 | time.sleep(SLEEP) 264 | 265 | write_config_done(done) 266 | 267 | 268 | if __name__ == "__main__": 269 | if not USERAGENT: 270 | log.error("missing useragent") 271 | else: 272 | run_bot() 273 | -------------------------------------------------------------------------------- /EMailNotification/README.md: -------------------------------------------------------------------------------- 1 | # EMailNotification 2 | Writes an email if some rule is satisfied. 3 | 4 | You can specify as many rules as you want in the file `rules.txt`, one rule per line. For each rule, specify the parameters, separated by one tab. The following rules are available: 5 | 6 | - `recipient VotesInTime subreddit age score` This rule will trigger when a post in `/r/subreddit` gets `score` upvotes within `age` seconds 7 | - `recipient UserNewPost user` This rule will trigger when the user `/u/user` submits a new post 8 | - `recipient SubNewPost subreddit` This rule will trigger when a new post is submitted to `/r/subreddit` 9 | - `recipient UserInSubNewPost user subreddit` This rule will trigger when the user `/u/user` submits a new post to `/r/subreddit` 10 | - `recipient UserNewComment user` This rule will trigger when user `/u/user` submits a new comment 11 | - `recipient SubNewComment subreddit` This rule will trigger when a new comment is submitted to `/r/subreddit` 12 | - `recipient UserInSubNewComment user subreddit` This rule will trigger when the user `/u/user` submits a new post to `/r/subreddit` 13 | 14 | As a `recipient` you can use either a reddit user in the format `/u/user` or an email address. 15 | 16 | The rules are read after every cycle, so no need to restart the bot if you want to add / remove a rule. 17 | 18 | To prevent your inbox from overflowing you will want to run the bot with the flag `BUILD_DONE_LIST = True` set and then after he built his list restart the bot with the flag unset. 19 | -------------------------------------------------------------------------------- /EMailNotification/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=identity,read,privatemessages,history 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /EMailNotification/rules.txt: -------------------------------------------------------------------------------- 1 | me@example.com VotesInTime askreddit 1500 5 2 | me@example.com UserNewPost unidanx 3 | /u/user SubNewPost requestabot 4 | /u/user UserInSubNewPost unidanx test 5 | me@example.com UserNewComment unidanx 6 | /u/user SubNewComment requestabot 7 | /u/user UserInSubNewComment unidanx requestabot 8 | -------------------------------------------------------------------------------- /EvoCreoBot/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt 2 | done.txt -------------------------------------------------------------------------------- /EvoCreoBot/EvoCreoBot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | A bot that posts a link to a wiki (for /r/evocreo) 5 | Written by /u/SmBe19 6 | """ 7 | 8 | import praw 9 | import re 10 | import time 11 | import OAuth2Util 12 | 13 | # ### USER CONFIGURATION ### # 14 | 15 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 16 | USERAGENT = "" 17 | 18 | # The name of the subreddit to post to. e.g. "funny" 19 | SUBREDDIT = "" 20 | 21 | # The time in seconds the bot should sleep until it checks again. 22 | SLEEP = 60 23 | 24 | # The regex used to find comments to reply 25 | COMMENT_REGEX = re.compile(r"\{(.*?)\} is my favorite Creo\.") 26 | 27 | ANSWER = "More information about [{0}](http://evocreo.wikia.com/wiki/{0})." 28 | 29 | # ### END USER CONFIGURATION ### # 30 | 31 | # ### BOT CONFIGURATION ### # 32 | DONE_CONFIGFILE = "done.txt" 33 | # ### END BOT CONFIGURATION ### # 34 | 35 | try: 36 | # A file containing data for global constants. 37 | import bot 38 | for k in dir(bot): 39 | if k.upper() in globals(): 40 | globals()[k.upper()] = getattr(bot, k) 41 | except ImportError: 42 | pass 43 | 44 | def read_config_done(): 45 | done = set() 46 | try: 47 | with open(DONE_CONFIGFILE, "r") as f: 48 | for line in f: 49 | if line.strip(): 50 | done.add(line.strip()) 51 | except OSError: 52 | print(DONE_CONFIGFILE, "not found.") 53 | return done 54 | 55 | def write_config_done(done): 56 | with open(DONE_CONFIGFILE, "w") as f: 57 | for d in done: 58 | if d: 59 | f.write(d + "\n") 60 | 61 | # main procedure 62 | def run_bot(): 63 | r = praw.Reddit(USERAGENT) 64 | o = OAuth2Util.OAuth2Util(r) 65 | o.refresh() 66 | sub = r.get_subreddit(SUBREDDIT) 67 | 68 | print("Start bot for subreddit", SUBREDDIT) 69 | 70 | done = read_config_done() 71 | 72 | while True: 73 | try: 74 | o.refresh() 75 | sub.refresh() 76 | 77 | for comment in sub.get_comments(): 78 | if comment.name not in done: 79 | answer = "" 80 | for match in COMMENT_REGEX.finditer(comment.body): 81 | answer += ANSWER.format(match.group(1)) + "\n" 82 | 83 | if len(answer) > 0: 84 | print("reply") 85 | comment.reply(answer) 86 | done.add(comment.name) 87 | 88 | # Allows the bot to exit on ^C, all other exceptions are ignored 89 | except KeyboardInterrupt: 90 | break 91 | except Exception as e: 92 | print("Exception", e) 93 | 94 | write_config_done(done) 95 | print("sleep for", SLEEP, "s") 96 | time.sleep(SLEEP) 97 | 98 | write_config_done(done) 99 | 100 | 101 | if __name__ == "__main__": 102 | if not USERAGENT: 103 | print("missing useragent") 104 | elif not SUBREDDIT: 105 | print("missing subreddit") 106 | else: 107 | run_bot() 108 | -------------------------------------------------------------------------------- /EvoCreoBot/README.md: -------------------------------------------------------------------------------- 1 | # EvoCreo Bot 2 | A bot that posts a link to a wiki (for http://reddit.com/r/evocreo). 3 | -------------------------------------------------------------------------------- /EvoCreoBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=submit,read 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /ForwardOrangered/.gitignore: -------------------------------------------------------------------------------- 1 | accounts.txt 2 | done.*.txt 3 | oauth.txt -------------------------------------------------------------------------------- /ForwardOrangered/ForwardOrangered.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to forward orangereds from one account to another account. 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import logging 9 | import logging.handlers 10 | import OAuth2Util 11 | 12 | # ### USER CONFIGURATION ### # 13 | 14 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 15 | USERAGENT = "" 16 | 17 | # The time in seconds the bot should sleep until it checks again. 18 | SLEEP = 60*60 19 | 20 | # ### END USER CONFIGURATION ### # 21 | 22 | # ### BOT CONFIGURATION ### # 23 | ACCOUNTS_CONFIGFILE = "accounts.txt" 24 | DONE_CONFIGFILE = "done.{0}.txt" 25 | # ### END BOT CONFIGURATION ### # 26 | 27 | # ### LOGGING CONFIGURATION ### # 28 | LOG_LEVEL = logging.INFO 29 | LOG_FILENAME = "bot.log" 30 | LOG_FILE_BACKUPCOUNT = 5 31 | LOG_FILE_MAXSIZE = 1024 * 256 32 | # ### END LOGGING CONFIGURATION ### # 33 | 34 | # ### EXTERNAL CONFIG FILE ### # 35 | try: 36 | # A file containing data for global constants. 37 | import bot 38 | for k in dir(bot): 39 | if k.upper() in globals(): 40 | globals()[k.upper()] = getattr(bot, k) 41 | except ImportError: 42 | pass 43 | # ### END EXTERNAL CONFIG FILE ### # 44 | 45 | # ### LOGGING SETUP ### # 46 | log = logging.getLogger("bot") 47 | log.setLevel(LOG_LEVEL) 48 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 49 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 50 | log_stderrHandler = logging.StreamHandler() 51 | log_stderrHandler.setFormatter(log_formatter) 52 | log.addHandler(log_stderrHandler) 53 | if LOG_FILENAME is not None: 54 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 55 | log_fileHandler.setFormatter(log_formatter_file) 56 | log.addHandler(log_fileHandler) 57 | # ### END LOGGING SETUP ### # 58 | 59 | def read_accounts_config(): 60 | accounts = [] 61 | try: 62 | with open(ACCOUNTS_CONFIGFILE) as f: 63 | for line in f: 64 | # username password forward_to reset_orangered active 65 | acc = line.split("\t") 66 | if len(acc) < 5: 67 | log.error("not enough info for account %s. Format is: username password forward_to reset_orangered active (with one tab between values)", acc[0]) 68 | 69 | if acc[4].strip().lower() == "true": 70 | r = praw.Reddit(USERAGENT) 71 | try: 72 | r.login(acc[0].strip(), acc[1].strip(), disable_warning=True) 73 | except praw.errors.InvalidUserPass: 74 | log.error("Wrong password for account %s", acc[0]) 75 | else: 76 | accounts.append((r, acc[2].strip(), acc[3].strip().lower() == "true")) 77 | 78 | except OSError: 79 | log.error("%s not found.", ACCOUNTS_CONFIGFILE) 80 | return accounts 81 | 82 | def read_config_done(account): 83 | done = set() 84 | try: 85 | with open(DONE_CONFIGFILE.format(account), "r") as f: 86 | for line in f: 87 | if line.strip(): 88 | done.add(line.strip()) 89 | except OSError: 90 | log.info("%s not found.", DONE_CONFIGFILE.format(account)) 91 | return done 92 | 93 | def write_config_done(done, account): 94 | with open(DONE_CONFIGFILE.format(account), "w") as f: 95 | for d in done: 96 | if d: 97 | f.write(d + "\n") 98 | 99 | 100 | # main procedure 101 | def run_bot(): 102 | r = praw.Reddit(USERAGENT) 103 | o = OAuth2Util.OAuth2Util(r) 104 | 105 | log.info("Start bot") 106 | 107 | while True: 108 | try: 109 | o.refresh() 110 | accounts = read_accounts_config() 111 | for account in accounts: 112 | try: 113 | log.info("check %s", account[0].user.name) 114 | message = "" 115 | message_count = 0 116 | done = read_config_done(account[0].user.name) 117 | for msg in account[0].get_unread(): 118 | if msg.name in done: 119 | continue 120 | if msg.context and msg.author: 121 | this_message = "Comment from /u/{0}. [Link]({1}?context=10000)\n\n".format(msg.author.name, msg.permalink) 122 | elif msg.author: 123 | this_message = "Message from /u/{0} ({1}).\n\n".format(msg.author.name, msg.subject) 124 | else: 125 | this_message = "Something from Someone.\n\n" 126 | for line in msg.body.split("\n"): 127 | this_message += "> " + line + "\n" 128 | if account[2]: 129 | msg.mark_as_read() 130 | message += "\n\n" + this_message 131 | message_count += 1 132 | done.add(msg.name) 133 | 134 | if message: 135 | message = "Summary for account /u/{0} ({1}):{2}".format(account[0].user.name, message_count, message) 136 | r.send_message(account[1], "Summary for account {0}: {1}".format(account[0].user.name, message_count), message) 137 | log.info("Message sent") 138 | 139 | write_config_done(done, account[0].user.name) 140 | except KeyboardInterrupt: 141 | raise 142 | except Exception as e: 143 | log.error("Exception %s", e, exc_info=True) 144 | 145 | except KeyboardInterrupt: 146 | break 147 | except Exception as e: 148 | log.error("Exception %s", e, exc_info=True) 149 | 150 | log.info("sleep for %s s", SLEEP) 151 | time.sleep(SLEEP) 152 | 153 | 154 | if __name__ == "__main__": 155 | if not USERAGENT: 156 | log.error("missing useragent") 157 | else: 158 | run_bot() 159 | -------------------------------------------------------------------------------- /ForwardOrangered/README.md: -------------------------------------------------------------------------------- 1 | # Forward Organgered 2 | A bot to forward orangereds from one account to another account. 3 | 4 | To configure the accounts to check, use the file `accounts.txt`, one account per line. The file is read after every cycle, so no need to restart the bot. 5 | 6 | For every account: `username password forward_to_account reset_orangered active` (with one tab between values) 7 | 8 | * username: the username of the account to check 9 | * password: the password to this account 10 | * forward_to_account: the account to send a message with a summary 11 | * reset_orangered: If reset_orangered is set, all forwarded messages will be marked as read. 12 | * active: If active is set to False, the account is ignored -------------------------------------------------------------------------------- /ForwardOrangered/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=identity,read,privatemessages 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /HeaderChangeBot/.gitignore: -------------------------------------------------------------------------------- 1 | header*.jpg 2 | oauth.txt -------------------------------------------------------------------------------- /HeaderChangeBot/HeaderChangeBot.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to change the header of a subreddit according a schedule 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import OAuth2Util 9 | 10 | # ### USER CONFIGURATION ### # 11 | 12 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 13 | USERAGENT = "" 14 | 15 | # The name of the subreddit to operate on. The bot has to be a mod there. 16 | SUBREDDIT = "" 17 | 18 | # ### END USER CONFIGURATION ### # 19 | 20 | # ### BOT CONFIGURATION ### # 21 | HEADERS_CONFIGFILE = "headers.txt" 22 | # ### END BOT CONFIGURATION ### # 23 | 24 | 25 | try: 26 | # A file containing data for global constants. 27 | import bot 28 | for k in dir(bot): 29 | if k.upper() in globals(): 30 | globals()[k.upper()] = getattr(bot, k) 31 | except ImportError: 32 | pass 33 | 34 | def read_headers_config(): 35 | headers = [] 36 | with open(HEADERS_CONFIGFILE, "r") as f: 37 | for line in f: 38 | parts = line.split("\t") 39 | headers.append((int(parts[0]), parts[1].strip())) 40 | headers.sort() 41 | return headers 42 | 43 | # main procedure 44 | def run_bot(): 45 | r = praw.Reddit(USERAGENT) 46 | o = OAuth2Util.OAuth2Util(r) 47 | o.refresh() 48 | sub = r.get_subreddit(SUBREDDIT) 49 | 50 | print("Start bot for subreddit", SUBREDDIT) 51 | 52 | while True: 53 | try: 54 | o.refresh() 55 | headers = read_headers_config() 56 | if len(headers) < 1: 57 | return 58 | 59 | next_header = headers[0] 60 | atime = time.localtime().tm_hour * 100 + time.localtime().tm_min 61 | for header in headers: 62 | if header[0] > atime: 63 | next_header = header 64 | break 65 | 66 | sleeptime = (next_header[0] % 100 - atime % 100) * 60 + (next_header[0] // 100 - atime // 100) * 3600 67 | if sleeptime < 0: 68 | sleeptime += 24*3600 69 | print("Now:", atime, "/ Sleep for", sleeptime, "s until", next_header[0]) 70 | time.sleep(sleeptime) 71 | 72 | sub.upload_image(next_header[1], header=True) 73 | print("Change header") 74 | 75 | except KeyboardInterrupt: 76 | break 77 | except Exception as e: 78 | print("Exception", e) 79 | 80 | 81 | if __name__ == "__main__": 82 | if not USERAGENT: 83 | print("missing useragent") 84 | elif not SUBREDDIT: 85 | print("missing subreddit") 86 | else: 87 | run_bot() 88 | -------------------------------------------------------------------------------- /HeaderChangeBot/README.md: -------------------------------------------------------------------------------- 1 | # Header Change Bot 2 | A Bot to change the header of a subreddit according a schedule. 3 | 4 | The schedule is located in the file `headers.txt`, one image per line. For each line specify the time in the format `hhmm` (e.g. `1642` would be 16:42) and the name of the image (e.g. `header1.jpg`), seperated by one tab. 5 | 6 | The schedule file is reread after every header change, so no need to restart the bot if the schedule changes (only if there is a scheduled change before the one the bot is at the moment waiting for). -------------------------------------------------------------------------------- /HeaderChangeBot/headers.txt: -------------------------------------------------------------------------------- 1 | 0800 header1.jpg 2 | 1200 header2.jpg 3 | 1800 header3.jpg -------------------------------------------------------------------------------- /HeaderChangeBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=read,modconfig 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Benjamin Schmid 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /ProxyBot/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt 2 | done.txt -------------------------------------------------------------------------------- /ProxyBot/ProxyBot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | A bot that posts comments / posts received by PM 5 | Written by /u/SmBe19 6 | """ 7 | 8 | import praw 9 | import praw.errors 10 | import time 11 | import logging 12 | import logging.handlers 13 | import OAuth2Util 14 | 15 | # ### USER CONFIGURATION ### # 16 | 17 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 18 | USERAGENT = "" 19 | 20 | # The time in seconds the bot should sleep until it checks again. 21 | SLEEP = 60*10 22 | 23 | # text that has to appear at the start of the message for a new self post 24 | COMMAND_SELF = "proxy#self" 25 | 26 | # text that has to appear at the start of the message for a new link post 27 | COMMAND_LINK = "proxy#link" 28 | 29 | # text that has to appear at the start of the message for a new toplevel comment 30 | COMMAND_TOP_COMMENT = "proxy#topcomment" 31 | 32 | # text that has to appear at the start of the message for a new comment 33 | COMMAND_COMMENT = "proxy#comment" 34 | 35 | # ### END USER CONFIGURATION ### # 36 | 37 | # ### BOT CONFIGURATION ### # 38 | DONE_CONFIGFILE = "done.txt" 39 | # ### END BOT CONFIGURATION ### # 40 | 41 | # ### LOGGING CONFIGURATION ### # 42 | LOG_LEVEL = logging.INFO 43 | LOG_FILENAME = "bot.log" 44 | LOG_FILE_BACKUPCOUNT = 5 45 | LOG_FILE_MAXSIZE = 1024 * 256 46 | # ### END LOGGING CONFIGURATION ### # 47 | 48 | # ### EXTERNAL CONFIG FILE ### # 49 | try: 50 | # A file containing data for global constants. 51 | import bot 52 | for k in dir(bot): 53 | if k.upper() in globals(): 54 | globals()[k.upper()] = getattr(bot, k) 55 | except ImportError: 56 | pass 57 | # ### END EXTERNAL CONFIG FILE ### # 58 | 59 | # ### LOGGING SETUP ### # 60 | log = logging.getLogger("bot") 61 | log.setLevel(LOG_LEVEL) 62 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 63 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 64 | log_stderrHandler = logging.StreamHandler() 65 | log_stderrHandler.setFormatter(log_formatter) 66 | log.addHandler(log_stderrHandler) 67 | if LOG_FILENAME is not None: 68 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 69 | log_fileHandler.setFormatter(log_formatter_file) 70 | log.addHandler(log_fileHandler) 71 | # ### END LOGGING SETUP ### # 72 | 73 | # ### DONE CONFIG FILE ### # 74 | def read_config_done(): 75 | done = set() 76 | try: 77 | with open(DONE_CONFIGFILE, "r") as f: 78 | for line in f: 79 | if line.strip(): 80 | done.add(line.strip()) 81 | except OSError: 82 | log.info("%s not found.", DONE_CONFIGFILE) 83 | return done 84 | 85 | def write_config_done(done): 86 | with open(DONE_CONFIGFILE, "w") as f: 87 | for d in done: 88 | if d: 89 | f.write(d + "\n") 90 | # ### END DONE CONFIG FILE ### # 91 | 92 | # ### MAIN PROCEDURE ### # 93 | def extract_body(r, pm, command, with_title=False): 94 | lines = [s.replace("\r", "") for s in pm.body.split("\n")] 95 | assert lines[0].lower().startswith(command), lines[0] 96 | destination = lines[0][len(command):].strip() 97 | 98 | start = 1 99 | title = None 100 | while start < len(lines) and len(lines[start]) < 1: 101 | start += 1 102 | if title is None and with_title and start < len(lines) and len(lines[start]) > 0: 103 | title = lines[start] 104 | start += 1 105 | 106 | if start >= len(lines): 107 | log.info("Command without body") 108 | return None 109 | 110 | lines = lines[start:] 111 | 112 | if with_title: 113 | return (destination, title, lines) 114 | else: 115 | return (destination, lines) 116 | 117 | def add_toplevel_comment(r, pm): 118 | body = extract_body(r, pm, COMMAND_TOP_COMMENT) 119 | if body is None: 120 | return 121 | 122 | url, lines = body 123 | sub = r.get_submission(url) 124 | sub.add_comment("\n".join(lines)) 125 | 126 | log.info("post new topcomment in %s", sub.subreddit.display_name) 127 | 128 | def add_comment(r, pm): 129 | body = extract_body(r, pm, COMMAND_COMMENT) 130 | if body is None: 131 | return 132 | 133 | url, lines = body 134 | sub = r.get_submission(url) 135 | if len(sub.comments) < 1: 136 | log.info("invalid comment url") 137 | return 138 | com = sub.comments[0] 139 | com.reply("\n".join(lines)) 140 | 141 | log.info("post new comment in %s", sub.subreddit.display_name) 142 | 143 | def add_self(r, pm): 144 | body = extract_body(r, pm, COMMAND_SELF, with_title=True) 145 | if body is None: 146 | return 147 | 148 | subreddit, title, lines = body 149 | sub = r.get_subreddit(subreddit) 150 | sub.submit(title=title, text="\n".join(lines)) 151 | 152 | log.info("post new self post in %s", subreddit) 153 | 154 | def add_link(r, pm): 155 | body = extract_body(r, pm, COMMAND_LINK, with_title=True) 156 | if body is None: 157 | return 158 | 159 | subreddit, title, lines = body 160 | sub = r.get_subreddit(subreddit) 161 | sub.submit(title=title, url=lines[0], resubmit=True) 162 | 163 | log.info("post new link post in %s", subreddit) 164 | 165 | def handle_pm(r, pm): 166 | bodylower = pm.body.strip().lower() 167 | if bodylower.startswith(COMMAND_SELF): 168 | add_self(r, pm) 169 | elif bodylower.startswith(COMMAND_LINK): 170 | add_link(r, pm) 171 | elif bodylower.startswith(COMMAND_COMMENT): 172 | add_comment(r, pm) 173 | elif bodylower.startswith(COMMAND_TOP_COMMENT): 174 | add_toplevel_comment(r, pm) 175 | else: 176 | return False 177 | return True 178 | 179 | def check_inbox(r, done): 180 | log.info("check inbox") 181 | for pm in r.get_unread(): 182 | if pm.name in done: 183 | continue 184 | try: 185 | if handle_pm(r, pm): 186 | pm.mark_as_read() 187 | done.add(pm.name) 188 | except praw.errors.RateLimitExceeded as e: 189 | log.info("Hit rate limit: %s", e.message) 190 | 191 | def run_bot(): 192 | r = praw.Reddit(USERAGENT) 193 | o = OAuth2Util.OAuth2Util(r) 194 | o.refresh() 195 | 196 | log.info("Start bot") 197 | 198 | done = read_config_done() 199 | 200 | while True: 201 | try: 202 | o.refresh() 203 | check_inbox(r, done) 204 | 205 | # Allows the bot to exit on ^C, all other exceptions are ignored 206 | except KeyboardInterrupt: 207 | break 208 | except Exception as e: 209 | log.error("Exception %s", e, exc_info=True) 210 | 211 | write_config_done(done) 212 | log.info("sleep for %s s", SLEEP) 213 | time.sleep(SLEEP) 214 | 215 | write_config_done(done) 216 | # ### END MAIN PROCEDURE ### # 217 | 218 | # ### START BOT ### # 219 | if __name__ == "__main__": 220 | if not USERAGENT: 221 | log.error("missing useragent") 222 | else: 223 | run_bot() 224 | # ### END START BOT ### # 225 | -------------------------------------------------------------------------------- /ProxyBot/README.md: -------------------------------------------------------------------------------- 1 | # Proxy Bot 2 | Posts comments / posts received by PM in a specified post / subreddit. 3 | 4 | To post something use the following format, depending on what you want to post. Each format starts with one or two lines with headers (what to post, where to post, \[title of post\]). 5 | 6 | ## Self Post 7 | 8 | Add the text you want to be posted as body 9 | 10 | proxy#self subreddit 11 | 12 | Fancy Title 13 | 14 | This is the text, 15 | 16 | it can be many lines long! 17 | 18 | Even three? Yes!!! 19 | 20 | ## Link Post 21 | 22 | Add the link you want to be posted as body 23 | 24 | proxy#link subreddit 25 | 26 | Fancy Title 27 | 28 | http://fancy.example.org 29 | 30 | ## Toplevel Comment 31 | 32 | Use a link to the submission you want to post a toplevel comment to. 33 | 34 | proxy#topcomment https://www.reddit.com/r/RequestABot/comments/4r3v8i/rneedamod_bot_to_pull_usernames_to_the_wiki/ 35 | 36 | A long comment, 37 | 38 | that can span several lines!!! 39 | 40 | ## Comment 41 | 42 | Use a permalink to the comment you want to reply to. 43 | 44 | proxy#comment https://www.reddit.com/r/RequestABot/comments/4r3v8i/rneedamod_bot_to_pull_usernames_to_the_wiki/d51tarb 45 | 46 | A long comment, 47 | 48 | that can span several lines!!! 49 | -------------------------------------------------------------------------------- /ProxyBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=identity,submit,privatemessages 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RedditBots 2 | Reddit Bots by [/u/SmBe19](http://www.reddit.com/u/SmBe19) 3 | 4 | To run any of those bots you need: 5 | - Python 6 | - PRAW (`pip install praw`) 7 | - OAuth2Util (`pip install praw-oauth2util`) 8 | 9 | **You need PRAW 3** for the bots. They don't work anymore with PRAW 4 and PRAW 5. Due to missing time they won't be ported to new versions of PRAW, sorry. 10 | 11 | If the bot uses OAuth2 you have to [register an app on Reddit](https://www.reddit.com/prefs/apps/), using `script` as app type and `http://127.0.0.1:65010/authorize_callback` as redirect uri. You then have to copy the file called `oauthtemplate.txt` to `oauth.ini` and enter the app id and app secret at the corresponding places. On first start up a webbrowser will be started where Reddit asks for permission. Make sure you are logged in with the user you want the bot to be run with when you click accept. If you want to run it on a server where you don't have a graphical browser you can try [server mode](https://github.com/SmBe19/praw-OAuth2Util/blob/master/OAuth2Util/README.md#server-mode) of `OAuth2Util`. Or you can run the bot the first time locally and then copy the `oauth.ini` file (which now contains all necessary tokens) to your server. 12 | 13 | In the source code of the bots you will find at the top the `USER CONFIGURATION` and sometimes the `BOT CONFIGURATION`. In the `USER CONFIGURATION` section you should fill out every variable as they describe detailed what and where the bot should do (e.g. User Name, Subreddit to operate in, duration of sleep). The `BOT CONFIGURATION` section defines variables that you don't really have to change, but if you really have to, they are there. They are mostly constants for the bot (e.g. Name of config files). 14 | 15 | You can set the variables set in the `USER CONFIGURATION` / `BOT CONFIGURATION` also in a separate file called `bot.py`, just use `key = value` (e.g. `username = "SmBe19"`). This way you don't have to edit the source directly (so it's easier to update) and you can exclude this file from git. Btw. it's a normal Python file, that get's executed, so you can use code as for example `password = getpass.getpass()`. 16 | -------------------------------------------------------------------------------- /RSSBot/.gitignore: -------------------------------------------------------------------------------- 1 | done.txt 2 | oauth.txt -------------------------------------------------------------------------------- /RSSBot/README.md: -------------------------------------------------------------------------------- 1 | # RSS Bot 2 | A bot which checks a RSS feed and posts new articles on a subreddit. 3 | 4 | The sources are listed in the file `sources.txt`, one per line. You can add or remove sources while the bot is running and it will check accordingly. -------------------------------------------------------------------------------- /RSSBot/RSSBot.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to post from rss feeds to a given subreddit 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import logging 9 | import logging.handlers 10 | import OAuth2Util 11 | import RSSReader 12 | 13 | # ### USER CONFIGURATION ### # 14 | 15 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 16 | USERAGENT = "" 17 | 18 | # The name of the subreddit to post to. e.g. "funny" 19 | SUBREDDIT = "" 20 | 21 | # The time in seconds the bot should sleep until it checks again. 22 | SLEEP = 60*60 23 | 24 | # If True, the bot will submit a link even if reddit says it was already submitted. This can be the case if it was submitted in an other subreddit or by an other user, or if the bot failed with keeping track of already submitted articles (shouldn't be the case). 25 | RESUBMIT_ANYWAYS = True 26 | 27 | # If True, the bot will post a comment with the description of the article. 28 | POST_DESCRIPTION = True 29 | 30 | # The text the bot should post with the description, {0} will be replaced by the description 31 | DESCRIPTION_FORMAT = "Link description:\n\n{0}" 32 | 33 | # ### END USER CONFIGURATION ### # 34 | 35 | # ### BOT CONFIGURATION ### # 36 | SOURCES_CONFIGFILE = "sources.txt" 37 | DONE_CONFIGFILE = "done.txt" 38 | # ### END BOT CONFIGURATION ### # 39 | 40 | # ### LOGGING CONFIGURATION ### # 41 | LOG_LEVEL = logging.INFO 42 | LOG_FILENAME = "bot.log" 43 | LOG_FILE_BACKUPCOUNT = 5 44 | LOG_FILE_MAXSIZE = 1024 * 256 45 | # ### END LOGGING CONFIGURATION ### # 46 | 47 | # ### EXTERNAL CONFIG FILE ### # 48 | try: 49 | # A file containing data for global constants. 50 | import bot 51 | for k in dir(bot): 52 | if k.upper() in globals(): 53 | globals()[k.upper()] = getattr(bot, k) 54 | except ImportError: 55 | pass 56 | # ### END EXTERNAL CONFIG FILE ### # 57 | 58 | # ### LOGGING SETUP ### # 59 | log = logging.getLogger("bot") 60 | log.setLevel(LOG_LEVEL) 61 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 62 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 63 | log_stderrHandler = logging.StreamHandler() 64 | log_stderrHandler.setFormatter(log_formatter) 65 | log.addHandler(log_stderrHandler) 66 | if LOG_FILENAME is not None: 67 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 68 | log_fileHandler.setFormatter(log_formatter_file) 69 | log.addHandler(log_fileHandler) 70 | # ### END LOGGING SETUP ### # 71 | 72 | def read_config_sources(): 73 | sources = [] 74 | try: 75 | with open(SOURCES_CONFIGFILE, "r") as f: 76 | for line in f: 77 | sources.append(line) 78 | except OSError: 79 | log.error("%s not found.", SOURCES_CONFIGFILE) 80 | return sources 81 | 82 | def read_config_done(): 83 | done = set() 84 | try: 85 | with open(DONE_CONFIGFILE, "r") as f: 86 | for line in f: 87 | if line.strip(): 88 | done.add(line.strip()) 89 | except OSError: 90 | log.info("%s not found.", DONE_CONFIGFILE) 91 | return done 92 | 93 | def write_config_done(done): 94 | with open(DONE_CONFIGFILE, "w") as f: 95 | for d in done: 96 | if d: 97 | f.write(d + "\n") 98 | 99 | # main procedure 100 | def run_bot(): 101 | r = praw.Reddit(USERAGENT) 102 | o = OAuth2Util.OAuth2Util(r) 103 | o.refresh() 104 | sub = r.get_subreddit(SUBREDDIT) 105 | 106 | log.info("Start bot for subreddit %s", SUBREDDIT) 107 | 108 | done = read_config_done() 109 | 110 | while True: 111 | try: 112 | o.refresh() 113 | sources = read_config_sources() 114 | 115 | log.info("check sources") 116 | newArticles = [] 117 | for source in sources: 118 | newArticles.extend(RSSReader.get_new_articles(source)) 119 | 120 | for article in newArticles: 121 | if article[3] not in done: 122 | done.add(article[3]) 123 | try: 124 | submission = sub.submit(article[0], url=article[1], resubmit=RESUBMIT_ANYWAYS) 125 | if POST_DESCRIPTION and article[2] is not None: 126 | submission.add_comment(DESCRIPTION_FORMAT.format(article[2])) 127 | except praw.errors.AlreadySubmitted: 128 | log.info("already submitted") 129 | else: 130 | log.info("submit article") 131 | 132 | # Allows the bot to exit on ^C, all other exceptions are ignored 133 | except KeyboardInterrupt: 134 | break 135 | except Exception as e: 136 | log.error("Exception %s", e, exc_info=True) 137 | 138 | write_config_done(done) 139 | log.info("sleep for %s s", SLEEP) 140 | time.sleep(SLEEP) 141 | 142 | write_config_done(done) 143 | 144 | 145 | if __name__ == "__main__": 146 | if not USERAGENT: 147 | log.error("missing useragent") 148 | elif not SUBREDDIT: 149 | log.error("missing subreddit") 150 | else: 151 | run_bot() 152 | -------------------------------------------------------------------------------- /RSSBot/RSSReader.py: -------------------------------------------------------------------------------- 1 | import urllib.request 2 | from urllib.error import URLError 3 | import html2text 4 | import xml.etree.ElementTree as ET 5 | #from time import strptime, mktime 6 | 7 | #PUBDATEFORMAT = "%a, %d %b %Y %H:%M:%S %z" 8 | 9 | def get_new_articles(source): 10 | articles = [] 11 | try: 12 | response = urllib.request.urlopen(source) 13 | orig_rss = response.read().decode("utf-8") 14 | rss = ET.fromstring(orig_rss) 15 | channel = rss.find("channel") 16 | 17 | for item in channel.findall("item"): 18 | # Not used anymore 19 | # pubDate = item.find("pubDate").text 20 | # pubDateConv = mktime(time.strptime(pubDate, PUBDATEFORMAT))) 21 | 22 | link = item.find("link").text 23 | 24 | title = item.find("title") 25 | 26 | if title is not None: 27 | title = title.text 28 | if title is None: 29 | print("found no title, will use link") 30 | title = link 31 | 32 | description = item.find("description") 33 | 34 | if description is not None: 35 | description = html2text.html2text(description.text) 36 | 37 | guid = item.find("guid") 38 | 39 | if guid is not None: 40 | guid = guid.text 41 | if guid is None: 42 | #print("found no guid, will use link") 43 | guid = link 44 | articles.append((title, link, description, guid)) 45 | 46 | except URLError as e: 47 | print("Error:", e.reason) 48 | 49 | return articles -------------------------------------------------------------------------------- /RSSBot/html2text.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """html2text: Turn HTML into equivalent Markdown-structured text.""" 3 | __version__ = "3.200.3" 4 | __author__ = "Aaron Swartz (me@aaronsw.com)" 5 | __copyright__ = "(C) 2004-2008 Aaron Swartz. GNU GPL 3." 6 | __contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes", "Kevin Jay North"] 7 | 8 | # TODO: 9 | # Support decoded entities with unifiable. 10 | 11 | try: 12 | True 13 | except NameError: 14 | setattr(__builtins__, 'True', 1) 15 | setattr(__builtins__, 'False', 0) 16 | 17 | def has_key(x, y): 18 | if hasattr(x, 'has_key'): return x.has_key(y) 19 | else: return y in x 20 | 21 | try: 22 | import htmlentitydefs 23 | import urlparse 24 | import HTMLParser 25 | except ImportError: #Python3 26 | import html.entities as htmlentitydefs 27 | import urllib.parse as urlparse 28 | import html.parser as HTMLParser 29 | try: #Python3 30 | import urllib.request as urllib 31 | except: 32 | import urllib 33 | import optparse, re, sys, codecs, types 34 | 35 | try: from textwrap import wrap 36 | except: pass 37 | 38 | # Use Unicode characters instead of their ascii psuedo-replacements 39 | UNICODE_SNOB = 0 40 | 41 | # Escape all special characters. Output is less readable, but avoids corner case formatting issues. 42 | ESCAPE_SNOB = 0 43 | 44 | # Put the links after each paragraph instead of at the end. 45 | LINKS_EACH_PARAGRAPH = 0 46 | 47 | # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.) 48 | BODY_WIDTH = 78 49 | 50 | # Don't show internal links (href="#local-anchor") -- corresponding link targets 51 | # won't be visible in the plain text file anyway. 52 | SKIP_INTERNAL_LINKS = True 53 | 54 | # Use inline, rather than reference, formatting for images and links 55 | INLINE_LINKS = True 56 | 57 | # Number of pixels Google indents nested lists 58 | GOOGLE_LIST_INDENT = 36 59 | 60 | IGNORE_ANCHORS = False 61 | IGNORE_IMAGES = False 62 | IGNORE_EMPHASIS = False 63 | 64 | ### Entity Nonsense ### 65 | 66 | def name2cp(k): 67 | if k == 'apos': return ord("'") 68 | if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3 69 | return htmlentitydefs.name2codepoint[k] 70 | else: 71 | k = htmlentitydefs.entitydefs[k] 72 | if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1 73 | return ord(codecs.latin_1_decode(k)[0]) 74 | 75 | unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"', 76 | 'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*', 77 | 'ndash':'-', 'oelig':'oe', 'aelig':'ae', 78 | 'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a', 79 | 'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e', 80 | 'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i', 81 | 'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o', 82 | 'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u', 83 | 'lrm':'', 'rlm':''} 84 | 85 | unifiable_n = {} 86 | 87 | for k in unifiable.keys(): 88 | unifiable_n[name2cp(k)] = unifiable[k] 89 | 90 | ### End Entity Nonsense ### 91 | 92 | def onlywhite(line): 93 | """Return true if the line does only consist of whitespace characters.""" 94 | for c in line: 95 | if c is not ' ' and c is not ' ': 96 | return c is ' ' 97 | return line 98 | 99 | def hn(tag): 100 | if tag[0] == 'h' and len(tag) == 2: 101 | try: 102 | n = int(tag[1]) 103 | if n in range(1, 10): return n 104 | except ValueError: return 0 105 | 106 | def dumb_property_dict(style): 107 | """returns a hash of css attributes""" 108 | return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]); 109 | 110 | def dumb_css_parser(data): 111 | """returns a hash of css selectors, each of which contains a hash of css attributes""" 112 | # remove @import sentences 113 | data += ';' 114 | importIndex = data.find('@import') 115 | while importIndex != -1: 116 | data = data[0:importIndex] + data[data.find(';', importIndex) + 1:] 117 | importIndex = data.find('@import') 118 | 119 | # parse the css. reverted from dictionary compehension in order to support older pythons 120 | elements = [x.split('{') for x in data.split('}') if '{' in x.strip()] 121 | try: 122 | elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements]) 123 | except ValueError: 124 | elements = {} # not that important 125 | 126 | return elements 127 | 128 | def element_style(attrs, style_def, parent_style): 129 | """returns a hash of the 'final' style attributes of the element""" 130 | style = parent_style.copy() 131 | if 'class' in attrs: 132 | for css_class in attrs['class'].split(): 133 | css_style = style_def['.' + css_class] 134 | style.update(css_style) 135 | if 'style' in attrs: 136 | immediate_style = dumb_property_dict(attrs['style']) 137 | style.update(immediate_style) 138 | return style 139 | 140 | def google_list_style(style): 141 | """finds out whether this is an ordered or unordered list""" 142 | if 'list-style-type' in style: 143 | list_style = style['list-style-type'] 144 | if list_style in ['disc', 'circle', 'square', 'none']: 145 | return 'ul' 146 | return 'ol' 147 | 148 | def google_has_height(style): 149 | """check if the style of the element has the 'height' attribute explicitly defined""" 150 | if 'height' in style: 151 | return True 152 | return False 153 | 154 | def google_text_emphasis(style): 155 | """return a list of all emphasis modifiers of the element""" 156 | emphasis = [] 157 | if 'text-decoration' in style: 158 | emphasis.append(style['text-decoration']) 159 | if 'font-style' in style: 160 | emphasis.append(style['font-style']) 161 | if 'font-weight' in style: 162 | emphasis.append(style['font-weight']) 163 | return emphasis 164 | 165 | def google_fixed_width_font(style): 166 | """check if the css of the current element defines a fixed width font""" 167 | font_family = '' 168 | if 'font-family' in style: 169 | font_family = style['font-family'] 170 | if 'Courier New' == font_family or 'Consolas' == font_family: 171 | return True 172 | return False 173 | 174 | def list_numbering_start(attrs): 175 | """extract numbering from list element attributes""" 176 | if 'start' in attrs: 177 | return int(attrs['start']) - 1 178 | else: 179 | return 0 180 | 181 | class HTML2Text(HTMLParser.HTMLParser): 182 | def __init__(self, out=None, baseurl=''): 183 | HTMLParser.HTMLParser.__init__(self) 184 | 185 | # Config options 186 | self.unicode_snob = UNICODE_SNOB 187 | self.escape_snob = ESCAPE_SNOB 188 | self.links_each_paragraph = LINKS_EACH_PARAGRAPH 189 | self.body_width = BODY_WIDTH 190 | self.skip_internal_links = SKIP_INTERNAL_LINKS 191 | self.inline_links = INLINE_LINKS 192 | self.google_list_indent = GOOGLE_LIST_INDENT 193 | self.ignore_links = IGNORE_ANCHORS 194 | self.ignore_images = IGNORE_IMAGES 195 | self.ignore_emphasis = IGNORE_EMPHASIS 196 | self.google_doc = False 197 | self.ul_item_mark = '*' 198 | self.emphasis_mark = '_' 199 | self.strong_mark = '**' 200 | 201 | if out is None: 202 | self.out = self.outtextf 203 | else: 204 | self.out = out 205 | 206 | self.outtextlist = [] # empty list to store output characters before they are "joined" 207 | 208 | try: 209 | self.outtext = unicode() 210 | except NameError: # Python3 211 | self.outtext = str() 212 | 213 | self.quiet = 0 214 | self.p_p = 0 # number of newline character to print before next output 215 | self.outcount = 0 216 | self.start = 1 217 | self.space = 0 218 | self.a = [] 219 | self.astack = [] 220 | self.maybe_automatic_link = None 221 | self.absolute_url_matcher = re.compile(r'^[a-zA-Z+]+://') 222 | self.acount = 0 223 | self.list = [] 224 | self.blockquote = 0 225 | self.pre = 0 226 | self.startpre = 0 227 | self.code = False 228 | self.br_toggle = '' 229 | self.lastWasNL = 0 230 | self.lastWasList = False 231 | self.style = 0 232 | self.style_def = {} 233 | self.tag_stack = [] 234 | self.emphasis = 0 235 | self.drop_white_space = 0 236 | self.inheader = False 237 | self.abbr_title = None # current abbreviation definition 238 | self.abbr_data = None # last inner HTML (for abbr being defined) 239 | self.abbr_list = {} # stack of abbreviations to write later 240 | self.baseurl = baseurl 241 | 242 | try: del unifiable_n[name2cp('nbsp')] 243 | except KeyError: pass 244 | unifiable['nbsp'] = ' _place_holder;' 245 | 246 | 247 | def feed(self, data): 248 | data = data.replace("", "") 249 | HTMLParser.HTMLParser.feed(self, data) 250 | 251 | def handle(self, data): 252 | self.feed(data) 253 | self.feed("") 254 | return self.optwrap(self.close()) 255 | 256 | def outtextf(self, s): 257 | self.outtextlist.append(s) 258 | if s: self.lastWasNL = s[-1] == '\n' 259 | 260 | def close(self): 261 | HTMLParser.HTMLParser.close(self) 262 | 263 | self.pbr() 264 | self.o('', 0, 'end') 265 | 266 | self.outtext = self.outtext.join(self.outtextlist) 267 | if self.unicode_snob: 268 | nbsp = unichr(name2cp('nbsp')) 269 | else: 270 | nbsp = u' ' 271 | self.outtext = self.outtext.replace(u' _place_holder;', nbsp) 272 | 273 | return self.outtext 274 | 275 | def handle_charref(self, c): 276 | self.o(self.charref(c), 1) 277 | 278 | def handle_entityref(self, c): 279 | self.o(self.entityref(c), 1) 280 | 281 | def handle_starttag(self, tag, attrs): 282 | self.handle_tag(tag, attrs, 1) 283 | 284 | def handle_endtag(self, tag): 285 | self.handle_tag(tag, None, 0) 286 | 287 | def previousIndex(self, attrs): 288 | """ returns the index of certain set of attributes (of a link) in the 289 | self.a list 290 | 291 | If the set of attributes is not found, returns None 292 | """ 293 | if not has_key(attrs, 'href'): return None 294 | 295 | i = -1 296 | for a in self.a: 297 | i += 1 298 | match = 0 299 | 300 | if has_key(a, 'href') and a['href'] == attrs['href']: 301 | if has_key(a, 'title') or has_key(attrs, 'title'): 302 | if (has_key(a, 'title') and has_key(attrs, 'title') and 303 | a['title'] == attrs['title']): 304 | match = True 305 | else: 306 | match = True 307 | 308 | if match: return i 309 | 310 | def drop_last(self, nLetters): 311 | if not self.quiet: 312 | self.outtext = self.outtext[:-nLetters] 313 | 314 | def handle_emphasis(self, start, tag_style, parent_style): 315 | """handles various text emphases""" 316 | tag_emphasis = google_text_emphasis(tag_style) 317 | parent_emphasis = google_text_emphasis(parent_style) 318 | 319 | # handle Google's text emphasis 320 | strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough 321 | bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis 322 | italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis 323 | fixed = google_fixed_width_font(tag_style) and not \ 324 | google_fixed_width_font(parent_style) and not self.pre 325 | 326 | if start: 327 | # crossed-out text must be handled before other attributes 328 | # in order not to output qualifiers unnecessarily 329 | if bold or italic or fixed: 330 | self.emphasis += 1 331 | if strikethrough: 332 | self.quiet += 1 333 | if italic: 334 | self.o(self.emphasis_mark) 335 | self.drop_white_space += 1 336 | if bold: 337 | self.o(self.strong_mark) 338 | self.drop_white_space += 1 339 | if fixed: 340 | self.o('`') 341 | self.drop_white_space += 1 342 | self.code = True 343 | else: 344 | if bold or italic or fixed: 345 | # there must not be whitespace before closing emphasis mark 346 | self.emphasis -= 1 347 | self.space = 0 348 | self.outtext = self.outtext.rstrip() 349 | if fixed: 350 | if self.drop_white_space: 351 | # empty emphasis, drop it 352 | self.drop_last(1) 353 | self.drop_white_space -= 1 354 | else: 355 | self.o('`') 356 | self.code = False 357 | if bold: 358 | if self.drop_white_space: 359 | # empty emphasis, drop it 360 | self.drop_last(2) 361 | self.drop_white_space -= 1 362 | else: 363 | self.o(self.strong_mark) 364 | if italic: 365 | if self.drop_white_space: 366 | # empty emphasis, drop it 367 | self.drop_last(1) 368 | self.drop_white_space -= 1 369 | else: 370 | self.o(self.emphasis_mark) 371 | # space is only allowed after *all* emphasis marks 372 | if (bold or italic) and not self.emphasis: 373 | self.o(" ") 374 | if strikethrough: 375 | self.quiet -= 1 376 | 377 | def handle_tag(self, tag, attrs, start): 378 | #attrs = fixattrs(attrs) 379 | if attrs is None: 380 | attrs = {} 381 | else: 382 | attrs = dict(attrs) 383 | 384 | if self.google_doc: 385 | # the attrs parameter is empty for a closing tag. in addition, we 386 | # need the attributes of the parent nodes in order to get a 387 | # complete style description for the current element. we assume 388 | # that google docs export well formed html. 389 | parent_style = {} 390 | if start: 391 | if self.tag_stack: 392 | parent_style = self.tag_stack[-1][2] 393 | tag_style = element_style(attrs, self.style_def, parent_style) 394 | self.tag_stack.append((tag, attrs, tag_style)) 395 | else: 396 | dummy, attrs, tag_style = self.tag_stack.pop() 397 | if self.tag_stack: 398 | parent_style = self.tag_stack[-1][2] 399 | 400 | if hn(tag): 401 | self.p() 402 | if start: 403 | self.inheader = True 404 | self.o(hn(tag)*"#" + ' ') 405 | else: 406 | self.inheader = False 407 | return # prevent redundant emphasis marks on headers 408 | 409 | if tag in ['p', 'div']: 410 | if self.google_doc: 411 | if start and google_has_height(tag_style): 412 | self.p() 413 | else: 414 | self.soft_br() 415 | else: 416 | self.p() 417 | 418 | if tag == "br" and start: self.o(" \n") 419 | 420 | if tag == "hr" and start: 421 | self.p() 422 | self.o("* * *") 423 | self.p() 424 | 425 | if tag in ["head", "style", 'script']: 426 | if start: self.quiet += 1 427 | else: self.quiet -= 1 428 | 429 | if tag == "style": 430 | if start: self.style += 1 431 | else: self.style -= 1 432 | 433 | if tag in ["body"]: 434 | self.quiet = 0 # sites like 9rules.com never close 435 | 436 | if tag == "blockquote": 437 | if start: 438 | self.p(); self.o('> ', 0, 1); self.start = 1 439 | self.blockquote += 1 440 | else: 441 | self.blockquote -= 1 442 | self.p() 443 | 444 | if tag in ['em', 'i', 'u'] and not self.ignore_emphasis: self.o(self.emphasis_mark) 445 | if tag in ['strong', 'b'] and not self.ignore_emphasis: self.o(self.strong_mark) 446 | if tag in ['del', 'strike', 's']: 447 | if start: 448 | self.o("<"+tag+">") 449 | else: 450 | self.o("") 451 | 452 | if self.google_doc: 453 | if not self.inheader: 454 | # handle some font attributes, but leave headers clean 455 | self.handle_emphasis(start, tag_style, parent_style) 456 | 457 | if tag in ["code", "tt"] and not self.pre: self.o('`') #TODO: `` `this` `` 458 | if tag == "abbr": 459 | if start: 460 | self.abbr_title = None 461 | self.abbr_data = '' 462 | if has_key(attrs, 'title'): 463 | self.abbr_title = attrs['title'] 464 | else: 465 | if self.abbr_title != None: 466 | self.abbr_list[self.abbr_data] = self.abbr_title 467 | self.abbr_title = None 468 | self.abbr_data = '' 469 | 470 | if tag == "a" and not self.ignore_links: 471 | if start: 472 | if has_key(attrs, 'href') and not (self.skip_internal_links and attrs['href'].startswith('#')): 473 | self.astack.append(attrs) 474 | self.maybe_automatic_link = attrs['href'] 475 | else: 476 | self.astack.append(None) 477 | else: 478 | if self.astack: 479 | a = self.astack.pop() 480 | if self.maybe_automatic_link: 481 | self.maybe_automatic_link = None 482 | elif a: 483 | if self.inline_links: 484 | self.o("](" + escape_md(a['href']) + ")") 485 | else: 486 | i = self.previousIndex(a) 487 | if i is not None: 488 | a = self.a[i] 489 | else: 490 | self.acount += 1 491 | a['count'] = self.acount 492 | a['outcount'] = self.outcount 493 | self.a.append(a) 494 | self.o("][" + str(a['count']) + "]") 495 | 496 | if tag == "img" and start and not self.ignore_images: 497 | if has_key(attrs, 'src'): 498 | attrs['href'] = attrs['src'] 499 | alt = attrs.get('alt', '') 500 | self.o("![" + escape_md(alt) + "]") 501 | 502 | if self.inline_links: 503 | self.o("(" + escape_md(attrs['href']) + ")") 504 | else: 505 | i = self.previousIndex(attrs) 506 | if i is not None: 507 | attrs = self.a[i] 508 | else: 509 | self.acount += 1 510 | attrs['count'] = self.acount 511 | attrs['outcount'] = self.outcount 512 | self.a.append(attrs) 513 | self.o("[" + str(attrs['count']) + "]") 514 | 515 | if tag == 'dl' and start: self.p() 516 | if tag == 'dt' and not start: self.pbr() 517 | if tag == 'dd' and start: self.o(' ') 518 | if tag == 'dd' and not start: self.pbr() 519 | 520 | if tag in ["ol", "ul"]: 521 | # Google Docs create sub lists as top level lists 522 | if (not self.list) and (not self.lastWasList): 523 | self.p() 524 | if start: 525 | if self.google_doc: 526 | list_style = google_list_style(tag_style) 527 | else: 528 | list_style = tag 529 | numbering_start = list_numbering_start(attrs) 530 | self.list.append({'name':list_style, 'num':numbering_start}) 531 | else: 532 | if self.list: self.list.pop() 533 | self.lastWasList = True 534 | else: 535 | self.lastWasList = False 536 | 537 | if tag == 'li': 538 | self.pbr() 539 | if start: 540 | if self.list: li = self.list[-1] 541 | else: li = {'name':'ul', 'num':0} 542 | if self.google_doc: 543 | nest_count = self.google_nest_count(tag_style) 544 | else: 545 | nest_count = len(self.list) 546 | self.o(" " * nest_count) #TODO: line up
  1. s > 9 correctly. 547 | if li['name'] == "ul": self.o(self.ul_item_mark + " ") 548 | elif li['name'] == "ol": 549 | li['num'] += 1 550 | self.o(str(li['num'])+". ") 551 | self.start = 1 552 | 553 | if tag in ["table", "tr"] and start: self.p() 554 | if tag == 'td': self.pbr() 555 | 556 | if tag == "pre": 557 | if start: 558 | self.startpre = 1 559 | self.pre = 1 560 | else: 561 | self.pre = 0 562 | self.p() 563 | 564 | def pbr(self): 565 | if self.p_p == 0: 566 | self.p_p = 1 567 | 568 | def p(self): 569 | self.p_p = 2 570 | 571 | def soft_br(self): 572 | self.pbr() 573 | self.br_toggle = ' ' 574 | 575 | def o(self, data, puredata=0, force=0): 576 | if self.abbr_data is not None: 577 | self.abbr_data += data 578 | 579 | if not self.quiet: 580 | if self.google_doc: 581 | # prevent white space immediately after 'begin emphasis' marks ('**' and '_') 582 | lstripped_data = data.lstrip() 583 | if self.drop_white_space and not (self.pre or self.code): 584 | data = lstripped_data 585 | if lstripped_data != '': 586 | self.drop_white_space = 0 587 | 588 | if puredata and not self.pre: 589 | data = re.sub('\s+', ' ', data) 590 | if data and data[0] == ' ': 591 | self.space = 1 592 | data = data[1:] 593 | if not data and not force: return 594 | 595 | if self.startpre: 596 | #self.out(" :") #TODO: not output when already one there 597 | if not data.startswith("\n"): #
    stuff...
    598 |                     data = "\n" + data
    599 | 
    600 |             bq = (">" * self.blockquote)
    601 |             if not (force and data and data[0] == ">") and self.blockquote: bq += " "
    602 | 
    603 |             if self.pre:
    604 |                 if not self.list:
    605 |                     bq += "    "
    606 |                 #else: list content is already partially indented
    607 |                 for i in xrange(len(self.list)):
    608 |                     bq += "    "
    609 |                 data = data.replace("\n", "\n"+bq)
    610 | 
    611 |             if self.startpre:
    612 |                 self.startpre = 0
    613 |                 if self.list:
    614 |                     data = data.lstrip("\n") # use existing initial indentation
    615 | 
    616 |             if self.start:
    617 |                 self.space = 0
    618 |                 self.p_p = 0
    619 |                 self.start = 0
    620 | 
    621 |             if force == 'end':
    622 |                 # It's the end.
    623 |                 self.p_p = 0
    624 |                 self.out("\n")
    625 |                 self.space = 0
    626 | 
    627 |             if self.p_p:
    628 |                 self.out((self.br_toggle+'\n'+bq)*self.p_p)
    629 |                 self.space = 0
    630 |                 self.br_toggle = ''
    631 | 
    632 |             if self.space:
    633 |                 if not self.lastWasNL: self.out(' ')
    634 |                 self.space = 0
    635 | 
    636 |             if self.a and ((self.p_p == 2 and self.links_each_paragraph) or force == "end"):
    637 |                 if force == "end": self.out("\n")
    638 | 
    639 |                 newa = []
    640 |                 for link in self.a:
    641 |                     if self.outcount > link['outcount']:
    642 |                         self.out("   ["+ str(link['count']) +"]: " + urlparse.urljoin(self.baseurl, link['href']))
    643 |                         if has_key(link, 'title'): self.out(" ("+link['title']+")")
    644 |                         self.out("\n")
    645 |                     else:
    646 |                         newa.append(link)
    647 | 
    648 |                 if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done.
    649 | 
    650 |                 self.a = newa
    651 | 
    652 |             if self.abbr_list and force == "end":
    653 |                 for abbr, definition in self.abbr_list.items():
    654 |                     self.out("  *[" + abbr + "]: " + definition + "\n")
    655 | 
    656 |             self.p_p = 0
    657 |             self.out(data)
    658 |             self.outcount += 1
    659 | 
    660 |     def handle_data(self, data):
    661 |         if r'\/script>' in data: self.quiet -= 1
    662 | 
    663 |         if self.style:
    664 |             self.style_def.update(dumb_css_parser(data))
    665 | 
    666 |         if not self.maybe_automatic_link is None:
    667 |             href = self.maybe_automatic_link
    668 |             if href == data and self.absolute_url_matcher.match(href):
    669 |                 self.o("<" + data + ">")
    670 |                 return
    671 |             else:
    672 |                 self.o("[")
    673 |                 self.maybe_automatic_link = None
    674 | 
    675 |         if not self.code and not self.pre:
    676 |             data = escape_md_section(data, snob=self.escape_snob)
    677 |         self.o(data, 1)
    678 | 
    679 |     def unknown_decl(self, data): pass
    680 | 
    681 |     def charref(self, name):
    682 |         if name[0] in ['x','X']:
    683 |             c = int(name[1:], 16)
    684 |         else:
    685 |             c = int(name)
    686 | 
    687 |         if not self.unicode_snob and c in unifiable_n.keys():
    688 |             return unifiable_n[c]
    689 |         else:
    690 |             try:
    691 |                 return unichr(c)
    692 |             except NameError: #Python3
    693 |                 return chr(c)
    694 | 
    695 |     def entityref(self, c):
    696 |         if not self.unicode_snob and c in unifiable.keys():
    697 |             return unifiable[c]
    698 |         else:
    699 |             try: name2cp(c)
    700 |             except KeyError: return "&" + c + ';'
    701 |             else:
    702 |                 try:
    703 |                     return unichr(name2cp(c))
    704 |                 except NameError: #Python3
    705 |                     return chr(name2cp(c))
    706 | 
    707 |     def replaceEntities(self, s):
    708 |         s = s.group(1)
    709 |         if s[0] == "#":
    710 |             return self.charref(s[1:])
    711 |         else: return self.entityref(s)
    712 | 
    713 |     r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
    714 |     def unescape(self, s):
    715 |         return self.r_unescape.sub(self.replaceEntities, s)
    716 | 
    717 |     def google_nest_count(self, style):
    718 |         """calculate the nesting count of google doc lists"""
    719 |         nest_count = 0
    720 |         if 'margin-left' in style:
    721 |             nest_count = int(style['margin-left'][:-2]) / self.google_list_indent
    722 |         return nest_count
    723 | 
    724 | 
    725 |     def optwrap(self, text):
    726 |         """Wrap all paragraphs in the provided text."""
    727 |         if not self.body_width:
    728 |             return text
    729 | 
    730 |         assert wrap, "Requires Python 2.3."
    731 |         result = ''
    732 |         newlines = 0
    733 |         for para in text.split("\n"):
    734 |             if len(para) > 0:
    735 |                 if not skipwrap(para):
    736 |                     result += "\n".join(wrap(para, self.body_width))
    737 |                     if para.endswith('  '):
    738 |                         result += "  \n"
    739 |                         newlines = 1
    740 |                     else:
    741 |                         result += "\n\n"
    742 |                         newlines = 2
    743 |                 else:
    744 |                     if not onlywhite(para):
    745 |                         result += para + "\n"
    746 |                         newlines = 1
    747 |             else:
    748 |                 if newlines < 2:
    749 |                     result += "\n"
    750 |                     newlines += 1
    751 |         return result
    752 | 
    753 | ordered_list_matcher = re.compile(r'\d+\.\s')
    754 | unordered_list_matcher = re.compile(r'[-\*\+]\s')
    755 | md_chars_matcher = re.compile(r"([\\\[\]\(\)])")
    756 | md_chars_matcher_all = re.compile(r"([`\*_{}\[\]\(\)#!])")
    757 | md_dot_matcher = re.compile(r"""
    758 |     ^             # start of line
    759 |     (\s*\d+)      # optional whitespace and a number
    760 |     (\.)          # dot
    761 |     (?=\s)        # lookahead assert whitespace
    762 |     """, re.MULTILINE | re.VERBOSE)
    763 | md_plus_matcher = re.compile(r"""
    764 |     ^
    765 |     (\s*)
    766 |     (\+)
    767 |     (?=\s)
    768 |     """, flags=re.MULTILINE | re.VERBOSE)
    769 | md_dash_matcher = re.compile(r"""
    770 |     ^
    771 |     (\s*)
    772 |     (-)
    773 |     (?=\s|\-)     # followed by whitespace (bullet list, or spaced out hr)
    774 |                   # or another dash (header or hr)
    775 |     """, flags=re.MULTILINE | re.VERBOSE)
    776 | slash_chars = r'\`*_{}[]()#+-.!'
    777 | md_backslash_matcher = re.compile(r'''
    778 |     (\\)          # match one slash
    779 |     (?=[%s])      # followed by a char that requires escaping
    780 |     ''' % re.escape(slash_chars),
    781 |     flags=re.VERBOSE)
    782 | 
    783 | def skipwrap(para):
    784 |     # If the text begins with four spaces or one tab, it's a code block; don't wrap
    785 |     if para[0:4] == '    ' or para[0] == '\t':
    786 |         return True
    787 |     # If the text begins with only two "--", possibly preceded by whitespace, that's
    788 |     # an emdash; so wrap.
    789 |     stripped = para.lstrip()
    790 |     if stripped[0:2] == "--" and len(stripped) > 2 and stripped[2] != "-":
    791 |         return False
    792 |     # I'm not sure what this is for; I thought it was to detect lists, but there's
    793 |     # a 
    -inside- case in one of the tests that also depends upon it. 794 | if stripped[0:1] == '-' or stripped[0:1] == '*': 795 | return True 796 | # If the text begins with a single -, *, or +, followed by a space, or an integer, 797 | # followed by a ., followed by a space (in either case optionally preceeded by 798 | # whitespace), it's a list; don't wrap. 799 | if ordered_list_matcher.match(stripped) or unordered_list_matcher.match(stripped): 800 | return True 801 | return False 802 | 803 | def wrapwrite(text): 804 | text = text.encode('utf-8') 805 | try: #Python3 806 | sys.stdout.buffer.write(text) 807 | except AttributeError: 808 | sys.stdout.write(text) 809 | 810 | def html2text(html, baseurl=''): 811 | h = HTML2Text(baseurl=baseurl) 812 | return h.handle(html) 813 | 814 | def unescape(s, unicode_snob=False): 815 | h = HTML2Text() 816 | h.unicode_snob = unicode_snob 817 | return h.unescape(s) 818 | 819 | def escape_md(text): 820 | """Escapes markdown-sensitive characters within other markdown constructs.""" 821 | return md_chars_matcher.sub(r"\\\1", text) 822 | 823 | def escape_md_section(text, snob=False): 824 | """Escapes markdown-sensitive characters across whole document sections.""" 825 | text = md_backslash_matcher.sub(r"\\\1", text) 826 | if snob: 827 | text = md_chars_matcher_all.sub(r"\\\1", text) 828 | text = md_dot_matcher.sub(r"\1\\\2", text) 829 | text = md_plus_matcher.sub(r"\1\\\2", text) 830 | text = md_dash_matcher.sub(r"\1\\\2", text) 831 | return text 832 | 833 | 834 | def main(): 835 | baseurl = '' 836 | 837 | p = optparse.OptionParser('%prog [(filename|url) [encoding]]', 838 | version='%prog ' + __version__) 839 | p.add_option("--ignore-emphasis", dest="ignore_emphasis", action="store_true", 840 | default=IGNORE_EMPHASIS, help="don't include any formatting for emphasis") 841 | p.add_option("--ignore-links", dest="ignore_links", action="store_true", 842 | default=IGNORE_ANCHORS, help="don't include any formatting for links") 843 | p.add_option("--ignore-images", dest="ignore_images", action="store_true", 844 | default=IGNORE_IMAGES, help="don't include any formatting for images") 845 | p.add_option("-g", "--google-doc", action="store_true", dest="google_doc", 846 | default=False, help="convert an html-exported Google Document") 847 | p.add_option("-d", "--dash-unordered-list", action="store_true", dest="ul_style_dash", 848 | default=False, help="use a dash rather than a star for unordered list items") 849 | p.add_option("-e", "--asterisk-emphasis", action="store_true", dest="em_style_asterisk", 850 | default=False, help="use an asterisk rather than an underscore for emphasized text") 851 | p.add_option("-b", "--body-width", dest="body_width", action="store", type="int", 852 | default=BODY_WIDTH, help="number of characters per output line, 0 for no wrap") 853 | p.add_option("-i", "--google-list-indent", dest="list_indent", action="store", type="int", 854 | default=GOOGLE_LIST_INDENT, help="number of pixels Google indents nested lists") 855 | p.add_option("-s", "--hide-strikethrough", action="store_true", dest="hide_strikethrough", 856 | default=False, help="hide strike-through text. only relevant when -g is specified as well") 857 | p.add_option("--escape-all", action="store_true", dest="escape_snob", 858 | default=False, help="Escape all special characters. Output is less readable, but avoids corner case formatting issues.") 859 | (options, args) = p.parse_args() 860 | 861 | # process input 862 | encoding = "utf-8" 863 | if len(args) > 0: 864 | file_ = args[0] 865 | if len(args) == 2: 866 | encoding = args[1] 867 | if len(args) > 2: 868 | p.error('Too many arguments') 869 | 870 | if file_.startswith('http://') or file_.startswith('https://'): 871 | baseurl = file_ 872 | j = urllib.urlopen(baseurl) 873 | data = j.read() 874 | if encoding is None: 875 | try: 876 | from feedparser import _getCharacterEncoding as enc 877 | except ImportError: 878 | enc = lambda x, y: ('utf-8', 1) 879 | encoding = enc(j.headers, data)[0] 880 | if encoding == 'us-ascii': 881 | encoding = 'utf-8' 882 | else: 883 | data = open(file_, 'rb').read() 884 | if encoding is None: 885 | try: 886 | from chardet import detect 887 | except ImportError: 888 | detect = lambda x: {'encoding': 'utf-8'} 889 | encoding = detect(data)['encoding'] 890 | else: 891 | data = sys.stdin.read() 892 | 893 | data = data.decode(encoding) 894 | h = HTML2Text(baseurl=baseurl) 895 | # handle options 896 | if options.ul_style_dash: h.ul_item_mark = '-' 897 | if options.em_style_asterisk: 898 | h.emphasis_mark = '*' 899 | h.strong_mark = '__' 900 | 901 | h.body_width = options.body_width 902 | h.list_indent = options.list_indent 903 | h.ignore_emphasis = options.ignore_emphasis 904 | h.ignore_links = options.ignore_links 905 | h.ignore_images = options.ignore_images 906 | h.google_doc = options.google_doc 907 | h.hide_strikethrough = options.hide_strikethrough 908 | h.escape_snob = options.escape_snob 909 | 910 | wrapwrite(h.handle(data)) 911 | 912 | 913 | if __name__ == "__main__": 914 | main() 915 | -------------------------------------------------------------------------------- /RSSBot/html2text_LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /RSSBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=submit 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /RSSBot/sources.txt: -------------------------------------------------------------------------------- 1 | http://www.nzz.ch/international.rss 2 | http://www.nzz.ch/wissenschaft.rss 3 | http://www.nzz.ch/mehr/digital.rss -------------------------------------------------------------------------------- /RandomUserSelector/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt 2 | done.txt -------------------------------------------------------------------------------- /RandomUserSelector/README.md: -------------------------------------------------------------------------------- 1 | # Random User Selector 2 | Selects random users using comments from /r/all. If you wish you can add them as approved submitters (to build a secret secret society :p). 3 | -------------------------------------------------------------------------------- /RandomUserSelector/RandomUserSelector.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | A script that selects random users and add them as approved submitters 5 | Written by /u/SmBe19 6 | """ 7 | 8 | import praw 9 | import random 10 | import time 11 | import OAuth2Util 12 | 13 | # ### USER CONFIGURATION ### # 14 | 15 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 16 | USERAGENT = "" 17 | 18 | # The name of the subreddit to post to. e.g. "funny" 19 | SUBREDDIT = "" 20 | 21 | # Number of users to select 22 | USERS_COUNT = 10 23 | 24 | # Number of comments from which the users are selected (max is 1000) 25 | SAMPLE_SIZE = 1000 26 | 27 | # Whether to check whether the selected user is already a contributor (does not work atm) 28 | CHECK_CONTRIBUTOR = False 29 | 30 | # Whether to add the selected users as approved submitters. 31 | # Note that that running the script with this flag set to True is considered spam. 32 | ADD_CONTRIBUTOR = False 33 | 34 | # ### END USER CONFIGURATION ### # 35 | 36 | try: 37 | # A file containing data for global constants. 38 | import bot 39 | for k in dir(bot): 40 | if k.upper() in globals(): 41 | globals()[k.upper()] = getattr(bot, k) 42 | except ImportError: 43 | pass 44 | 45 | # main procedure 46 | def run_bot(): 47 | r = praw.Reddit(USERAGENT) 48 | if CHECK_CONTRIBUTOR or ADD_CONTRIBUTOR: 49 | o = OAuth2Util.OAuth2Util(r) 50 | o.refresh() 51 | sub = r.get_subreddit(SUBREDDIT) 52 | 53 | print("Start bot for subreddit", SUBREDDIT) 54 | print("Select", USERS_COUNT, "users from", SAMPLE_SIZE, "comments") 55 | 56 | sub = r.get_subreddit(SUBREDDIT) 57 | if CHECK_CONTRIBUTOR: 58 | contributors = list(sub.get_contributors()) 59 | comments = list(r.get_comments("all", limit=SAMPLE_SIZE)) 60 | added_users = [] 61 | 62 | for i in range(USERS_COUNT): 63 | user = random.choice(comments).author 64 | while (CHECK_CONTRIBUTOR and user in contributors) or user in added_users: 65 | user = random.choice(comments).author 66 | added_users.append(user) 67 | 68 | print(user.name) 69 | 70 | if ADD_CONTRIBUTOR: 71 | sub.add_contributor(user) 72 | 73 | if __name__ == "__main__": 74 | if not USERAGENT: 75 | print("missing useragent") 76 | elif not SUBREDDIT: 77 | print("missing subreddit") 78 | else: 79 | run_bot() 80 | -------------------------------------------------------------------------------- /RandomUserSelector/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=modcontributors,read 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /RespondQuest/.gitignore: -------------------------------------------------------------------------------- 1 | done.txt 2 | oauth.txt -------------------------------------------------------------------------------- /RespondQuest/README.md: -------------------------------------------------------------------------------- 1 | # RespondQuest 2 | Checks whether or not the OP commented on his own thread within a given time span. If not, report the post. -------------------------------------------------------------------------------- /RespondQuest/RespondQuest.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to post from rss feeds to a given subreddit 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import OAuth2Util 9 | 10 | # ### USER CONFIGURATION ### # 11 | 12 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RespondQuest Bot by /u/SmBe19" 13 | USERAGENT = "" 14 | 15 | # The name of the subreddit to check. e.g. "funny" 16 | SUBREDDIT = "" 17 | 18 | # The time in seconds the bot should sleep until it checks again. 19 | SLEEP = 60*60 20 | 21 | # The reason the bot should give for reporting the post 22 | REPORT_MESSAGE = "Potential Rule E violation, please check!" 23 | 24 | # The time in seconds, within OP has to respond 25 | RESPOND_QUEST_TIME = 3*60*60 26 | 27 | # The minimum number of comments a post should have before it is reported 28 | MIN_COMMENTS = 15 29 | 30 | # ### END USER CONFIGURATION ### # 31 | 32 | # ### BOT CONFIGURATION ### # 33 | DONE_CONFIGFILE = "done.txt" 34 | # ### END BOT CONFIGURATION ### # 35 | 36 | try: 37 | # A file containing data for global constants. 38 | import bot 39 | for k in dir(bot): 40 | if k.upper() in globals(): 41 | globals()[k.upper()] = getattr(bot, k) 42 | except ImportError: 43 | pass 44 | 45 | def read_config_done(): 46 | done = set() 47 | try: 48 | with open(DONE_CONFIGFILE, "r") as f: 49 | for line in f: 50 | if line.strip(): 51 | done.add(line.strip()) 52 | except OSError: 53 | print(DONE_CONFIGFILE, "not found.") 54 | return done 55 | 56 | def write_config_done(done): 57 | with open(DONE_CONFIGFILE, "w") as f: 58 | for d in done: 59 | if d: 60 | f.write(d + "\n") 61 | 62 | def op_responded(post): 63 | try: 64 | post.replace_more_comments() 65 | except: 66 | pass 67 | 68 | for comment in praw.helpers.flatten_tree(post.comments): 69 | if comment.author == post.author: 70 | return True 71 | return False 72 | 73 | # main procedure 74 | def run_bot(): 75 | r = praw.Reddit(USERAGENT) 76 | o = OAuth2Util.OAuth2Util(r) 77 | o.refresh() 78 | sub = r.get_subreddit(SUBREDDIT) 79 | 80 | print("Start bot for subreddit", SUBREDDIT) 81 | 82 | done = read_config_done() 83 | 84 | while True: 85 | try: 86 | print("check subreddit") 87 | o.refresh() 88 | 89 | for post in sub.get_new(limit=100): 90 | if post.name in done: 91 | continue 92 | if time.time() - post.created_utc > RESPOND_QUEST_TIME: 93 | if len(post.comments) >= MIN_COMMENTS: 94 | if not op_responded(post): 95 | post.report(REPORT_MESSAGE) 96 | print("reported") 97 | 98 | done.add(post.name) 99 | 100 | # Allows the bot to exit on ^C, all other exceptions are ignored 101 | except KeyboardInterrupt: 102 | break 103 | except Exception as e: 104 | print("Exception", e) 105 | 106 | write_config_done(done) 107 | print("sleep for", SLEEP, "s") 108 | time.sleep(SLEEP) 109 | 110 | write_config_done(done) 111 | 112 | 113 | if __name__ == "__main__": 114 | if not USERAGENT: 115 | print("missing useragent") 116 | elif not SUBREDDIT: 117 | print("missing subreddit") 118 | else: 119 | run_bot() 120 | -------------------------------------------------------------------------------- /RespondQuest/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=read,report 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /ScheduleBot/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt -------------------------------------------------------------------------------- /ScheduleBot/README.md: -------------------------------------------------------------------------------- 1 | # Schedule Bot 2 | A Bot that can post on a schedule. It will, other than AutoMod, post under a specified account such that the comment can be edited. 3 | 4 | ##Usage 5 | Create a wiki page named `schedulebot-config`. Here you can add rules, very similar to the ones AutoMod uses. 6 | To update the schedule, edit the wiki page and then send the bot a PM with only `Schedule` as content. 7 | 8 | For each scheduled post create a rule. Rules are separated by exactly three hypens on a single line (`---`). For each variable, write `variableName: Value`. Indent the lines with spaces, always the same number of spaces per level. 9 | 10 | There are four variables you should define: 11 | 12 | * **First**: The date and time you want the post to be submitted for the first time. The format is `dd.mm.yyyy hh:mm`. If you like you can also specify your timezone eg. as `+0200` (difference to UTC). For example: `First: 24.04.2015 22:10` or `First: 24.04.2015 22:10 +0800` 13 | * **repeat**: How long the timespan is between two posts. Specify a number and a unit of time(seconds, minutes, hours, days, weeks, months, years). If repeat is not specified or there is no unit of time, the post will only posted once. E.g. `repeat: 2 hours`. Note: 1 months = 30 days, 1 years = 365 days. 14 | * **title**: The title of the post. 15 | * **text**: The text of the post. If you would like to specify a multi line comment, write on the first line `text: |` and then write the text on the following lines, one level more indented than the rest of the variables. If you submit a link, the text will be posted as a top level comment. 16 | * **link**: The link to submit. If not specified, a self post will be made. 17 | 18 | Optionally you can define the following variables: 19 | * **times**: The number of times a post should be posted 20 | * **flair_text**: The flair text to set for the post 21 | * **flair_css**: The flair css class to set for the post 22 | * **distinguish**: Whether the post should be distinguished (true or false). Defaults to false 23 | * **sticky**: Whether the post should be made sticky (true or false). Defaults to false 24 | * **contest_mode**: Whether to turn contest mode on for the post (true or false). Defaults to false 25 | 26 | You can use the current Date / Time in the title or body of your Post. For this include a place holder that looks like `{{date }}`. The format section should be a formatting string using [python strftime formatting](http://strftime.org/). 27 | 28 | You can specify multiple titles / links using the multiline syntax (see `text`), one title / link per line. Each submission will take the next item from the list. This can for example be used to prepare several submissions and post them in a specified interval. 29 | 30 | ##Example 31 | 32 | --- 33 | First: 24.4.2015 21:10 34 | Repeat: 5 months 35 | Sticky: false 36 | Distinguish: true 37 | Contest_mode: false 38 | Title: TestPost 39 | Text: | 40 | This is a test post 41 | 42 | It is multiline 43 | --- 44 | First: 24.4.2015 21:12 45 | Repeat: 5 weeks 46 | Times: 5 47 | Flair_Text: Test 48 | Flair_CSS: TestCSS 49 | Sticky: false 50 | Distinguish: true 51 | Contest_mode: false 52 | Title: TestPost - {{date %B %d, %Y}} 53 | Text: | 54 | This is a second test post 55 | 56 | It is also *multiline* 57 | --- 58 | First: 23.11.2015 20:06 59 | Repeat: 2 minutes 60 | Times: 5 61 | Title: | 62 | Img1 63 | Img2 64 | Img3 65 | Img4 66 | Img5 67 | Link: | 68 | http://imgur.com/gallery/H4yC8C2 69 | http://imgur.com/gallery/qPwfEnt 70 | http://imgur.com/gallery/1s1yuZ6 71 | http://imgur.com/gallery/G0IKECz 72 | http://imgur.com/gallery/io1D2 73 | Text: Enjoy! 74 | -------------------------------------------------------------------------------- /ScheduleBot/ScheduleBot.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bot to post on a schedule but posts on a given user so it can be edited later 3 | Written by /u/SmBe19 4 | """ 5 | 6 | import praw 7 | import time 8 | import logging 9 | import logging.handlers 10 | import re 11 | import threading 12 | import OAuth2Util 13 | import ScheduledPost 14 | 15 | # ### USER CONFIGURATION ### # 16 | 17 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 18 | USERAGENT = "" 19 | 20 | # The name of the subreddits to post to. e.g. "funny" 21 | SUBREDDITS = ["", ""] 22 | 23 | # The time in seconds the bot should sleep until it checks the inbox again. 24 | SLEEP_INBOX = 60 25 | 26 | # ### END USER CONFIGURATION ### # 27 | 28 | # ### BOT CONFIGURATION ### # 29 | DATE_RE = re.compile("\{\{date (.+?)\}\}") 30 | # ### END BOT CONFIGURATION ### # 31 | 32 | # ### LOGGING CONFIGURATION ### # 33 | LOG_LEVEL = logging.INFO 34 | LOG_FILENAME = "bot.log" 35 | LOG_FILE_BACKUPCOUNT = 5 36 | LOG_FILE_MAXSIZE = 1024 * 256 37 | # ### END LOGGING CONFIGURATION ### # 38 | 39 | # ### EXTERNAL CONFIG FILE ### # 40 | try: 41 | # A file containing data for global constants. 42 | import bot 43 | for k in dir(bot): 44 | if k.upper() in globals(): 45 | globals()[k.upper()] = getattr(bot, k) 46 | except ImportError: 47 | pass 48 | # ### END EXTERNAL CONFIG FILE ### # 49 | 50 | # ### LOGGING SETUP ### # 51 | log = logging.getLogger("bot") 52 | log.setLevel(LOG_LEVEL) 53 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 54 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 55 | log_stderrHandler = logging.StreamHandler() 56 | log_stderrHandler.setFormatter(log_formatter) 57 | log.addHandler(log_stderrHandler) 58 | if LOG_FILENAME is not None: 59 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 60 | log_fileHandler.setFormatter(log_formatter_file) 61 | log.addHandler(log_fileHandler) 62 | # ### END LOGGING SETUP ### # 63 | 64 | def check_inbox(r, reschedule): 65 | Poster.lock.acquire() 66 | for mail in r.get_unread(): 67 | if not mail.was_comment: 68 | if mail.body.strip().lower() == "schedule": 69 | mail.mark_as_read() 70 | reschedule.set() 71 | log.info("reschedule") 72 | Poster.lock.release() 73 | 74 | def repl_date(matchobj): 75 | return time.strftime(matchobj.group(1)) 76 | 77 | class Poster (threading.Thread): 78 | lock = threading.Lock() 79 | 80 | def __init__(self, o, subs, reschedule, weredone): 81 | threading.Thread.__init__(self) 82 | self.o = o 83 | self.subs = subs 84 | self.reschedule = reschedule 85 | self.weredone = weredone 86 | 87 | def run(self): 88 | while True: 89 | Poster.lock.acquire() 90 | scheduled_posts = [] 91 | for sub in self.subs: 92 | scheduled_posts.extend(ScheduledPost.read_config(sub)) 93 | Poster.lock.release() 94 | 95 | while True: 96 | try: 97 | Poster.lock.acquire() 98 | self.o.refresh() 99 | Poster.lock.release() 100 | 101 | sleep_time = float("inf") 102 | nextPost = None 103 | for p in scheduled_posts: 104 | if p.get_time_until_next_post() < sleep_time: 105 | sleep_time = p.get_time_until_next_post() 106 | nextPost = p 107 | nextPostNumber = nextPost.get_next_post_number() 108 | assert nextPostNumber >= 0 or sleep_time == float("inf") 109 | log.info("sleep submission for %s s(%s)", sleep_time, time.strftime("%d.%m.%Y %H:%M", time.localtime(nextPost.get_next_post_time()))) 110 | 111 | if sleep_time == float("inf"): 112 | self.reschedule.wait() 113 | elif not self.reschedule.wait(sleep_time): 114 | Poster.lock.acquire() 115 | titles = nextPost.title.split("\n") 116 | titleFormatted = titles[nextPostNumber % len(titles)] 117 | titleFormatted = DATE_RE.sub(repl_date, titleFormatted) 118 | textFormatted = nextPost.text 119 | if textFormatted is not None: 120 | textFormatted = DATE_RE.sub(repl_date, textFormatted) 121 | if nextPost.link is not None: 122 | links = nextPost.link.split("\n") 123 | link = links[nextPostNumber % len(links)] 124 | submission = nextPost.sub.submit(titleFormatted, url=link, resubmit=True) 125 | if textFormatted is not None and len(textFormatted) > 0: 126 | submission.add_comment(textFormatted) 127 | else: 128 | if textFormatted is None: 129 | textFormatted = "..." 130 | submission = nextPost.sub.submit(titleFormatted, textFormatted) 131 | submission.set_flair(flair_text=nextPost.flair_text, flair_css_class=nextPost.flair_css) 132 | if nextPost.distinguish: 133 | submission.distinguish() 134 | if nextPost.sticky: 135 | submission.sticky() 136 | if nextPost.contest_mode: 137 | submission.set_contest_mode(nextPost.contest_mode) 138 | log.info("submitted") 139 | Poster.lock.release() 140 | 141 | if self.reschedule.is_set(): 142 | self.reschedule.clear() 143 | break 144 | 145 | # Allows the bot to exit on ^C, all other exceptions are ignored 146 | except KeyboardInterrupt: 147 | log.info("We're almost done") 148 | break 149 | except Exception as e: 150 | log.error("Exception %s", e, exc_info=True) 151 | import traceback 152 | traceback.print_exc() 153 | Poster.lock.acquire(False) 154 | Poster.lock.release() 155 | 156 | if self.weredone.is_set(): 157 | break 158 | 159 | # main procedure 160 | def run_bot(): 161 | r = praw.Reddit(USERAGENT) 162 | o = OAuth2Util.OAuth2Util(r) 163 | o.refresh() 164 | subs = [r.get_subreddit(x) for x in SUBREDDITS] 165 | 166 | log.info("Start bot for subreddits %s", SUBREDDITS) 167 | 168 | reschedule = threading.Event() 169 | weredone = threading.Event() 170 | 171 | thread = Poster(o, subs, reschedule, weredone) 172 | thread.deamon = True 173 | thread.start() 174 | 175 | while True: 176 | try: 177 | o.refresh() 178 | check_inbox(r, reschedule) 179 | 180 | log.info("sleep inbox for %s s", SLEEP_INBOX) 181 | time.sleep(SLEEP_INBOX) 182 | # Allows the bot to exit on ^C, all other exceptions are ignored 183 | except KeyboardInterrupt: 184 | log.info("We're almost done") 185 | break 186 | except Exception as e: 187 | log.error("Exception %s", e, exc_info=True) 188 | import traceback 189 | traceback.print_exc() 190 | Poster.lock.acquire(False) 191 | Poster.lock.release() 192 | 193 | weredone.set() 194 | reschedule.set() 195 | log.info("We're done") 196 | 197 | 198 | if __name__ == "__main__": 199 | if not USERAGENT: 200 | log.error("missing useragent") 201 | elif not SUBREDDITS: 202 | log.error("missing subreddits") 203 | else: 204 | run_bot() 205 | -------------------------------------------------------------------------------- /ScheduleBot/ScheduledPost.py: -------------------------------------------------------------------------------- 1 | import praw 2 | import time 3 | import re 4 | 5 | # ### BOT CONFIGURATION ### # 6 | CONFIG_WIKIPAGE = "schedulebot-config" 7 | # ### END BOT CONFIGURATION ### # 8 | 9 | class ScheduledPost: 10 | def __init__(self, sub, first, title="Scheduled Post", text=None, link=None, repeat="-1", times="-1", flair_text="", flair_css="", distinguish="False", sticky="False", contest_mode="False"): 11 | self.sub = sub 12 | self.first = first 13 | self.title = title 14 | self.text = text 15 | self.link = link 16 | self.repeat = repeat 17 | self.times = int(times) 18 | self.flair_text = flair_text 19 | self.flair_css = flair_css 20 | self.distinguish = distinguish.lower() == "true" 21 | self.sticky = sticky.lower() == "true" 22 | self.contest_mode = contest_mode.lower() == "true" 23 | 24 | try: 25 | self.first = time.mktime(time.strptime(self.first, "%d.%m.%Y %H:%M %z")) 26 | except ValueError: 27 | self.first = time.mktime(time.strptime(self.first, "%d.%m.%Y %H:%M")) 28 | 29 | num = int(repeat.split(" ")[0]) 30 | unit = repeat.split(" ")[-1].lower() 31 | if unit == "years": 32 | num *= 365*24*60*60 33 | elif unit == "months": 34 | num *= 30*24*60*60 35 | elif unit == "weeks": 36 | num *= 7*24*60*60 37 | elif unit == "days": 38 | num *= 24*60*60 39 | elif unit == "hours": 40 | num *= 60*60 41 | elif unit == "minutes": 42 | num *= 60 43 | elif unit == "seconds": 44 | num *= 1 45 | else: 46 | num = -1 47 | 48 | if num == 0: 49 | num = 1 50 | 51 | self.repeat = num 52 | 53 | def get_time_until_next_post(self): 54 | diff = time.time() - self.first 55 | if diff < 0: 56 | return -diff 57 | if self.repeat < 0: 58 | return float("inf") 59 | if self.times > 0: 60 | if diff // self.repeat >= self.times - 1: 61 | return float("inf") 62 | used = diff % self.repeat 63 | return self.repeat - used 64 | 65 | def get_next_post_number(self): 66 | diff = time.time() - self.first 67 | if diff < 0: 68 | return 0 69 | if self.repeat < 0: 70 | return -1 71 | return int(diff // self.repeat) + 1 72 | 73 | def get_next_post_time(self): 74 | return time.time() + self.get_time_until_next_post() 75 | 76 | def repl_indentation(matchobj): 77 | return "\r" * matchobj.group(0).count(matchobj.group(1)) 78 | 79 | def read_config(sub): 80 | scheduled_posts = [] 81 | config = sub.get_wiki_page(CONFIG_WIKIPAGE).content_md 82 | config = config.replace("\r\n", "\n") 83 | rules = list(filter(len, config.split("---\n"))) 84 | if len(rules) < 1: 85 | return scheduled_posts 86 | match = re.match("^\s+", rules[0]) 87 | if not match: 88 | print("Error: Could not define indentation") 89 | return scheduled_posts 90 | indentation = match.group(0) 91 | for rule in rules: 92 | lines = [re.sub("^({0})+".format(indentation), repl_indentation, line) for line in rule.split("\n")] 93 | properties = {} 94 | last_property = "" 95 | for line in lines: 96 | level = line.count("\r") 97 | if level == 1: 98 | last_property = line.replace("\r", "").split(": ")[0].strip().lower() 99 | properties[last_property] = line.replace("\r", "")[len(last_property) + 2:].strip() 100 | else: 101 | properties[last_property] += "\n" + line.replace("\r", "").strip() 102 | 103 | for key in properties: 104 | if properties[key].startswith("|\n"): 105 | properties[key] = properties[key][2:] 106 | # print(key, ":", properties[key]) 107 | try: 108 | scheduled_posts.append(ScheduledPost(sub, **properties)) 109 | except TypeError: 110 | print("Rule for post with title", properties["title"], "is not correct!") 111 | 112 | return scheduled_posts 113 | -------------------------------------------------------------------------------- /ScheduleBot/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=submit,privatemessages,modflair 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /UserListKeeper/.gitignore: -------------------------------------------------------------------------------- 1 | oauth.txt 2 | done.txt -------------------------------------------------------------------------------- /UserListKeeper/README.md: -------------------------------------------------------------------------------- 1 | # UserListKeeper 2 | Keeps a list of users that meet a certain criteria (e.g. they have a post with a certain link flair). The list is kept in a wiki page. If an entry is older than some treshold it is removed. -------------------------------------------------------------------------------- /UserListKeeper/UserListKeeper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Keep a list of users that posted a "matching" post. 5 | Written by /u/SmBe19 6 | """ 7 | 8 | import praw 9 | import praw.errors 10 | import time 11 | import logging 12 | import logging.handlers 13 | import OAuth2Util 14 | 15 | # ### USER CONFIGURATION ### # 16 | 17 | # The bot's useragent. It should contain a short description of what it does and your username. e.g. "RSS Bot by /u/SmBe19" 18 | USERAGENT = "" 19 | 20 | # The name of the subreddit to post to. e.g. "funny" 21 | SUBREDDIT = "" 22 | 23 | # The name of the subreddit to post the wiki page to 24 | WIKI_SUBREDDIT = "" 25 | 26 | # The name of the wiki page to post the list to 27 | WIKI_PAGE = "UserListKeeper" 28 | 29 | # The flair a post needs to have so it's added to the list 30 | ADD_FLAIR = "offer to mod" 31 | 32 | # Time in seconds until a user is removed from the list 33 | LEAVE_TIME = 30 * 24 * 3600 # one month 34 | 35 | # The time in seconds the bot should sleep until it checks again. 36 | SLEEP = 60*60 37 | 38 | # ### END USER CONFIGURATION ### # 39 | 40 | # ### BOT CONFIGURATION ### # 41 | DONE_CONFIGFILE = "done.txt" 42 | USERLIST_CONFIGFILE = "userlist.txt" 43 | # ### END BOT CONFIGURATION ### # 44 | 45 | # ### LOGGING CONFIGURATION ### # 46 | LOG_LEVEL = logging.INFO 47 | LOG_FILENAME = "bot.log" 48 | LOG_FILE_BACKUPCOUNT = 5 49 | LOG_FILE_MAXSIZE = 1024 * 256 50 | # ### END LOGGING CONFIGURATION ### # 51 | 52 | # ### EXTERNAL CONFIG FILE ### # 53 | try: 54 | # A file containing data for global constants. 55 | import bot 56 | for k in dir(bot): 57 | if k.upper() in globals(): 58 | globals()[k.upper()] = getattr(bot, k) 59 | except ImportError: 60 | pass 61 | # ### END EXTERNAL CONFIG FILE ### # 62 | 63 | # ### LOGGING SETUP ### # 64 | log = logging.getLogger("bot") 65 | log.setLevel(LOG_LEVEL) 66 | log_formatter = logging.Formatter('%(levelname)s: %(message)s') 67 | log_formatter_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 68 | log_stderrHandler = logging.StreamHandler() 69 | log_stderrHandler.setFormatter(log_formatter) 70 | log.addHandler(log_stderrHandler) 71 | if LOG_FILENAME is not None: 72 | log_fileHandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_FILE_MAXSIZE, backupCount=LOG_FILE_BACKUPCOUNT) 73 | log_fileHandler.setFormatter(log_formatter_file) 74 | log.addHandler(log_fileHandler) 75 | # ### END LOGGING SETUP ### # 76 | 77 | # ### DONE CONFIG FILE ### # 78 | def read_config_done(): 79 | done = set() 80 | try: 81 | with open(DONE_CONFIGFILE, "r") as f: 82 | for line in f: 83 | if line.strip(): 84 | done.add(line.strip()) 85 | except OSError: 86 | log.info("%s not found.", DONE_CONFIGFILE) 87 | return done 88 | 89 | def write_config_done(done): 90 | with open(DONE_CONFIGFILE, "w") as f: 91 | for d in done: 92 | if d: 93 | f.write(d + "\n") 94 | 95 | def read_config_userlist(): 96 | users = {} 97 | try: 98 | with open(USERLIST_CONFIGFILE, "r") as f: 99 | for line in f: 100 | sp = line.strip().split("\t") 101 | assert len(sp) == 7, sp 102 | users[sp[0]] = User(*sp) 103 | except OSError: 104 | log.info("%s not found.", USERLIST_CONFIGFILE) 105 | return users 106 | 107 | def write_config_userlist(users): 108 | with open(USERLIST_CONFIGFILE, "w") as f: 109 | for user in users: 110 | print(users[user].get_for_file(), file=f) 111 | # ### END DONE CONFIG FILE ### # 112 | 113 | # ### MAIN PROCEDURE ### # 114 | class User: 115 | 116 | def __init__(self, name, posting, added, link_karma, comment_karma, age, subs): 117 | self.name = name 118 | self.posting = posting 119 | self.added = float(added) 120 | self.link_karma = link_karma 121 | self.comment_karma = comment_karma 122 | self.age = float(age) 123 | self.subs = int(subs) 124 | 125 | def get_for_file(self): 126 | return "\t".join(map(str, [self.name, self.posting, self.added, self.link_karma, self.comment_karma, self.age, self.subs])) 127 | 128 | def get_for_table(self): 129 | return "| {} |".format(" | ".join(map(str, ["/u/{}".format(self.name), "[link]({})".format(self.posting), self.link_karma, self.comment_karma, self.age // (24*3600), self.subs]))) 130 | 131 | 132 | def add_user(users, submission): 133 | user = submission.author 134 | # deleted 135 | if user is None: 136 | return 137 | try: 138 | log.info("add user %s", user.name) 139 | nuser = User(user.name, submission.permalink, submission.created_utc, user.link_karma, user.comment_karma, time.time() - user.created_utc, 0) 140 | if nuser.name in users: 141 | if nuser.added < users[nuser.name].added: 142 | log.info("newer posting for %s already registered", user.name) 143 | return 144 | users[nuser.name] = nuser 145 | except AttributeError: 146 | log.info("user %s is suspended", user.name) 147 | except praw.errors.NotFound: 148 | log.info("user %s is banned", user.name) 149 | 150 | 151 | def check_posts(r, users, done): 152 | log.info("look for new posts") 153 | sub = r.get_subreddit(SUBREDDIT) 154 | sub.refresh() 155 | for submission in sub.get_new(limit=1000): 156 | if submission.name in done: 157 | continue 158 | if submission.link_flair_text is not None and submission.link_flair_text.lower() == ADD_FLAIR: 159 | add_user(users, submission) 160 | done.add(submission.name) 161 | if time.time() - submission.created_utc > LEAVE_TIME: 162 | log.info("reached age limit") 163 | break 164 | 165 | 166 | def remove_old_users(users): 167 | todel = [] 168 | for user in users: 169 | if time.time() - users[user].added > LEAVE_TIME: 170 | todel.append(users[user]) 171 | for user in todel: 172 | if user in users: 173 | del users[user] 174 | log.info("remove user %s", user) 175 | 176 | 177 | def update_wiki_page(r, users): 178 | entry = ["| User | Link | Link Karma | Comment Karma | Age [d] | Subreddits |", 179 | "| ---- | ---- | ---------- | ------------- | ------- | ---------- |"] 180 | usertable = [] 181 | for username in users: 182 | usertable.append(users[username].get_for_table()) 183 | entry.extend(sorted(usertable)) 184 | r.edit_wiki_page(WIKI_SUBREDDIT, WIKI_PAGE, "\n".join(entry)) 185 | log.info("update wiki page %s/%s", WIKI_SUBREDDIT, WIKI_PAGE) 186 | 187 | 188 | def run_bot(): 189 | r = praw.Reddit(USERAGENT) 190 | o = OAuth2Util.OAuth2Util(r) 191 | o.refresh() 192 | 193 | log.info("Start bot for subreddit %s", SUBREDDIT) 194 | 195 | done = read_config_done() 196 | users = read_config_userlist() 197 | 198 | while True: 199 | try: 200 | o.refresh() 201 | 202 | check_posts(r, users, done) 203 | remove_old_users(users) 204 | update_wiki_page(r, users) 205 | 206 | # Allows the bot to exit on ^C, all other exceptions are ignored 207 | except KeyboardInterrupt: 208 | break 209 | except Exception as e: 210 | log.error("Exception %s", e, exc_info=True) 211 | 212 | write_config_done(done) 213 | write_config_userlist(users) 214 | log.info("sleep for %s s", SLEEP) 215 | time.sleep(SLEEP) 216 | 217 | write_config_done(done) 218 | write_config_userlist(users) 219 | # ### END MAIN PROCEDURE ### # 220 | 221 | # ### START BOT ### # 222 | if __name__ == "__main__": 223 | if not USERAGENT: 224 | log.error("missing useragent") 225 | elif not SUBREDDIT: 226 | log.error("missing subreddit") 227 | else: 228 | run_bot() 229 | # ### END START BOT ### # 230 | -------------------------------------------------------------------------------- /UserListKeeper/oauth_template.txt: -------------------------------------------------------------------------------- 1 | # Rename this file to oauth.ini 2 | 3 | [app] 4 | scope=identity,read,wikiedit 5 | refreshable=True 6 | app_key=thisistheid 7 | app_secret=ThisIsTheSecretDoNotShare 8 | 9 | [server] 10 | server_mode=False 11 | url=127.0.0.1 12 | port=65010 13 | redirect_path=authorize_callback 14 | link_path=oauth 15 | 16 | [token] 17 | token=None 18 | refresh_token=None 19 | -------------------------------------------------------------------------------- /UserListKeeper/userlist.txt: -------------------------------------------------------------------------------- 1 | _e_e_e_ https://www.reddit.com/r/needamod/comments/4nwp98/offer_to_mod/ 1465838652.0 2512 28443 8739620.555735111 0 2 | Nightslash360 https://www.reddit.com/r/needamod/comments/4qjwn1/i_would_like_to_help_out_in_the_community_ive/ 1467261546.0 2428 3913 77808613.60959196 0 3 | PreviousHistory https://www.reddit.com/r/needamod/comments/4qmxid/willing_to_mod_if_you_need_previous_mod_experience/ 1467308286.0 3299 813 62792262.57091689 0 4 | lordmalifico https://www.reddit.com/r/needamod/comments/4o5tot/looking_to_be_a_moderator_again/ 1465969042.0 8489 55026 159861949.60011506 0 5 | jtww https://www.reddit.com/r/needamod/comments/4o45jy/looking_to_help_mod_any_nature_related_subreddits/ 1465944132.0 1115 1870 138910689.573349 0 6 | AmmianusMarcellinus https://www.reddit.com/r/needamod/comments/4r1rse/offer_to_be_a_mod_preferably_an_animal_history/ 1467547557.0 121717 28094 78054889.65604305 0 7 | Tanner_Twaggs https://www.reddit.com/r/needamod/comments/4p23lv/looking_to_be_a_mod_active_at_least_3_hours_a_day/ 1466471969.0 2052 14167 50970720.61556792 0 8 | GrittyGrits https://www.reddit.com/r/needamod/comments/4o90an/looking_to_mod_for_video_game_subreddits/ 1466017364.0 41 86 33156156.867285013 0 9 | ZeStumpinator https://www.reddit.com/r/needamod/comments/4qpseb/anyone_wanting_to_mimick_another_subreddits_style/ 1467345331.0 13759 6534 8547028.565272093 0 10 | MyNiggaIsWorking https://www.reddit.com/r/needamod/comments/4odx9t/i_would_like_to_be_mod/ 1466091280.0 541 5918 22906724.555022955 0 11 | Addictedtowhitegirls https://www.reddit.com/r/needamod/comments/4or2zz/offer_to_mod_2_year_redditor_always_on_reddit/ 1466295945.0 1139 9430 80503150.56971788 0 12 | katiedaboss https://www.reddit.com/r/needamod/comments/4nfyqi/i_cant_code_but_will_be_happy_to_mod_in_other/ 1465560236.0 25 229 9412887.604074001 0 13 | ThatITguy2015 https://www.reddit.com/r/needamod/comments/4r11jn/id_like_to_be_a_mod_preferably_for_a_pc_or_gpu/ 1467529071.0 1 3224 19770399.628210068 0 14 | MeowZedong- https://www.reddit.com/r/needamod/comments/4oat5b/looking_to_mod/ 1466039458.0 1 743 66638318.88214803 0 15 | Moshifan100 https://www.reddit.com/r/needamod/comments/4my2xy/i_would_like_to_help_mod_a_subreddit_some_past/ 1465288369.0 167 238 48536172.04709697 0 16 | StfnJT https://www.reddit.com/r/needamod/comments/4r23cm/offer_to_mod_tech_subreddits_apple_pc/ 1467554145.0 739 249 35525790.58810711 0 17 | TOaFK https://www.reddit.com/r/needamod/comments/4o2dwd/offer_to_mod/ 1465923426.0 2155 1310 107056895.5611589 0 18 | giraffedog123 https://www.reddit.com/r/needamod/comments/4n2ksl/offers_to_mod/ 1465349609.0 115 226 12974168.609468937 0 19 | UNLUCK3 https://www.reddit.com/r/needamod/comments/4ouj0i/new_user_offering_to_mod_any_sub/ 1466361463.0 12 11 5329574.563182116 0 20 | RogerDeanVenture https://www.reddit.com/r/needamod/comments/4odi38/looking_to_mod/ 1466086306.0 5186 103880 176234440.5794189 0 21 | CRABS_GIVER https://www.reddit.com/r/needamod/comments/4pwal8/i_too_would_like_to_become_a_moderator/ 1466917474.0 1 1575 1626650.5667190552 0 22 | Aquilon96 https://www.reddit.com/r/needamod/comments/4q35v8/id_like_to_be_a_moderator/ 1467031876.0 107 252 23009674.705713987 0 23 | gotti9660 https://www.reddit.com/r/needamod/comments/4omj23/offer_to_mod_some_css_experience_some_moderation/ 1466214152.0 410 125 28742087.87012911 0 24 | MrBauer24 https://www.reddit.com/r/needamod/comments/4o27gl/looking_to_mod/ 1465921365.0 368 -79 96713814.56441593 0 25 | Optimus_Pr1me https://www.reddit.com/r/needamod/comments/4r2x6s/offer_to_mod_various_subs_i_am_competent_in_css/ 1467567168.0 2076 407 25440992.570518017 0 26 | Magnum26 https://www.reddit.com/r/needamod/comments/4p5fnb/expert_css/ 1466526042.0 4169 1019 126786939.55359507 0 27 | revolution486 https://www.reddit.com/r/needamod/comments/4oi1m1/i_want_to_b_a_moderator_for_anyone_who_wants_help/ 1466146793.0 817 644 115488537.58557296 0 28 | Beastness https://www.reddit.com/r/needamod/comments/4ppg9m/experienced_mod_looking_to_mod_some_nsfw_subs/ 1466805331.0 89 730 61950745.569670916 0 29 | Son_Of_A_Diddley https://www.reddit.com/r/needamod/comments/4nyftc/ive_worked_for_a_few_small_subreddits_id_like_to/ 1465859723.0 10691 2471 14057893.595383883 0 30 | Beetlejuice22 https://www.reddit.com/r/needamod/comments/4npgsm/i_can_mod_if_anyone_needs_me/ 1465719991.0 1 0 9119728.552242994 0 31 | ovivios https://www.reddit.com/r/needamod/comments/4ogogs/looking_to_mod_for_css_specifically_and_can_do/ 1466124364.0 349 6333 155345185.71179295 0 32 | AWhaleAteMyDog https://www.reddit.com/r/needamod/comments/4o54vv/offering_to_mod/ 1465957795.0 1265 33 86232987.594378 0 33 | ThunderSpruceTree https://www.reddit.com/r/needamod/comments/4o9esk/looking_to_mod_for_any_videogame_subreddit/ 1466021843.0 1 1626 43590210.62369299 0 34 | Lewisholyland https://www.reddit.com/r/needamod/comments/4occmu/looking_to_mod_any_type_of_sub/ 1466066120.0 19693 2468 36483309.55062604 0 35 | PauseAGame https://www.reddit.com/r/needamod/comments/4o1mke/if_anyone_needs_some_mods_you_can_ask_me/ 1465914258.0 7428 690 13679643.657748938 0 36 | bentheawesome69 https://www.reddit.com/r/needamod/comments/4r4so7/experience_mod_willing_to_help_any_subreddit/ 1467594522.0 93 4565 13676027.93772006 0 37 | Fireheart318s_Reddit https://www.reddit.com/r/needamod/comments/4pk4x2/offering_to_mod_a_gamingrelated_sub/ 1466730319.0 712 200 15894507.570725918 0 38 | ccousins https://www.reddit.com/r/needamod/comments/4nz79i/offer_to_mod_any_type_or_size_of_subreddit/ 1465870521.0 270 768 110305111.57211494 0 39 | nioaka https://www.reddit.com/r/needamod/comments/4niodl/offers_to_mod/ 1465595797.0 1 37 3170203.5531549454 0 40 | lalaffel https://www.reddit.com/r/needamod/comments/4ol3u6/anyone_need_a_mod/ 1466193870.0 2782 1312 28405203.60023403 0 41 | Pudmeister https://www.reddit.com/r/needamod/comments/4qxux9/do_you_need_an_experienced_mod/ 1467476513.0 488 16293 111354634.55585098 0 42 | --------------------------------------------------------------------------------