From e00b09c5d86810cf9365232e8a2afb52f237d7fe Mon Sep 17 00:00:00 2001 From: "Casper V. Kristensen" Date: Sat, 21 May 2022 20:39:12 +0200 Subject: [PATCH] Add midnight mode --- dailyreleases/config.ini.default | 5 +++-- dailyreleases/main.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/dailyreleases/config.ini.default b/dailyreleases/config.ini.default index 63b813f..53260b4 100644 --- a/dailyreleases/config.ini.default +++ b/dailyreleases/config.ini.default @@ -3,6 +3,7 @@ # immediately : Immediately generate and submit post to own subreddit. PM reddit notify_users with link to post. This # mode is useful for cron jobs, e.g. generating at midnight: '0 0 * * * /usr/local/bin/python3.7 -m dailyreleases'. # reply : Listen for reddit PMs; on receipt, generate and submit post to own subreddit. Reply with link to post. +# midnight : Like 'immediately', but run continuously, generating and submitting post at midnight every day. # test : Generate and print to log and console. Nothing is posted to reddit. mode = test @@ -24,8 +25,8 @@ password = xxxxxxx # List of users who are authorized to start the generation by PM'ing the bot. Only applies to 'reply' mode. authorized_users = spez,Deimorz,kn0thing -# List of users who should receive a PM on generation. Only applies to 'immediately' mode, since the sender will receive -# the PM in 'reply' mode. +# List of users who should receive a PM on generation. Only applies to 'immediately' and 'midnight' mode, since the +# sender will receive the PM in 'reply' mode. notify_users = chooter,alienth # Reddit perceives PMs with many links as spam, so the bot posts the code for the generated post in its own subreddit diff --git a/dailyreleases/main.py b/dailyreleases/main.py index 97f0a46..c083f7c 100644 --- a/dailyreleases/main.py +++ b/dailyreleases/main.py @@ -1,4 +1,6 @@ import logging +from datetime import time, datetime, timedelta +from time import sleep import prawcore @@ -28,6 +30,21 @@ def listen_inbox() -> None: print("Exiting (KeyboardInterrupt)") break +def at_midnight() -> None: + while True: + try: + now = datetime.now() + midnight = datetime.combine(now + timedelta(days=1), time.min) + until_midnight = midnight - now + logger.info(f"Waiting {until_midnight} until midnight..") + sleep(until_midnight.total_seconds()) + generate(post=True, pm_recipients=CONFIG["reddit"]["notify_users"].split(",")) + except Exception as e: + logger.exception(e) + except KeyboardInterrupt: + print("Exiting (KeyboardInterrupt)") + break + def main() -> None: try: @@ -39,6 +56,8 @@ def main() -> None: generate(post=False) if mode == "immediately": generate(post=True, pm_recipients=CONFIG["reddit"]["notify_users"].split(",")) + if mode == "midnight": + at_midnight() if mode == "reply": listen_inbox() except Exception as e: