Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 278
bot.py
from __future__ import annotations
import asyncio
import logging
import os
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("roblox-authorized-exporter")
def required_int(name: str) -> int:
value = os.getenv(name, "").strip()
try:
parsed = int(value)
except ValueError as exc:
raise RuntimeError(f"{name} must be a Discord snowflake integer") from exc
if parsed <= 0:
raise RuntimeError(f"{name} must be greater than zero")
return parsed
def configured_place_ids() -> frozenset[int]:
raw_ids = os.getenv("AUTHORIZED_PLACE_IDS", "")
place_ids: set[int] = set()
for raw_id in raw_ids.split(","):
raw_id = raw_id.strip()
if not raw_id:
continue
try:
place_id = int(raw_id)
except ValueError as exc:
raise RuntimeError("AUTHORIZED_PLACE_IDS must contain only integers") from exc
if place_id > 0:
place_ids.add(place_id)
if not place_ids:
raise RuntimeError("AUTHORIZED_PLACE_IDS must contain at least one place ID")
return frozenset(place_ids)
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN", "").strip()
AUTHORIZED_ROLE_ID = required_int("AUTHORIZED_ROLE_ID")
AUTHORIZED_PLACE_IDS = configured_place_ids()
AUTHORIZED_EXPORTER = Path(os.getenv("AUTHORIZED_EXPORTER", "").strip()).expanduser()
EXPORT_TIMEOUT_SECONDS = int(os.getenv("EXPORT_TIMEOUT_SECONDS", "300"))
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", str(24 * 1024 * 1024)))
if not DISCORD_TOKEN:
raise RuntimeError("DISCORD_TOKEN is required")
if not AUTHORIZED_EXPORTER:
raise RuntimeError("AUTHORIZED_EXPORTER is required")
if EXPORT_TIMEOUT_SECONDS <= 0:
raise RuntimeError("EXPORT_TIMEOUT_SECONDS must be greater than zero")
if MAX_UPLOAD_BYTES <= 0:
raise RuntimeError("MAX_UPLOAD_BYTES must be greater than zero")
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
def has_export_permission(interaction: discord.Interaction) -> bool:
if not isinstance(interaction.user, discord.Member):
return False
return any(role.id == AUTHORIZED_ROLE_ID for role in interaction.user.roles)
def exporter_command(place_id: int, output_directory: Path) -> list[str]:
if AUTHORIZED_EXPORTER.suffix.lower() == ".py":
return [sys.executable, str(AUTHORIZED_EXPORTER), str(place_id), str(output_directory)]
return [str(AUTHORIZED_EXPORTER), str(place_id), str(output_directory)]
async def run_authorized_exporter(place_id: int, output_directory: Path) -> tuple[int, str, str]:
process = await asyncio.create_subprocess_exec(
*exporter_command(place_id, output_directory),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
shell=False,
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(), timeout=EXPORT_TIMEOUT_SECONDS
)
except asyncio.TimeoutError:
process.kill()
await process.communicate()
raise
return process.returncode, stdout.decode(errors="replace"), stderr.decode(errors="replace")
def create_archive(source_directory: Path, archive_path: Path) -> int:
files = [path for path in source_directory.rglob("*") if path.is_file() and not path.is_symlink()]
if not files:
raise RuntimeError("The authorized exporter did not produce any files")
with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for file_path in files:
relative_path = file_path.relative_to(source_directory)
archive.write(file_path, relative_path.as_posix())
archive_size = archive_path.stat().st_size
if archive_size > MAX_UPLOAD_BYTES:
archive_path.unlink(missing_ok=True)
raise RuntimeError(
f"The export is too large for Discord ({archive_size:,} bytes; "
f"limit is {MAX_UPLOAD_BYTES:,} bytes)"
)
return archive_size
@bot.event
async def on_ready() -> None:
if bot.user is None:
return
logger.info("Logged in as %s (%s)", bot.user, bot.user.id)
try:
synced = await bot.tree.sync()
logger.info("Synced %d application commands", len(synced))
except discord.HTTPException:
logger.exception("Could not sync application commands")
@bot.tree.command(name="decompile", description="Export an authorized Roblox place")
@app_commands.describe(place_id="The allowlisted Roblox place ID")
async def decompile(interaction: discord.Interaction, place_id: int) -> None:
if interaction.guild is None:
await interaction.response.send_message(
"This command can only be used inside an authorized server.", ephemeral=True
)
return
if not has_export_permission(interaction):
await interaction.response.send_message(
"You do not have the required export role.", ephemeral=True
)
return
if place_id not in AUTHORIZED_PLACE_IDS:
await interaction.response.send_message(
"That place ID is not allowlisted for this bot.", ephemeral=True
)
return
if not AUTHORIZED_EXPORTER.exists() or not AUTHORIZED_EXPORTER.is_file():
await interaction.response.send_message(
"The authorized exporter is not configured correctly.", ephemeral=True
)
return
await interaction.response.defer(ephemeral=True, thinking=True)
try:
with tempfile.TemporaryDirectory(prefix=f"roblox-export-{place_id}-") as temporary_directory:
output_directory = Path(temporary_directory) / "output"
output_directory.mkdir()
archive_path = Path(temporary_directory) / f"place-{place_id}.zip"
return_code, stdout, stderr = await run_authorized_exporter(
place_id, output_directory
)
if return_code != 0:
logger.error(
"Exporter failed for place %s with code %s\nstdout:\n%s\nstderr:\n%s",
place_id,
return_code,
stdout[-4000:],
stderr[-4000:],
)
await interaction.followup.send(
"The authorized exporter failed. Check the bot logs for details.",
ephemeral=True,
)
return
archive_size = create_archive(output_directory, archive_path)
await interaction.followup.send(
content=f"Authorized export completed ({archive_size:,} bytes).",
file=discord.File(archive_path, filename=f"place-{place_id}.zip"),
ephemeral=True,
)
except asyncio.TimeoutError:
await interaction.followup.send(
"The authorized exporter timed out.", ephemeral=True
)
except (OSError, RuntimeError, zipfile.BadZipFile) as exc:
logger.exception("Export failed for place %s", place_id)
await interaction.followup.send(
f"The export could not be completed: {exc}", ephemeral=True