No chat to show

This project's files are all here to explore.

Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 287
bot.py
import logging
import os
from datetime import datetime
from pathlib import Path

import aiohttp
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


PROJECT_DIR = Path(__file__).resolve().parent
load_dotenv(PROJECT_DIR / ".env")

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("roblox-game-bot")


class RobloxNotFound(Exception):
    """Raised when Roblox has no public game for the requested ID."""


class RobloxAPIError(Exception):
    """Raised when Roblox returns an unexpected API error."""


class RobloxAPI:
    BASE_HEADERS = {"User-Agent": "RobloxGameInfoBot/1.0"}

    def __init__(self) -> None:
        self.session: aiohttp.ClientSession | None = None

    async def start(self) -> None:
        self.session = aiohttp.ClientSession(
            headers=self.BASE_HEADERS,
            timeout=aiohttp.ClientTimeout(total=12),
        )

    async def close(self) -> None:
        if self.session is not None:
            await self.session.close()
            self.session = None

    async def _get_json(self, url: str, params: dict[str, str] | None = None) -> dict:
        if self.session is None:
            raise RobloxAPIError("The Roblox API client is not ready.")

        try:
            async with self.session.get(url, params=params) as response:
                if response.status == 404:
                    raise RobloxNotFound
                if response.status >= 400:
                    body = await response.text()
                    raise RobloxAPIError(
                        f"Roblox returned HTTP {response.status}: {body[:200]}"
                    )
                return await response.json(content_type=None)
        except aiohttp.ClientError as error:
            raise RobloxAPIError("Roblox could not be reached.") from error

    async def get_game(self, requested_id: int) -> tuple[dict, int]:
        universe_id = None

        try:
            mapping = await self._get_json(
                f"https://apis.roblox.com/universes/v1/places/{requested_id}/universe"
            )
            universe_id = int(mapping["universeId"])
        except (RobloxNotFound, KeyError, ValueError):
            universe_id = requested_id

        response = await self._get_json(
            "https://games.roblox.com/v1/games",
            {"universeIds": str(universe_id)},
        )
        games = response.get("data", [])
        if not games:
            raise RobloxNotFound

        game = games[0]
        thumbnails = await self._get_json(
            "https://thumbnails.roblox.com/v1/games/icons",
            {
                "universeIds": str(universe_id),
                "returnPolicy": "PlaceHolder",
                "size": "420x420",
                "format": "Png",
                "isCircular": "false",
            },
        )
        thumbnail_data = thumbnails.get("data", [])
        if thumbnail_data:
            game["thumbnailUrl"] = thumbnail_data[0].get("imageUrl")

        return game, universe_id


def shorten(value: str | None, limit: int) -> str:
    text = (value or "").strip()
    if len(text) <= limit:
        return text or "No description provided."
    return text[: limit - 1].rstrip() + "…"


def format_number(value: int | None) -> str:
    return f"{value:,}" if isinstance(value, int) else "Unknown"


def format_date(value: str | None) -> str:
    if not value:
        return "Unknown"
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
        return discord.utils.format_dt(parsed, style="D")
    except ValueError:
        return "Unknown"


class GameBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.none()
        super().__init__(
            command_prefix=commands.when_mentioned,
            intents=intents,
        )
        self.roblox = RobloxAPI()

    async def setup_hook(self) -> None:
        await self.roblox.start()

        guild_id = os.getenv("DISCORD_GUILD_ID")
        if guild_id:
            guild = discord.Object(id=int(guild_id))
            self.tree.copy_global_to(guild=guild)
            synced = await self.tree.sync(guild=guild)
            logger.info("Synced %d command(s) to guild %s", len(synced), guild_id)
        else:
            synced = await self.tree.sync()
            logger.info("Synced %d global command(s)", len(synced))

    async def close(self) -> None:
        await self.roblox.close()
        await super().close()


bot = GameBot()


@bot.event
async def on_ready() -> None:
    if bot.user is not None:
        logger.info("Logged in as %s (%s)", bot.user, bot.user.id)


@bot.tree.command(name="game", description="Show public information about a Roblox game")
@app_commands.describe(game_id="A Roblox place ID or universe ID")
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def game(interaction: discord.Interaction, game_id: str) -> None:
    game_id = game_id.strip()
    if not game_id.isdigit() or int(game_id) <= 0:
        await interaction.response.send_message(
            "Enter a positive Roblox place ID or universe ID.",
            ephemeral=True,
        )
        return

    await interaction.response.defer(thinking=True)

    try:
        game_data, universe_id = await bot.roblox.get_game(int(game_id))
    except RobloxNotFound:
        await interaction.followup.send(
            "I couldn't find a public Roblox game for that ID."
        )
        return
    except RobloxAPIError:
        logger.exception("Roblox API request failed for ID %s", game_id)
        await interaction.followup.send(
            "Roblox is unavailable right now. Please try again later."
        )
        return

    creator = game_data.get("creator") or {}
    creator_name = creator.get("name", "Unknown")
    creator_type = creator.get("type", "Creator")
    embed = discord.Embed(
        title=shorten(game_data.get("name"), 256),
        url=f"https://www.roblox.com/games/{game_id}",
        description=shorten(game_data.get("description"), 4096),
        color=discord.Color.blurple(),
    )
    embed.add_field(name="Creator", value=f"{creator_name} ({creator_type})", inline=True)
    embed.add_field(name="Playing", value=format_number(game_data.get("playing")), inline=True)
    embed.add_field(name="Visits", value=format_number(game_data.get("visits")), inline=True)
    embed.add_field(name="Max players", value=format_number(game_data.get("maxPlayers")), inline=True)
    embed.add_field(name="Created", value=format_date(game_data.get("created")), inline=True)