Added better flair tools.
This commit is contained in:
@@ -8,7 +8,6 @@ import praw
|
|||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# --- CONFIGURATION ---
|
|
||||||
IMAGE_DIR = "images"
|
IMAGE_DIR = "images"
|
||||||
|
|
||||||
|
|
||||||
@@ -51,39 +50,33 @@ def find_latest_image(pattern):
|
|||||||
print(f"Error finding image file: {e}")
|
print(f"Error finding image file: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def get_flair_id(subreddit, flair_text):
|
|
||||||
"""
|
|
||||||
Attempts to find the ID of a flair by its text.
|
|
||||||
Returns the ID string or None if not found or an error occurs.
|
|
||||||
"""
|
|
||||||
if not flair_text:
|
|
||||||
return None
|
|
||||||
|
|
||||||
print(f"Attempting to find Flair ID for text: '{flair_text}'...")
|
|
||||||
try:
|
|
||||||
flairs = subreddit.flair.link_templates
|
|
||||||
for flair in flairs:
|
|
||||||
if flair['text'].lower() == flair_text.lower():
|
|
||||||
print(f" -> Found Flair ID: {flair['id']}")
|
|
||||||
return flair['id']
|
|
||||||
print(" -> Warning: No matching flair text found.")
|
|
||||||
return None
|
|
||||||
except Exception as e:
|
|
||||||
print(f" -> Warning: Could not fetch flairs for this subreddit (Error: {e}). Proceeding without flair.")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Main function to find an image and post it to Reddit."""
|
"""Main function to find an image and post it to Reddit."""
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description="Find the latest sentiment image and post it to a subreddit."
|
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(
|
||||||
parser.add_argument("-w", "--weekly", action="store_true", help="Post the weekly summary instead of the daily one.")
|
"-s",
|
||||||
parser.add_argument("-t", "--target-subreddit", default="rstat", help="The subreddit to post the image to. (Default: rstat)")
|
"--subreddit",
|
||||||
parser.add_argument("--flair-text", help="The text of the flair to search for (e.g., 'Daily Summary').")
|
help="The source subreddit of the image to post. (Defaults to overall summary)",
|
||||||
parser.add_argument("--flair-id", help="Manually provide a specific Flair ID (overrides --flair-text).")
|
)
|
||||||
|
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.add_argument(
|
||||||
|
"--flair-id",
|
||||||
|
help="The specific Flair ID to use for the post (required for some subreddits).",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@@ -125,23 +118,13 @@ def main():
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
target_sub = reddit.subreddit(args.target_subreddit)
|
target_sub = reddit.subreddit(args.target_subreddit)
|
||||||
|
|
||||||
# --- NEW SMART FLAIR LOGIC ---
|
|
||||||
final_flair_id = None
|
|
||||||
if args.flair_id:
|
|
||||||
# If the user provides a specific ID, use it directly.
|
|
||||||
print(f"Using provided Flair ID: {args.flair_id}")
|
|
||||||
final_flair_id = args.flair_id
|
|
||||||
elif args.flair_text:
|
|
||||||
# If they provide text, try to find the ID automatically.
|
|
||||||
final_flair_id = get_flair_id(target_sub, args.flair_text)
|
|
||||||
|
|
||||||
print(f"Submitting '{post_title}' to r/{target_sub.display_name}...")
|
print(f"Submitting '{post_title}' to r/{target_sub.display_name}...")
|
||||||
|
|
||||||
|
# --- Simplified submission logic ---
|
||||||
submission = target_sub.submit_image(
|
submission = target_sub.submit_image(
|
||||||
title=post_title,
|
title=post_title,
|
||||||
image_path=image_to_post,
|
image_path=image_to_post,
|
||||||
flair_id=final_flair_id # This will be the found ID or None
|
flair_id=args.flair_id, # Directly use the provided ID. This will be None if not provided.
|
||||||
)
|
)
|
||||||
|
|
||||||
print("\n--- Post Successful! ---")
|
print("\n--- Post Successful! ---")
|
||||||
@@ -149,8 +132,14 @@ def main():
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"\nAn error occurred while posting to Reddit: {e}")
|
print(f"\nAn error occurred while posting to Reddit: {e}")
|
||||||
if 'FLAIR_REQUIRED' in str(e):
|
if "FLAIR_REQUIRED" in str(e).upper():
|
||||||
print("\nHint: This subreddit requires a flair. Try finding the flair text or ID and use the --flair-text or --flair-id argument.")
|
print(
|
||||||
|
"\nHINT: This subreddit requires a flair. You MUST provide a valid Flair ID using the --flair-id argument."
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"Please follow the manual steps to find the Flair ID using your browser's developer tools."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
76
rstat_tool/flair_finder.py
Normal file
76
rstat_tool/flair_finder.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
# rstat_tool/flair_finder.py
|
||||||
|
# A dedicated tool to find available link flairs for a subreddit.
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import praw
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
def get_reddit_instance_for_flairs():
|
||||||
|
"""
|
||||||
|
Initializes and returns an authenticated PRAW instance using the refresh token.
|
||||||
|
This is a copy of the robust authentication from the posting script.
|
||||||
|
"""
|
||||||
|
# Find the .env file relative to the project root
|
||||||
|
env_path = Path(__file__).parent.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.", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
return praw.Reddit(
|
||||||
|
client_id=client_id,
|
||||||
|
client_secret=client_secret,
|
||||||
|
user_agent=user_agent,
|
||||||
|
refresh_token=refresh_token
|
||||||
|
)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Main function to fetch and display flairs."""
|
||||||
|
parser = argparse.ArgumentParser(description="Fetch and display available post flairs for a subreddit.")
|
||||||
|
parser.add_argument("subreddit", help="The name of the subreddit to check.")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
reddit = get_reddit_instance_for_flairs()
|
||||||
|
if not reddit:
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"\n--- Attempting to Fetch Post Flairs for r/{args.subreddit} ---")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# This uses PRAW's generic GET request method to hit the specific API endpoint.
|
||||||
|
api_path = f"/r/{args.subreddit}/api/link_flair_v2.json"
|
||||||
|
flairs = reddit.get(api_path, params={"raw_json": 1})
|
||||||
|
|
||||||
|
if not flairs:
|
||||||
|
print("No flairs found or flair list is empty for this subreddit.")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("\n--- Available Post Flairs ---")
|
||||||
|
found_count = 0
|
||||||
|
for flair in flairs:
|
||||||
|
flair_text = flair.get('text')
|
||||||
|
flair_id = flair.get('id')
|
||||||
|
if flair_text and flair_id:
|
||||||
|
print(f" Flair Text: '{flair_text}'")
|
||||||
|
print(f" Flair ID: {flair_id}\n")
|
||||||
|
found_count += 1
|
||||||
|
|
||||||
|
if found_count == 0:
|
||||||
|
print("No flairs with both text and ID were found.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\nAn error occurred: {e}", file=sys.stderr)
|
||||||
|
print("Hint: Please ensure the subreddit exists and that your authenticated user has permission to view it.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
1
setup.py
1
setup.py
@@ -20,6 +20,7 @@ setup(
|
|||||||
"rstat=rstat_tool.main:main",
|
"rstat=rstat_tool.main:main",
|
||||||
"rstat-dashboard=rstat_tool.dashboard:start_dashboard",
|
"rstat-dashboard=rstat_tool.dashboard:start_dashboard",
|
||||||
"rstat-cleanup=rstat_tool.cleanup:run_cleanup",
|
"rstat-cleanup=rstat_tool.cleanup:run_cleanup",
|
||||||
|
"rstat-flairs=rstat_tool.flair_finder:main",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
Reference in New Issue
Block a user