fbiguy_666

create a discord dex bot called "mets dex"

Kodari AI
KodariSep 26 at 6:54 pm 1
MetsDexBot
A Discord bot that serves as a Pokédex companion, allowing users to search for Pokémon information, view stats, types, abilities, and evolution chains directly in Discord. Features include slash commands for quick lookups, embed responses with sprite images, type effectiveness charts, and a catch/collection system where users can track their caught Pokémon. The bot integrates with PokeAPI for accurate data, supports fuzzy name matching, and includes pagination for multi-result searches. Built with discord.py and aiohttp, it maintains user collections in a SQLite database and provides leaderboard functionality for collection completion.
  1. Build Mets roster/profile lookups against MLB’s public Stats API.

  2. Add Discord slash-command setup, environment-based token loading, error handling, and run instructions.

Created Mets Dex, a Discord bot with /mets roster and /mets player slash commands, backed by the MLB Stats API. Added setup instructions, dependency list, and a .env.example for the bot token.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 235
bot.py
import logging
import os

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


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("mets_dex")

MLB_API_URL = "https://statsapi.mlb.com/api/v1"
METS_TEAM_ID = 121
METS_BLUE = discord.Colour(0x002D72)


class MLBApiError(Exception):
    """Raised when the MLB Stats API cannot provide usable data."""


class MLBStatsClient:
    def __init__(self, session: aiohttp.ClientSession):
        self.session = session

    async def _get(self, path: str) -> dict:
        try:
            async with self.session.get(f"{MLB_API_URL}{path}") as response:
                response.raise_for_status()
                return await response.json()
        except (aiohttp.ClientError, TimeoutError, ValueError) as exc:
            raise MLBApiError("The MLB Stats API request failed.") from exc

    async def get_mets_roster(self) -> list[dict]:
        data = await self._get(f"/teams/{METS_TEAM_ID}/roster/40")
        return data.get("roster", [])

    async def get_player(self, player_id: int) -> dict:
        data = await self._get(f"/people/{player_id}")
        people = data.get("people", [])
        if not people:
            raise MLBApiError("The MLB Stats API returned no player profile.")
        return people[0]


class MetsDexBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="!", intents=discord.Intents.default())
        self.session: aiohttp.ClientSession | None = None
        self.mlb: MLBStatsClient | None = None

    async def setup_hook(self) -> None:
        timeout = aiohttp.ClientTimeout(total=15)
        self.session = aiohttp.ClientSession(timeout=timeout)
        self.mlb = MLBStatsClient(self.session)
        await self.tree.sync()
        logger.info("Slash commands synced.")

    async def on_ready(self) -> None:
        logger.info("Mets Dex is online as %s", self.user)

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

    async def on_app_command_error(
        self, interaction: discord.Interaction, error: app_commands.AppCommandError
    ) -> None:
        if isinstance(error, app_commands.CommandOnCooldown):
            message = f"Please wait {error.retry_after:.1f} seconds before trying again."
        else:
            logger.error(
                "Slash command failed: %s",
                error,
                exc_info=(type(error), error, error.__traceback__),
            )
            message = "Mets Dex couldn't complete that request. Please try again shortly."

        if interaction.response.is_done():
            await interaction.followup.send(message, ephemeral=True)
        else:
            await interaction.response.send_message(message, ephemeral=True)


bot = MetsDexBot()
mets = app_commands.Group(
    name="mets", description="Look up the New York Mets roster and players."
)


@mets.command(name="roster", description="Show the current Mets 40-man roster.")
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def roster(interaction: discord.Interaction) -> None:
    await interaction.response.defer(thinking=True)
    entries = await bot.mlb.get_mets_roster()
    if not entries:
        await interaction.followup.send("The Mets roster is currently unavailable.")
        return

    positions: dict[str, list[str]] = {}
    for entry in entries:
        player = entry.get("person", {})
        position = entry.get("position", {}).get("abbreviation", "Other")
        if player.get("fullName"):
            positions.setdefault(position, []).append(player["fullName"])

    embed = discord.Embed(
        title="New York Mets — 40-Man Roster",
        description=f"{len(entries)} players",
        colour=METS_BLUE,
    )
    for position in sorted(positions):
        embed.add_field(
            name=position,
            value="\n".join(f"• {name}" for name in sorted(positions[position]))[:1024],
            inline=True,
        )
    embed.set_footer(text="Player data provided by MLB Stats API")
    await interaction.followup.send(embed=embed)


@mets.command(name="player", description="Look up a player on the current Mets 40-man roster.")
@app_commands.describe(name="The player's name")
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def player(interaction: discord.Interaction, name: str) -> None:
    await interaction.response.defer(thinking=True, ephemeral=True)
    entries = await bot.mlb.get_mets_roster()
    query = " ".join(name.casefold().split())
    match = next(
        (
            entry
            for entry in entries
            if " ".join(entry.get("person", {}).get("fullName", "").casefold().split())
            == query
        ),
        None,
    )
    if match is None:
        await interaction.followup.send(
            f"I couldn't find **{discord.utils.escape_markdown(name)}** on the current Mets 40-man roster."
        )
        return

    profile = await bot.mlb.get_player(match["person"]["id"])
    position = profile.get("primaryPosition", {}).get("name", "Unknown")
    embed = discord.Embed(
        title=profile.get("fullName", name),
        description=position,
        colour=METS_BLUE,
        url=f"https://www.mlb.com/player/{profile['id']}",
    )

    age = profile.get("currentAge")
    if age:
        embed.add_field(name="Age", value=str(age), inline=True)
    bats = profile.get("batSide", {}).get("description")
    throws = profile.get("pitchHand", {}).get("description")
    if bats or throws:
        embed.add_field(
            name="Bats / Throws",
            value=f"{bats or '—'} / {throws or '—'}",
            inline=True,
        )
    height = profile.get("height")
    weight = profile.get("weight")
    if height or weight:
        embed.add_field(
            name="Height / Weight",
            value=f"{height or '—'} / {f'{weight} lb' if weight else '—'}",
            inline=True,
        )

    birthplace = ", ".join(
        part
        for part in (
            profile.get("birthCity"),
            profile.get("birthStateProvince"),
            profile.get("birthCountry"),
        )
        if part
    )
    if birthplace:
        embed.add_field(name="Born", value=birthplace, inline=False)
    embed.set_thumbnail(
        url=f"https://img.mlbstatic.com/mlb-photos/image/upload/w_200,q_auto:good/v1/people/{profile['id']}/headshot/67/current"
    )
    embed.set_footer(text="Player data provided by MLB Stats API")
    await interaction.followup.send(embed=embed)


bot.tree.add_command(mets)


def main() -> None:
    load_dotenv()