Files
.gitignore
bot.py
requirements.txt
Code
3 710
bot.py
import asyncio
import base64
import html
import io
import logging
import os
import re
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
from urllib.parse import quote
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv(Path(__file__).resolve().with_name(".env"))
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("status.net")
TOKEN = os.getenv("DISCORD_TOKEN")
EA_STATUS_URL = os.getenv(
"EA_STATUS_URL",
"https://help.ea.com/en/server-status/",
)
PVZGW2_REPORTS_URL = os.getenv(
"PVZGW2_REPORTS_URL",
"https://downdetector.com/status/plants-vs-zombies/",
)
APEX_REPORTS_URL = os.getenv(
"APEX_REPORTS_URL",
"https://downdetector.com/status/apex-legends/",
)
MINECRAFT_STATUS_URL = "https://api.mcsrvstat.us/3/"
EPIC_STATUS_URL = "https://status.epicgames.com/api/v2/summary.json"
RIOT_STATUS_URL = "https://status.riotgames.com/"
http_session: Optional[aiohttp.ClientSession] = None
def shorten(value: Any, limit: int = 1024) -> str:
text = str(value or "").strip()
if not text:
return "Unavailable"
if len(text) <= limit:
return text
return f"{text[:limit - 3]}..."
def normalize_game(game: str) -> str:
return re.sub(r"[^a-z0-9]", "", game.lower())
def status_color(status: str) -> discord.Color:
normalized = status.lower()
if any(word in normalized for word in ("online", "operational", "available")):
return discord.Color.green()
if any(word in normalized for word in ("offline", "outage", "down", "error")):
return discord.Color.red()
if any(word in normalized for word in ("maintenance", "degraded", "unknown")):
return discord.Color.gold()
return discord.Color.blurple()
async def fetch_json(url: str) -> Dict[str, Any]:
if http_session is None:
raise RuntimeError("HTTP session is not available.")
async with http_session.get(
url,
headers={"User-Agent": "Status.net Discord Bot"},
) as response:
response.raise_for_status()
return await response.json(content_type=None)
async def fetch_text(url: str) -> str:
if http_session is None:
raise RuntimeError("HTTP session is not available.")
async with http_session.get(
url,
headers={"User-Agent": "Status.net Discord Bot"},
) as response:
response.raise_for_status()
return await response.text()
def minecraft_icon(data: Dict[str, Any]) -> Tuple[Optional[discord.File], Optional[str]]:
icon = data.get("icon")
if not icon:
return None, None
if icon.startswith("data:image/") and "," in icon:
try:
encoded_icon = icon.split(",", 1)[1]
image_bytes = base64.b64decode(encoded_icon)
filename = "server-icon.png"
return discord.File(io.BytesIO(image_bytes), filename=filename), filename
except (ValueError, base64.binascii.Error):
return None, None
if icon.startswith(("http://", "https://")):
return None, icon
return None, None
def minecraft_embed(
address: str,
data: Dict[str, Any],
) -> Tuple[discord.Embed, Optional[discord.File]]:
if not data.get("online"):
embed = discord.Embed(
title="Minecraft server not found",
description="Server not found - possibly offline?",
color=discord.Color.red(),
)
embed.add_field(name="Address", value=shorten(address, 256))
return embed, None
motd_data = data.get("motd", {})
motd_lines = motd_data.get("clean", []) if isinstance(motd_data, dict) else []
motd = "\n".join(str(line) for line in motd_lines)
players = data.get("players", {})
online_players = players.get("online", 0)
max_players = players.get("max", 0)
debug_data = data.get("debug", {})
ping = debug_data.get("ping") if isinstance(debug_data, dict) else None
embed = discord.Embed(
title="Minecraft server online",
description=shorten(motd, 1024),
color=discord.Color.green(),
)
embed.add_field(name="Address", value=shorten(address, 256), inline=False)
embed.add_field(
name="Players",
value=f"{online_players}/{max_players}",
inline=True,
)
embed.add_field(
name="Ping",
value=f"{ping} ms" if ping is not None else "Unavailable",
inline=True,
)
embed.add_field(
name="Version",
value=shorten(data.get("version", "Unavailable"), 256),
inline=True,
)
icon_file, icon_url = minecraft_icon(data)
if icon_file is not None:
embed.set_thumbnail(url="attachment://server-icon.png")
embed.add_field(name="Banner/Icon", value="Available", inline=True)
elif icon_url is not None:
embed.set_thumbnail(url=icon_url)
embed.add_field(name="Banner/Icon", value="Available", inline=True)
else:
embed.add_field(name="Banner/Icon", value="Unavailable", inline=True)
embed.set_footer(text="Data provided by mcsrvstat.us")
return embed, icon_file
async def community_report_status_embed(
game: str,
source_url: str,
source_name: str,
game_terms: Tuple[str, ...],
) -> discord.Embed:
disclaimer = f"This data may not be accurate - grabbed from {source_name}"
try:
page = await fetch_text(source_url)
except (aiohttp.ClientError, asyncio.TimeoutError) as error:
logger.warning("Community report lookup failed for %s: %s", game, error)
return discord.Embed(
title=f"{game} report status unavailable",
description=f"{disclaimer}\n\nThe report site could not be reached right now.",
color=discord.Color.red(),
)
clean_page = html.unescape(re.sub(r"<[^>]+>", " ", page))
clean_page = re.sub(r"\s+", " ", clean_page).strip()
normalized_page = clean_page.lower()
game_found = any(term in normalized_page for term in game_terms)
if any(phrase in normalized_page for phrase in (
"possible problems",