Files
Modreplybot/modreplybot.py
T
2026-03-08 21:32:51 +00:00

95 lines
3.5 KiB
Python

import praw
from config import get_reddit, Config
import time
class ModBot:
def __init__(self):
import os
self.reddit = get_reddit()
self.subreddit = self.reddit.subreddit(Config.SUBREDDIT)
self.config_path = os.path.join(os.path.dirname(__file__), 'config', 'config.yaml')
self.triggers = []
self.comments = []
self.ensure_config_file()
def ensure_config_file(self):
import os
if not os.path.exists(self.config_path):
default_yaml = (
'triggers:\n'
' - trigger: help\n'
' comment: |\n'
' Thank you for your report!\n'
' This post is now approved.\n'
' - trigger: question\n'
' comment: |\n'
' This post has been approved.\n'
' Your question will be answered soon.\n'
)
os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
with open(self.config_path, 'w', encoding='utf-8') as f:
f.write(default_yaml)
def fetch_yaml_config(self):
import yaml
try:
with open(self.config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
self.triggers = []
self.comments = []
for entry in config.get('triggers', []):
self.triggers.append(entry.get('trigger', '').strip())
self.comments.append(entry.get('comment', '').strip())
except Exception as e:
print(f"Error fetching YAML config: {e}")
def run(self):
print("ModReplyBot started. Watching for comments...")
try:
self.fetch_yaml_config()
print(f"Triggers loaded: {self.triggers}")
print(f"Reddit user: {self.reddit.user.me()}")
print(f"Subreddit: {self.subreddit.display_name}")
except Exception as e:
print(f"Startup error: {e}")
return
while True:
try:
self.fetch_yaml_config()
for comment in self.subreddit.stream.comments(skip_existing=True):
self.handle_comment(comment)
except Exception as e:
print(f"Main loop error: {e}")
time.sleep(5) # Poll every 5 seconds
def handle_comment(self, comment):
comment_body = comment.body.lower()
for idx, trigger in enumerate(self.triggers):
expected = f"!{trigger.lower()}"
if expected in comment_body:
# Remove the triggering comment
try:
comment.mod.remove()
print(f"Removed triggering comment: {comment.id}")
except Exception as e:
print(f"Error removing comment: {e}")
# Approve the submission and post bot's comment
submission = comment.submission
self.fetch_yaml_config()
self.approve_and_comment(submission, self.comments[idx])
break
def approve_and_comment(self, submission, comment_text):
try:
submission.mod.approve()
comment = submission.reply(comment_text)
comment.mod.distinguish(sticky=True)
print(f"Approved and commented on: {submission.id}")
except Exception as e:
print(f"Error approving/commenting: {e}")
if __name__ == "__main__":
bot = ModBot()
bot.run()