Files
TestPostsBot/config.py
T

82 lines
2.7 KiB
Python
Raw Normal View History

2026-03-04 23:01:36 +00:00
# config.py
# Fetches config from subreddit wiki page in YAML format
import yaml
2026-03-04 23:01:36 +00:00
def fetch_config_from_wiki(reddit, subreddit_name, wiki_page):
"""
Fetches config from the wiki page as YAML.
Returns the parsed config dict, or empty dict if error.
"""
2026-03-04 23:01:36 +00:00
subreddit = reddit.subreddit(subreddit_name)
try:
wiki = subreddit.wiki[wiki_page]
config_text = wiki.content_md
config = yaml.safe_load(config_text)
# If config is None or empty, return empty dict
if not config:
config = {'posts': []}
2026-03-04 23:01:36 +00:00
return config
except yaml.YAMLError as e:
print(f"Error parsing YAML config from wiki: {e}")
return {'posts': []}
2026-03-04 23:01:36 +00:00
except Exception as e:
print(f"Error fetching config from wiki: {e}")
return {'posts': []}
def validate_config_from_wiki(reddit, subreddit_name, wiki_page):
"""
Validates the config from the wiki page.
Returns True if the config is valid YAML with 'posts' key, False otherwise.
"""
subreddit = reddit.subreddit(subreddit_name)
try:
wiki = subreddit.wiki[wiki_page]
config_text = wiki.content_md
config = yaml.safe_load(config_text)
# Validate required structure
if not isinstance(config, dict) or 'posts' not in config:
print("Wiki config missing required 'posts' key or is not a dict.")
return False
return True
except yaml.YAMLError as e:
print(f"Error parsing YAML config from wiki: {e}")
return False
except Exception as e:
print(f"Error fetching config from wiki: {e}")
return False
def get_trigger_posts(reddit, subreddit_name, wiki_page, trigger_name):
"""
Gets the posts associated with a specific trigger.
Returns a list of post dicts, or empty list if trigger not found.
"""
config = fetch_config_from_wiki(reddit, subreddit_name, wiki_page)
posts_config = config.get('posts', [])
if not isinstance(posts_config, list):
print("Config 'posts' is not a list.")
return []
for post_config in posts_config:
if not isinstance(post_config, dict):
continue
if post_config.get('trigger', '').lower() == trigger_name.lower():
# Get the posts for this trigger
trigger_posts = post_config.get('posts', [])
if not isinstance(trigger_posts, list):
print(f"Trigger '{trigger_name}' posts is not a list.")
return []
return trigger_posts
# Trigger not found
print(f"Trigger '{trigger_name}' not found in config.")
return []