Format all code.
This commit is contained in:
@@ -11,28 +11,32 @@ from pathlib import Path
|
||||
# --- CONFIGURATION ---
|
||||
IMAGE_DIR = "images"
|
||||
|
||||
|
||||
def get_reddit_instance():
|
||||
"""Initializes and returns a PRAW Reddit instance using OAuth2 refresh token."""
|
||||
|
||||
env_path = Path(__file__).parent / '.env'
|
||||
env_path = Path(__file__).parent / ".env"
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
|
||||
client_id = os.getenv("REDDIT_CLIENT_ID")
|
||||
client_secret = os.getenv("REDDIT_CLIENT_SECRET")
|
||||
user_agent = os.getenv("REDDIT_USER_AGENT")
|
||||
refresh_token = os.getenv("REDDIT_REFRESH_TOKEN")
|
||||
|
||||
if not all([client_id, client_secret, user_agent, refresh_token]):
|
||||
print("Error: Reddit API credentials (including REDDIT_REFRESH_TOKEN) must be set in .env file.")
|
||||
print(
|
||||
"Error: Reddit API credentials (including REDDIT_REFRESH_TOKEN) must be set in .env file."
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
return praw.Reddit(
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
user_agent=user_agent,
|
||||
refresh_token=refresh_token
|
||||
refresh_token=refresh_token,
|
||||
)
|
||||
|
||||
|
||||
def find_latest_image(pattern):
|
||||
"""Finds the most recent file in the IMAGE_DIR that matches a given pattern."""
|
||||
try:
|
||||
@@ -47,17 +51,34 @@ def find_latest_image(pattern):
|
||||
print(f"Error finding image file: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to find an image and post it to Reddit."""
|
||||
parser = argparse.ArgumentParser(description="Find the latest sentiment image and post it to a subreddit.")
|
||||
parser.add_argument("-s", "--subreddit", help="The source subreddit of the image to post. (Defaults to overall summary)")
|
||||
parser.add_argument("-w", "--weekly", action="store_true", help="Post the weekly summary instead of the daily one.")
|
||||
parser.add_argument("-t", "--target-subreddit", default="rstat", help="The subreddit to post the image to. (Default: rstat)")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Find the latest sentiment image and post it to a subreddit."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--subreddit",
|
||||
help="The source subreddit of the image to post. (Defaults to overall summary)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w",
|
||||
"--weekly",
|
||||
action="store_true",
|
||||
help="Post the weekly summary instead of the daily one.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--target-subreddit",
|
||||
default="rstat",
|
||||
help="The subreddit to post the image to. (Default: rstat)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
# --- 1. Determine filename pattern and post title ---
|
||||
current_date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
if args.subreddit:
|
||||
view_type = "weekly" if args.weekly else "daily"
|
||||
filename_pattern = f"{args.subreddit.lower()}_{view_type}_*.png"
|
||||
@@ -65,36 +86,42 @@ def main():
|
||||
else:
|
||||
# Default to the overall summary
|
||||
if args.weekly:
|
||||
print("Warning: --weekly flag has no effect for overall summary. Posting overall daily image.")
|
||||
print(
|
||||
"Warning: --weekly flag has no effect for overall summary. Posting overall daily image."
|
||||
)
|
||||
filename_pattern = "overall_summary_*.png"
|
||||
post_title = f"Overall Top 10 Ticker Mentions Across Reddit ({current_date_str})"
|
||||
|
||||
post_title = (
|
||||
f"Overall Top 10 Ticker Mentions Across Reddit ({current_date_str})"
|
||||
)
|
||||
|
||||
print(f"Searching for image pattern: {filename_pattern}")
|
||||
|
||||
|
||||
# --- 2. Find the latest image file ---
|
||||
image_to_post = find_latest_image(filename_pattern)
|
||||
|
||||
|
||||
if not image_to_post:
|
||||
print(f"Error: No image found matching the pattern '{filename_pattern}'. Please run the scraper and exporter first.")
|
||||
print(
|
||||
f"Error: No image found matching the pattern '{filename_pattern}'. Please run the scraper and exporter first."
|
||||
)
|
||||
return
|
||||
|
||||
print(f"Found image: {image_to_post}")
|
||||
|
||||
|
||||
# --- 3. Connect to Reddit and submit ---
|
||||
reddit = get_reddit_instance()
|
||||
if not reddit:
|
||||
return
|
||||
|
||||
|
||||
try:
|
||||
target_sub = reddit.subreddit(args.target_subreddit)
|
||||
print(f"Submitting '{post_title}' to r/{target_sub.display_name}...")
|
||||
|
||||
|
||||
submission = target_sub.submit_image(
|
||||
title=post_title,
|
||||
image_path=image_to_post,
|
||||
flair_id=None # Optional: You can add a flair ID here if you want
|
||||
flair_id=None, # Optional: You can add a flair ID here if you want
|
||||
)
|
||||
|
||||
|
||||
print("\n--- Post Successful! ---")
|
||||
print(f"Post URL: {submission.shortlink}")
|
||||
|
||||
@@ -103,4 +130,4 @@ def main():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
|
Reference in New Issue
Block a user