diff options
author | jwansek <eddie.atten.ea29@gmail.com> | 2020-11-24 00:14:19 +0000 |
---|---|---|
committer | jwansek <eddie.atten.ea29@gmail.com> | 2020-11-24 00:14:19 +0000 |
commit | dbd7b0f7fc39331e9c322b827d86bdd33b149f9c (patch) | |
tree | 78d0ab2f48220ac92537e6c78c796ede9c2efd1f | |
parent | 04bda312ef994b2d66b455d0b2b9538de8f6915e (diff) | |
download | SmallYTChannelBot-dbd7b0f7fc39331e9c322b827d86bdd33b149f9c.tar.gz SmallYTChannelBot-dbd7b0f7fc39331e9c322b827d86bdd33b149f9c.zip |
restructed onceaday.py, changed the main() function, started fixing auto-restarting
-rw-r--r-- | actions.log | 105 | ||||
-rwxr-xr-x | database.py | 81 | ||||
-rwxr-xr-x | onceaday.py | 97 | ||||
-rwxr-xr-x | readme.md | 5 | ||||
-rwxr-xr-x | subreddit.py | 204 |
5 files changed, 251 insertions, 241 deletions
diff --git a/actions.log b/actions.log new file mode 100644 index 0000000..6d7b029 --- /dev/null +++ b/actions.log @@ -0,0 +1,105 @@ +11606 [2020-11-23 23:04:20,072] Generating new fontManager, this may take some time... +11606 [2020-11-23 23:04:21,527] Failed to extract font properties from /usr/share/fonts/truetype/noto/NotoColorEmoji.ttf: In FT2Font: Can not load face. Unknown file format. +11606 [2020-11-23 23:04:23,685] Starting every day program... +11652 [2020-11-23 23:04:39,072] Starting every day program... +11652 [2020-11-23 23:04:39,081] Updating database statistics... +11708 [2020-11-23 23:05:35,008] Starting every day program... +11708 [2020-11-23 23:05:35,015] Updating database statistics... +11708 [2020-11-23 23:05:35,174] Posting and updating wiki... +11859 [2020-11-23 23:07:56,084] Starting every day program... +11859 [2020-11-23 23:07:56,090] Updating database statistics... +11859 [2020-11-23 23:07:56,259] Posting and updating wiki... +11859 [2020-11-23 23:08:02,226] Formatting leaderboard... +11859 [2020-11-23 23:08:02,620] Updating sidebar... +11859 [2020-11-23 23:08:06,503] Updated in old reddit... +11859 [2020-11-23 23:08:06,509] Completed. +11859 [2020-11-23 23:08:06,514] Called OAD prog @ Nov 23 2020 23:08:06 +12060 [2020-11-23 23:10:12,843] Starting every day program... +12060 [2020-11-23 23:10:12,878] Updating database statistics... +12060 [2020-11-23 23:10:12,990] Posting and updating wiki... +12060 [2020-11-23 23:10:21,422] Formatting leaderboard... +12060 [2020-11-23 23:10:21,832] Updating sidebar... +12060 [2020-11-23 23:10:25,652] Updated in old reddit... +12060 [2020-11-23 23:10:25,664] Completed. +12060 [2020-11-23 23:10:25,670] Called OAD prog @ Nov 23 2020 23:10:25 +12460 [2020-11-23 23:14:28,891] Starting every day program... +12460 [2020-11-23 23:14:28,897] Updating database statistics... +12460 [2020-11-23 23:14:28,900] Formatting leaderboard... +12460 [2020-11-23 23:14:30,236] Called OAD prog @ Nov 23 2020 23:14:30 +12603 [2020-11-23 23:15:55,186] Starting every day program... +12603 [2020-11-23 23:15:55,192] Updating database statistics... +12603 [2020-11-23 23:15:55,196] Formatting leaderboard... +12603 [2020-11-23 23:15:56,454] Called OAD prog @ Nov 23 2020 23:15:56 +12741 [2020-11-23 23:18:09,677] Starting every day program... +12741 [2020-11-23 23:18:09,683] Updating database statistics... +12741 [2020-11-23 23:18:09,686] Formatting leaderboard... +12755 [2020-11-23 23:18:17,841] Starting every day program... +12755 [2020-11-23 23:18:17,847] Updating database statistics... +12755 [2020-11-23 23:18:17,851] Formatting leaderboard... +12755 [2020-11-23 23:18:19,699] Called OAD prog @ Nov 23 2020 23:18:19 +12786 [2020-11-23 23:19:43,549] Starting every day program... +12786 [2020-11-23 23:19:43,556] Updating database statistics... +12786 [2020-11-23 23:19:43,559] Formatting leaderboard... +12807 [2020-11-23 23:20:00,535] Starting every day program... +12807 [2020-11-23 23:20:00,546] Updating database statistics... +12807 [2020-11-23 23:20:00,551] Formatting leaderboard... +12807 [2020-11-23 23:20:02,453] Called OAD prog @ Nov 23 2020 23:20:02 +12840 [2020-11-23 23:20:40,710] Starting every day program... +12840 [2020-11-23 23:20:40,732] Updating database statistics... +12840 [2020-11-23 23:20:40,740] Formatting leaderboard... +12840 [2020-11-23 23:20:42,728] Called OAD prog @ Nov 23 2020 23:20:42 +12972 [2020-11-23 23:22:12,663] Starting every day program... +12972 [2020-11-23 23:22:12,669] Updating database statistics... +12972 [2020-11-23 23:22:12,672] Formatting leaderboard... +12972 [2020-11-23 23:22:13,894] Called OAD prog @ Nov 23 2020 23:22:13 +12998 [2020-11-23 23:22:45,534] Starting every day program... +12998 [2020-11-23 23:22:45,540] Updating database statistics... +12998 [2020-11-23 23:22:45,543] Formatting leaderboard... +12998 [2020-11-23 23:22:46,805] Called OAD prog @ Nov 23 2020 23:22:46 +13060 [2020-11-23 23:24:00,476] Starting every day program... +13060 [2020-11-23 23:24:00,482] Updating database statistics... +13060 [2020-11-23 23:24:00,487] Formatting leaderboard... +13060 [2020-11-23 23:24:02,247] Called OAD prog @ Nov 23 2020 23:24:02 +13089 [2020-11-23 23:24:31,417] Starting every day program... +13089 [2020-11-23 23:24:31,436] Updating database statistics... +13089 [2020-11-23 23:24:31,442] Formatting leaderboard... +13089 [2020-11-23 23:24:32,720] Called OAD prog @ Nov 23 2020 23:24:32 +13120 [2020-11-23 23:24:54,973] Starting every day program... +13120 [2020-11-23 23:24:54,984] Updating database statistics... +13120 [2020-11-23 23:24:54,990] Formatting leaderboard... +13120 [2020-11-23 23:24:56,162] Called OAD prog @ Nov 23 2020 23:24:56 +13135 [2020-11-23 23:25:14,522] Starting every day program... +13135 [2020-11-23 23:25:14,528] Updating database statistics... +13135 [2020-11-23 23:25:14,531] Formatting leaderboard... +13135 [2020-11-23 23:25:15,766] Called OAD prog @ Nov 23 2020 23:25:15 +13210 [2020-11-23 23:26:36,168] Starting every day program... +13210 [2020-11-23 23:26:36,175] Updating database statistics... +13210 [2020-11-23 23:26:36,178] Formatting leaderboard... +13210 [2020-11-23 23:26:37,287] Called OAD prog @ Nov 23 2020 23:26:37 +13273 [2020-11-23 23:28:11,408] Starting every day program... +13273 [2020-11-23 23:28:11,414] Updating database statistics... +13273 [2020-11-23 23:28:11,417] Formatting leaderboard... +13273 [2020-11-23 23:28:13,703] Updated in old reddit... +13273 [2020-11-23 23:28:13,709] Completed. +13273 [2020-11-23 23:28:13,714] Called OAD prog @ Nov 23 2020 23:28:13 +13529 [2020-11-23 23:31:05,470] Starting every day program... +13529 [2020-11-23 23:31:05,476] Updating database statistics... +13529 [2020-11-23 23:31:05,479] Formatting leaderboard... +13529 [2020-11-23 23:31:05,753] Updating sidebar... +13529 [2020-11-23 23:31:06,650] Called OAD prog @ Nov 23 2020 23:31:06 +13549 [2020-11-23 23:31:29,883] Starting every day program... +13549 [2020-11-23 23:31:29,889] Updating database statistics... +13549 [2020-11-23 23:31:29,893] Formatting leaderboard... +13549 [2020-11-23 23:31:30,194] Updating sidebar... +13549 [2020-11-23 23:31:31,157] Called OAD prog @ Nov 23 2020 23:31:31 +13701 [2020-11-23 23:33:46,975] Starting every day program... +13701 [2020-11-23 23:33:46,986] Updating database statistics... +13701 [2020-11-23 23:33:46,993] Formatting leaderboard... +13701 [2020-11-23 23:33:47,269] Updating sidebar... +13701 [2020-11-23 23:33:48,575] Called OAD prog @ Nov 23 2020 23:33:48 +13756 [2020-11-23 23:34:30,418] Starting every day program... +13756 [2020-11-23 23:34:30,425] Updating database statistics... +13756 [2020-11-23 23:34:30,429] Formatting leaderboard... +13756 [2020-11-23 23:34:30,676] Updating sidebar... +13756 [2020-11-23 23:34:32,525] Updated in new reddit... +13756 [2020-11-23 23:34:32,532] Called OAD prog @ Nov 23 2020 23:34:32 diff --git a/database.py b/database.py index 6eaddbb..a5c9682 100755 --- a/database.py +++ b/database.py @@ -1,5 +1,4 @@ import pymysql -import sqlite3 import subprocess import subreddit import time @@ -19,68 +18,6 @@ class Database: def __exit__(self, type, value, traceback): self.__connection.close() - def migrate(self, sqlitefile): - """Function for converting data from an SQLite3 database to - MySQL. Will only be called once ever probably. First the data is - converted using migrate() global function. - - Args: - sqlitefile (str): Path to the SQLite3 file - """ - conn = sqlite3.connect(sqlitefile) - cur = conn.cursor() - cur.execute("SELECT * FROM blacklist;") - blacklist = [i[1] for i in cur.fetchall()] - cur.close() - conn.close() - print("Got blacklist ids...") - - with self.__connection.cursor() as cursor: - cursor.execute("DELETE FROM blacklist;") - cursor.execute(""" - ALTER TABLE blacklist CHANGE blacklistID blacklistID int(11) AUTO_INCREMENT; - """) - cursor.execute(""" - ALTER TABLE lambdas CHANGE lambdaID lambdaID int(11) AUTO_INCREMENT; - """) - cursor.execute(""" - ALTER TABLE lambdas DROP FOREIGN KEY lambdas_FK_0_0; - """) - cursor.execute(""" - ALTER TABLE users CHANGE userID userID int(11) AUTO_INCREMENT; - """) - cursor.execute(""" - ALTER TABLE lambdas ADD FOREIGN KEY (userID) REFERENCES users(userID); - """) - cursor.execute(""" - ALTER TABLE stats CHANGE statID statID int(11) AUTO_INCREMENT; - """) - print("Finished altering tables...") - - #still cant get executemany to work :/ - # cursor.executemany("INSERT INTO blacklist (prawID) VALUES (%s);", (blacklist, )) - for prawID in blacklist: - cursor.execute("INSERT INTO blacklist (prawID) VALUES (%s);", (prawID, )) - print("Finised adding blacklist ids...") - - cursor.execute(""" - CREATE TABLE IF NOT EXISTS log ( - log_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, - pid INT UNSIGNED NULL, - datetime_ DATETIME NOT NULL, - category VARCHAR(10) NOT NULL DEFAULT 'INFO', - data_ VARCHAR(500) NOT NULL, - reddit_id VARCHAR(120) NULL - );""") - print("Added logging table...") - - with open("actions.log", "r") as f: - for line in f: - self.append_log(line, commit = False) - print("Done.") - - self.__connection.commit() - def append_log(self, line, permalink = None, commit = True): """Function for adding a log file line to the database. Switched to use the database for logging at the same time as switched to MySQL. @@ -265,25 +202,7 @@ class Database: """) return cursor.fetchall() -def migrate(sqlitefile): - subprocess.run([ - "sqlite3mysql", - "-f", sqlitefile, - "-h", subreddit.CONFIG["mysql"]["host"], - "-d", subreddit.CONFIG["mysql"]["database"], - "-u", subreddit.CONFIG["mysql"]["user"], - "-p", subreddit.CONFIG["mysql"]["passwd"] - ]) - print("Converted table...") - - with Database() as db: - db.migrate(sqlitefile) - if __name__ == "__main__": - #migrate("SmallYTChannelDatabase.db") - # with Database() as db: - # #db.give_lambda("floofleberries", "https://www.reddit.com/r/SmallYTChannel/comments/ho5b5p/new_video_advice_would_help_but_even_just_a_watch/") - # print(db.id_in_blacklist("hyy6v0")) print(subreddit.format_monthly_leaderboard()) diff --git a/onceaday.py b/onceaday.py index d2f750a..ea54552 100755 --- a/onceaday.py +++ b/onceaday.py @@ -1,7 +1,100 @@ import os +from operator import itemgetter os.chdir("/root/SmallYTChannelBotSubmissions") import subreddit +import database +import datetime +import graph -subreddit.every_day() -subreddit.logging.info("Called OAD prog @ %s" % subreddit.get_time()) +def main(): + subreddit.display("Starting every day program...") + subreddit.display("Updating database statistics...") + with database.Database() as db: + db.update_stats() + subreddit.display("Posting and updating wiki...") + update_tables(db.get_scores(), db.get_stats()) + + subreddit.display("Formatting leaderboard...") + leaderboard = format_monthly_leaderboard() + subreddit.display("Made the following leaderboard:\n======================\n%s\n======================\n" % leaderboard) + subreddit.display("Updating sidebar...") + #it'd be cool to find a way to access this directly without iteration + for widget in subreddit.SUBREDDIT.widgets.sidebar: + if widget.shortName == "Monthly Lambda Leaderboard": + widget.mod.update(text = leaderboard) + subreddit.display("Updated in new reddit...") + + sidebar = subreddit.SUBREDDIT.mod.settings()["description"] + oldtable = sidebar.split("------")[-1] + subreddit.SUBREDDIT.wiki['config/sidebar'].edit(sidebar.replace(oldtable, "\n\n## Monthly Lambda Leaderboard\n\n" + leaderboard)) + subreddit.display("Updated in old reddit...") + subreddit.display("Completed.") + + subreddit.logging.info("Called OAD prog @ %s" % subreddit.get_time()) + +def update_tables(scores, data): + content = "" + date = str(datetime.date.today()) + mods = get_mods() + imagepath = graph.make_graph(data) + imageurl = upload_image(imagepath, date) + bylambda = [i for i in sorted(scores, key = itemgetter(1), reverse = True) if i[0] not in mods][:10] + byhelps = sorted(scores, key = itemgetter(2), reverse = True)[:10] + + subreddit.SUBREDDIT.stylesheet.upload("wikigraph", imagepath) + + content += "\n\n##/r/SmallYTChannel lambda tables: %s" % date + + content += "\n\n###By lambda:" + content += "\n\nUsername|Lambda|Help given\n:--|:--|:--" + for line in bylambda: + content += "\n/u/%s|%i|%i" % (line[0], line[1], line[2]) + + content += "\n\n###By Help given:" + content += "\n\nUsername|Lambda|Help given\n:--|:--|:--" + for line in byhelps: + λ = str(line[1]) + if line[0] in mods: + λ = "∞" + content += "\n/u/%s|%s|%i" % (line[0], λ, line[2]) + + content += "\n\n##Statistics from %s:\n\nIf you're looking at this through the wiki, not through the bot's profile, then" % (date) + content += "the most up-to-date graph will be shown below. To see the graph at this date, follow [this link.](%s)" % (imageurl) + content += "\n\n\n\nTotal λ in circulation|Useful advice given|Unique users\n:--|:--|:--\n%i|%i|%i" % (data[-1][1], data[-1][2], data[-1][3]) + + subreddit.REDDIT.subreddit("u_SmallYTChannelBot").submit("/r/SmallYTChannel Statistics: %s" % date, url = imageurl).reply(content).mod.distinguish(sticky = True) + + subreddit.SUBREDDIT.wiki["lambdatables"].edit(content, reason = "Update: %s" % date) + subreddit.SUBREDDIT.wiki[date].edit(content, reason = "Update: %s" % date) + + currentdata = subreddit.SUBREDDIT.wiki["index"].content_md + currentdata += "\n\n* [%s](/r/SmallYTChannel/wiki/%s)" % (date, date) + + subreddit.SUBREDDIT.wiki["index"].edit(currentdata, reason = "Update: %s" % date) + +def get_mods(): + return [str(i) for i in subreddit.SUBREDDIT.moderator()] + ["AutoModerator"] + +def format_monthly_leaderboard(): + with database.Database() as db: + leaderboard = db.get_lambda_leaderboard() + out = "**Username**|**Medal**|**Times Helped**|**Lambda**\n:-|:-|:-|:-\n" + for username, times_helped, λ in leaderboard: + out += "/u/%s|%1s|%s|%sλ\n" % (username, subreddit.get_medal(λ)[:-1], times_helped, λ) + return out + "\nLast updated: %s" % subreddit.get_time() + +def upload_image(path, date): + config = { + 'album': None, + 'name': 'SmallYTChannelBot Statistics graph: %s' % date, + 'title': 'SmallYTChannelBot Statistics graph: %s' % date, + 'description': 'SmallYTChannelBot Statistics graph: %s' % date + } + + image = subreddit.IMGUR.upload_from_path(path, config = config) + + return "https://i.imgur.com/%s.png" % image["id"] + +if __name__ == "__main__": + main() @@ -1,7 +1,6 @@ # /u/SmallYTChannelBot Source Code -The source code for /u/SmallYTChannelBot. This is a WIP branch that uses MySQL -instead of SQLite3 and is designed to work in a docker container. +The source code for /u/SmallYTChannelBot. # Docker @@ -9,8 +8,6 @@ instead of SQLite3 and is designed to work in a docker container. - Edit the configuration file and rename -- If applicable, download the newest SQLite3 database and run the migration script - - Build the image: `sudo docker build -t smallytchannelbot:latest .` diff --git a/subreddit.py b/subreddit.py index 5f6c906..4be5c20 100755 --- a/subreddit.py +++ b/subreddit.py @@ -15,6 +15,7 @@ with open("config.json", "r") as f: CONFIG = json.load(f) REDDIT = praw.Reddit(**CONFIG["redditapi"]) +REDDIT.validate_on_submit = True SUBREDDIT = REDDIT.subreddit(CONFIG["subreddit"]) COMMENT_TAIL = CONFIG["comment_tail"] FREE_FLAIRS = CONFIG["free_flairs"] @@ -63,14 +64,14 @@ def get_medal(actualscore): else: return "" -def update_users_flair(username): - flairtext = next(SUBREDDIT.flair(redditor=username))["flair_text"] +def update_users_flair(username, reddit): + flairtext = next(reddit.flair(redditor=username))["flair_text"] if flairtext is None: flairtext = "" else: flairscore = get_lambda_from_flair(flairtext) flairtext = str(flairtext.replace("[%s] " % flairscore, "")) - if username in get_mods(): + if username in get_mods(reddit): newflair = "[🏆 ∞λ] %s" % (flairtext) else: with database.Database() as db: @@ -78,89 +79,16 @@ def update_users_flair(username): newflair = "[%s%iλ] %s" % (get_medal(actualscore), actualscore, flairtext) logging.info("/u/%s had their flair updated" % username) - SUBREDDIT.flair.set(redditor = username, text = newflair) - -def get_mods(): - return [str(i) for i in SUBREDDIT.moderator()] + ["AutoModerator"] - -def update_tables(scores, data): - content = "" - date = str(datetime.date.today()) - mods = get_mods() - imagepath = graph.make_graph(data) - imageurl = upload_image(imagepath, date) - bylambda = [i for i in sorted(scores, key = itemgetter(1), reverse = True) if i[0] not in mods][:10] - byhelps = sorted(scores, key = itemgetter(2), reverse = True)[:10] - - SUBREDDIT.stylesheet.upload("wikigraph", imagepath) - - content += "\n\n##/r/SmallYTChannel lambda tables: %s" % date - - content += "\n\n###By lambda:" - content += "\n\nUsername|Lambda|Help given\n:--|:--|:--" - for line in bylambda: - content += "\n/u/%s|%i|%i" % (line[0], line[1], line[2]) - - content += "\n\n###By Help given:" - content += "\n\nUsername|Lambda|Help given\n:--|:--|:--" - for line in byhelps: - λ = str(line[1]) - if line[0] in mods: - λ = "∞" - content += "\n/u/%s|%s|%i" % (line[0], λ, line[2]) - - content += "\n\n##Statistics from %s:\n\nIf you're looking at this through the wiki, not through the bot's profile, then" % (date) - content += "the most up-to-date graph will be shown below. To see the graph at this date, follow [this link.](%s)" % (imageurl) - content += "\n\n\n\nTotal λ in circulation|Useful advice given|Unique users\n:--|:--|:--\n%i|%i|%i" % (data[-1][1], data[-1][2], data[-1][3]) - - REDDIT.subreddit("u_SmallYTChannelBot").submit("/r/SmallYTChannel Statistics: %s" % date, url = imageurl).reply(content).mod.distinguish(sticky = True) - - #SUBREDDIT.wiki["lambdatables"].edit(content, reason = "Update: %s" % date) - #SUBREDDIT.wiki[date].edit(content, reason = "Update: %s" % date) - - #currentdata = SUBREDDIT.wiki["index"].content_md - #currentdata += "\n\n* [%s](/r/SmallYTChannel/wiki/%s)" % (date, date) - - #SUBREDDIT.wiki["index"].edit(currentdata, reason = "Update: %s" % date) - -def upload_image(path, date): - config = { - 'album': None, - 'name': 'SmallYTChannelBot Statistics graph: %s' % date, - 'title': 'SmallYTChannelBot Statistics graph: %s' % date, - 'description': 'SmallYTChannelBot Statistics graph: %s' % date - } - - image = IMGUR.upload_from_path(path, config = config) + reddit.flair.set(redditor = username, text = newflair) - return "https://i.imgur.com/%s.png" % image["id"] +def get_mods(reddit): + return [str(i) for i in reddit.subreddit(CONFIG["subreddit"]).moderator()] + ["AutoModerator"] -def every_day(): - display("Starting every day program...") - display("Updating database statistics...") - with database.Database() as db: - db.update_stats() - display("Posting and updating wiki...") - update_tables(db.get_scores(), db.get_stats()) - display("Formatting leaderboard...") - leaderboard = format_monthly_leaderboard() - display("Updating sidebar...") - #it'd be cool to find a way to access this directly without iteration - for widget in SUBREDDIT.widgets.sidebar: - if widget.shortName == "Monthly Lambda Leaderboard": - widget.mod.update(text = leaderboard) - display("Updated in new reddit...") - sidebar = SUBREDDIT.mod.settings()["description"] - oldtable = sidebar.split("------")[-1] - SUBREDDIT.mod.update(description = sidebar.replace(oldtable, "\n\n## Monthly Lambda Leaderboard\n\n" + leaderboard)) - display("Updated in old reddit...") - display("Completed.") - -def handle_mylambda(comment): +def handle_mylambda(comment, reddit): author = str(comment.author) with database.Database() as db: λ, links = db.get_lambda(author) - if author in get_mods(): + if author in get_mods(reddit): text = "/u/%s is a moderator, and therefore has ∞λ." % author else: text = "/u/%s currently has %iλ, and has helped helping the following posts:" % (author, λ) @@ -180,7 +108,7 @@ def handle_mylambda(comment): update_users_flair_from_comment(comment) return text -def handle_givelambda(comment): +def handle_givelambda(comment, reddit): submission = comment.submission parentauthour = str(comment.parent().author) op = str(comment.author) @@ -189,7 +117,7 @@ def handle_givelambda(comment): text = "You cannot give yourself λ." elif parentauthour == "SmallYTChannelBot": text = "Please only give lambda to humans." - elif str(comment.author) in get_mods(): + elif str(comment.author) in get_mods(reddit): text = "The moderator /u/%s has given /u/%s 1λ. /u/%s now has %iλ." % (str(comment.author), parentauthour, parentauthour, db.get_lambda(parentauthour)[0] + 1) db.give_lambda(parentauthour, submission.permalink, timestamp = int(submission.created_utc)) display(text, concerning=comment.permalink) @@ -332,88 +260,56 @@ Views|%s update_users_flair(str(submission.author)) return text -def main(): - comment_stream = SUBREDDIT.stream.comments(pause_after=-1) - submission_stream = SUBREDDIT.stream.submissions(pause_after=-1) - - while True: - try: - for comment in comment_stream: - if comment is None: - break - - with database.Database() as db: - if not db.id_in_blacklist(comment.id): - db.add_to_blacklist(comment.id) - - response = None - if "!mylambda" in comment.body.lower() and str(comment.author) != "SmallYTChannelBot": - response = handle_mylambda(comment) - - if "!givelambda" in comment.body.lower() and str(comment.author) != "SmallYTChannelBot": - response = handle_givelambda(comment) +def handle_comment(comment, reddit): + response = None + if "!mylambda" in comment.body.lower() and str(comment.author) != "SmallYTChannelBot": + response = handle_mylambda(comment, reddit) - if comment.body.startswith("!takelambda") and str(comment.author) in get_mods(): - response = handle_takelambda(comment) + if "!givelambda" in comment.body.lower() and str(comment.author) != "SmallYTChannelBot": + response = handle_givelambda(comment, reddit) - if comment.body.startswith("!refundlambda") and str(comment.author) in get_mods(): - response = handle_refundlambda(comment) + if comment.body.startswith("!takelambda") and str(comment.author) in get_mods(): + response = handle_takelambda(comment) - if response is not None: - reply = comment.reply(response + COMMENT_TAIL) - reply.mod.distinguish(sticky = False) - - for submission in submission_stream: - if submission is None: - break - - with database.Database() as db: - if not db.id_in_blacklist(submission.id): - db.add_to_blacklist(submission.id) - display("There has been a new submission: '%s', with flair '%s'" % (submission.title, submission.link_flair_text), concerning=submission.permalink) - - response = None - if str(submission.author) not in get_mods(): - response = handle_submission(submission) - reply = submission.reply(response + COMMENT_TAIL) - reply.mod.distinguish(sticky = True) - reply.mod.approve() + if comment.body.startswith("!refundlambda") and str(comment.author) in get_mods(): + response = handle_refundlambda(comment) - except KeyboardInterrupt as e: - display("{ERROR} %s" % e) - continue + if response is not None: + reply = comment.reply(response + COMMENT_TAIL) + reply.mod.distinguish(sticky = False) -def get_submission_times(permalink): - if not permalink.startswith("https://www.reddit.com"): - permalink = "https://www.reddit.com" + permalink +def stream(reddit): + subreddit = reddit.subreddit(CONFIG["subreddit"]) + streams = [subreddit.stream.comments(pause_after=-1), subreddit.stream.submissions(pause_after=-1)] + with database.Database() as db: + while True: + for stream in streams: + for item in stream: + if item is None: + break - submission = REDDIT.submission(url = permalink) - return submission.created_utc + if db.id_in_blacklist(item.id): + continue -def add_times_to_lambdas(): - updated_permalinks = [] - with database.Database() as db: - for id_, permalink, user, created in db.get_all_lambdas(): - if created is None and permalink not in updated_permalinks: - db.add_date_to_permalink(permalink, get_submission_times(permalink)) - updated_permalinks.append(permalink) - logging.info("Added date for permalink %s" % permalink) + db.add_to_blacklist(item.id) + if type(item) is praw.models.reddit.comment.Comment: + handle_comment(item, reddit) + elif type(item) is praw.models.reddit.submission.Submission: + display("There has been a new submission: '%s', with flair '%s'" % (item.title, item.link_flair_text), concerning=item.permalink) -def format_monthly_leaderboard(): - with database.Database() as db: - leaderboard = db.get_lambda_leaderboard() - out = "**Username**|**Medal**|**Times Helped**|**Lambda**\n:-|:-|:-|:-\n" - for username, times_helped, λ in leaderboard: - out += "/u/%s|%1s|%s|%sλ\n" % (username, get_medal(λ)[:-1], times_helped, λ) - return out + "\nLast updated: %s" % get_time() + if str(item.author) not in get_mods(reddit): + reply = item.reply(handle_submission(item) + COMMENT_TAIL) + reply.mod.distinguish(sticky = True) + reply.mod.approve() - +def main(): + reddit = praw.Reddit(**CONFIG["redditapi"]) + reddit.validate_on_submit = True + stream(reddit) -if __name__ == "__main__": - with open("pid.txt", "w") as f: - f.write(str(os.getpid())) - display("####################[%s] RESTARTED####################" % get_time()) + +if __name__ == "__main__": main() |