prime12341234888181-eng

Discord bot that tracks all players in game and checks if the sever iss up or down

Kodari AI
KodariAug 23 at 2:34 pm 1
ServerStatusBot
A Discord bot that monitors game server status and tracks player presence. It periodically pings the server to check if it's online or offline, and maintains a real-time list of connected players. The bot posts status updates to a designated Discord channel, including server up/down notifications and player join/leave events. It uses Discord's presence and message APIs to provide live server health information and player activity tracking, with configurable check intervals and alert settings.

Created a Discord Minecraft server monitor bot with:

  • Java server availability polling via mcstatus

  • /server command for online/offline status

  • /players command for current players

  • Automatic player join/leave logging

  • Discord presence showing current player count

  • Optional live status embed in a configured channel

  • .env configuration support

  • Error handling and logging

  • Setup documentation and dependency files

Run it with:

Shell
cp .env.example .env
pip install -r requirements.txt
python bot.py
Kodari can make mistakes. Review important code before using.
Files
Discord bot
.gitignore
bot.py
README.md
requirements.txt
Code
5 413
bot.py
import asyncio
import logging
import os
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional

import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
from mcstatus import JavaServer


load_dotenv()

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


def optional_int(name: str) -> Optional[int]:
    value = os.getenv(name, "").strip()
    if not value:
        return None
    try:
        return int(value)
    except ValueError as exc:
        raise ValueError(f"{name} must be an integer") from exc


@dataclass(frozen=True)
class Config:
    token: str
    minecraft_host: str
    minecraft_port: int
    poll_interval: int
    status_channel_id: Optional[int]
    status_message_id: Optional[int]
    command_guild_id: Optional[int]

    @classmethod
    def from_environment(cls) -> "Config":
        token = os.getenv("DISCORD_TOKEN", "").strip()
        host = os.getenv("MINECRAFT_HOST", "").strip()
        if not token:
            raise ValueError("DISCORD_TOKEN is required")
        if not host:
            raise ValueError("MINECRAFT_HOST is required")

        try:
            port = int(os.getenv("MINECRAFT_PORT", "25565"))
            interval = int(os.getenv("POLL_INTERVAL", "60"))
        except ValueError as exc:
            raise ValueError("MINECRAFT_PORT and POLL_INTERVAL must be integers") from exc

        if not 1 <= port <= 65535:
            raise ValueError("MINECRAFT_PORT must be between 1 and 65535")
        if interval < 15:
            raise ValueError("POLL_INTERVAL must be at least 15 seconds")

        return cls(
            token=token,
            minecraft_host=host,
            minecraft_port=port,
            poll_interval=interval,
            status_channel_id=optional_int("STATUS_CHANNEL_ID"),
            status_message_id=optional_int("STATUS_MESSAGE_ID"),
            command_guild_id=optional_int("COMMAND_GUILD_ID"),
        )


@dataclass(frozen=True)
class ServerSnapshot:
    online: bool
    players: tuple[str, ...]
    player_count: int
    max_players: int
    version: str
    error: Optional[str]
    players_known: bool
    checked_at: datetime


class MinecraftMonitor:
    def __init__(self, bot: commands.Bot, config: Config) -> None:
        self.bot = bot
        self.config = config
        self.snapshot = ServerSnapshot(
            online=False,
            players=(),
            player_count=0,
            max_players=0,
            version="Unknown",
            error="Not checked yet",
            players_known=False,
            checked_at=datetime.now(timezone.utc),
        )
        self._refresh_lock = asyncio.Lock()
        self._status_message: Optional[discord.Message] = None

        self.poll_loop.change_interval(seconds=config.poll_interval)

    @staticmethod
    def _query_server(host: str, port: int) -> ServerSnapshot:
        checked_at = datetime.now(timezone.utc)
        try:
            server = JavaServer.lookup(f"{host}:{port}")
            status = server.status(timeout=5)
            sample = status.players.sample or []
            players = tuple(
                sorted(
                    {
                        player.name
                        for player in sample
                        if getattr(player, "name", None)
                    },
                    key=str.casefold,
                )
            )
            return ServerSnapshot(
                online=True,
                players=players,
                player_count=status.players.online,
                max_players=status.players.max,
                version=getattr(status.version, "name", "Unknown") or "Unknown",
                error=None,
                players_known=bool(sample),
                checked_at=checked_at,
            )
        except Exception as exc:
            logger.warning("Minecraft server check failed: %s", exc)
            return ServerSnapshot(
                online=False,
                players=(),
                player_count=0,
                max_players=0,
                version="Unknown",
                error=str(exc) or exc.__class__.__name__,
                players_known=False,
                checked_at=checked_at,
            )

    async def refresh(self) -> ServerSnapshot:
        async with self._refresh_lock:
            previous = self.snapshot
            current = await asyncio.to_thread(
                self._query_server,
                self.config.minecraft_host,
                self.config.minecraft_port,
            )
            self.snapshot = current
            self._log_player_changes(previous, current)
            await self._publish(current)
            return current

    def _log_player_changes(
        self, previous: ServerSnapshot, current: ServerSnapshot
    ) -> None:
        if not current.online or not current.players_known:
            return
        if previous.online and previous.players_known:
            joined = sorted(set(current.players) - set(previous.players), key=str.casefold)
            left = sorted(set(previous.players) - set(current.players), key=str.casefold)
            if joined:
                logger.info("Players joined: %s", ", ".join(joined))
            if left:
                logger.info("Players left: %s", ", ".join(left))

    async def _publish(self, snapshot: ServerSnapshot) -> None:
        if not self.bot.is_ready():
            return

        if snapshot.online:
            activity = discord.Game(
                name=f"{snapshot.player_count}/{snapshot.max_players} players"
            )
            await self.bot.change_presence(status=discord.Status.online, activity=activity)
        else:
            await self.bot.change_presence(
                status=discord.Status.idle,
                activity=discord.Game(name="Minecraft server offline"),
            )

        if self.config.status_channel_id is None:
            return

        channel = self.bot.get_channel(self.config.status_channel_id)
        if channel is None:
            try:
                channel = await self.bot.fetch_channel(self.config.status_channel_id)
            except discord.HTTPException:
                logger.exception("Could not fetch the configured status channel")
                return

        if not isinstance(channel, (discord.TextChannel, discord.Thread)):
            logger.error("STATUS_CHANNEL_ID is not a text channel or thread")
            return