initial
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
Minecraft Update Bot - Detects new Minecraft releases and posts to Reddit
|
||||
"""
|
||||
|
||||
import praw
|
||||
import json
|
||||
import time
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime
|
||||
import config
|
||||
from minecraft_checker import get_latest_releases, parse_release_date
|
||||
from wiki_config import WikiConfig
|
||||
from update_checker import start_update_checker
|
||||
|
||||
|
||||
# Bot version (increment when making changes)
|
||||
BOT_VERSION = "1.0"
|
||||
|
||||
# Database file to track posted versions
|
||||
DB_DIR = os.path.join(os.path.dirname(__file__), 'DB')
|
||||
POSTED_VERSIONS_FILE = os.path.join(DB_DIR, 'posted_versions.json')
|
||||
|
||||
# Wiki configuration manager (initialized on startup)
|
||||
wiki_config = WikiConfig()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialize the database directory and posted versions file."""
|
||||
os.makedirs(DB_DIR, exist_ok=True)
|
||||
|
||||
if not os.path.exists(POSTED_VERSIONS_FILE):
|
||||
with open(POSTED_VERSIONS_FILE, 'w') as f:
|
||||
json.dump({"posted": []}, f, indent=2)
|
||||
|
||||
|
||||
def load_posted_versions():
|
||||
"""Load the list of already-posted version IDs."""
|
||||
try:
|
||||
with open(POSTED_VERSIONS_FILE, 'r') as f:
|
||||
data = json.load(f)
|
||||
return set(data.get("posted", []))
|
||||
except:
|
||||
return set()
|
||||
|
||||
|
||||
def save_posted_version(version_id):
|
||||
"""Save a version ID as posted."""
|
||||
try:
|
||||
with open(POSTED_VERSIONS_FILE, 'r') as f:
|
||||
data = json.load(f)
|
||||
except:
|
||||
data = {"posted": []}
|
||||
|
||||
if version_id not in data.get("posted", []):
|
||||
data.setdefault("posted", []).append(version_id)
|
||||
|
||||
with open(POSTED_VERSIONS_FILE, 'w') as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
|
||||
def make_reddit_connection():
|
||||
"""Create a Reddit API connection using PRAW."""
|
||||
try:
|
||||
reddit = praw.Reddit(
|
||||
client_id=config.REDDIT_CLIENT_ID,
|
||||
client_secret=config.REDDIT_CLIENT_SECRET,
|
||||
user_agent=config.REDDIT_USER_AGENT,
|
||||
username=config.REDDIT_USERNAME,
|
||||
password=config.REDDIT_PASSWORD
|
||||
)
|
||||
|
||||
# Test the connection
|
||||
reddit.user.me()
|
||||
print("[BOT] ✓ Successfully connected to Reddit")
|
||||
return reddit
|
||||
except Exception as e:
|
||||
print(f"[BOT] ✗ Failed to connect to Reddit: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def post_to_subreddit(reddit, version_info):
|
||||
"""
|
||||
Post a message about a new Minecraft release to the subreddit.
|
||||
|
||||
Args:
|
||||
reddit: PRAW Reddit instance
|
||||
version_info: Dict with keys: id, type, releaseTime
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
try:
|
||||
version_id = version_info["id"]
|
||||
release_type = version_info["type"]
|
||||
release_date = parse_release_date(version_info["releaseTime"])
|
||||
|
||||
# Get title and body from wiki config
|
||||
title, body = wiki_config.format_post(release_type, version_id, release_date)
|
||||
|
||||
subreddit = reddit.subreddit(config.SUBREDDIT)
|
||||
submission = subreddit.submit(title, selftext=body)
|
||||
|
||||
print(f"[BOT] ✓ Posted Minecraft {version_id} ({release_type})")
|
||||
print(f" URL: {submission.url}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"[BOT] ✗ Failed to post: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_for_updates(reddit):
|
||||
"""
|
||||
Check for new Minecraft releases and post if any are new.
|
||||
|
||||
Args:
|
||||
reddit: PRAW Reddit instance
|
||||
"""
|
||||
try:
|
||||
posted_versions = load_posted_versions()
|
||||
latest_releases = get_latest_releases(config.RELEASE_TYPES)
|
||||
|
||||
for version_info in latest_releases:
|
||||
version_id = version_info["id"]
|
||||
|
||||
if version_id not in posted_versions:
|
||||
print(f"[BOT] New release found: {version_id}")
|
||||
if post_to_subreddit(reddit, version_info):
|
||||
save_posted_version(version_id)
|
||||
else:
|
||||
print(f"[BOT] Version {version_id} already posted, skipping")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[BOT] ✗ Error checking for updates: {e}")
|
||||
|
||||
|
||||
def bot_thread(reddit):
|
||||
"""
|
||||
Background thread that periodically checks for Minecraft updates.
|
||||
|
||||
Args:
|
||||
reddit: PRAW Reddit instance
|
||||
"""
|
||||
print(f"[BOT] Started update checker (checking every {config.CHECK_INTERVAL} seconds)")
|
||||
|
||||
while True:
|
||||
try:
|
||||
check_for_updates(reddit)
|
||||
except Exception as e:
|
||||
print(f"[BOT] ✗ Error in bot thread: {e}")
|
||||
|
||||
time.sleep(config.CHECK_INTERVAL)
|
||||
|
||||
|
||||
def start_bot():
|
||||
"""Start the Minecraft Update Bot."""
|
||||
print("[BOT] Starting Minecraft Update Bot...")
|
||||
|
||||
# Initialize database
|
||||
init_db()
|
||||
|
||||
# Connect to Reddit
|
||||
reddit = make_reddit_connection()
|
||||
if not reddit:
|
||||
print("[BOT] ✗ Cannot start bot without Reddit connection")
|
||||
return
|
||||
|
||||
# Initialize wiki configuration
|
||||
wiki_config.init(reddit, config.SUBREDDIT)
|
||||
wiki_config.fetch_from_wiki()
|
||||
|
||||
# Start update checker
|
||||
start_update_checker(reddit, config.SUBREDDIT, "MinecraftUpdateBot", BOT_VERSION)
|
||||
|
||||
# Do an initial check
|
||||
check_for_updates(reddit)
|
||||
|
||||
# Start background thread
|
||||
thread = threading.Thread(target=bot_thread, args=(reddit,), daemon=True)
|
||||
thread.start()
|
||||
|
||||
print("[BOT] ✓ Bot is running")
|
||||
|
||||
# Keep main thread alive
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
print("\n[BOT] Shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_bot()
|
||||
Reference in New Issue
Block a user