Files
.gitignore
bot.py
config.json
README.md
requirements.txt
Code
5 318
bot.py
from __future__ import annotations
import asyncio
import json
import logging
import os
from dataclasses import dataclass
from typing import Any
import aiohttp
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("fivem-bot")
def load_config() -> dict[str, Any]:
try:
with open("config.json", "r", encoding="utf-8") as config_file:
return json.load(config_file)
except FileNotFoundError:
logger.warning("config.json was not found; using defaults")
return {}
except json.JSONDecodeError as error:
raise RuntimeError("config.json contains invalid JSON") from error
CONFIG = load_config()
class FiveMUnavailableError(Exception):
pass
@dataclass(slots=True)
class FiveMStatus:
hostname: str
players: list[dict[str, Any]]
max_players: int
endpoints: list[str]
@property
def player_count(self) -> int:
return len(self.players)
class FiveMClient:
def __init__(self) -> None:
self.session: aiohttp.ClientSession | None = None
def configure(self, session: aiohttp.ClientSession) -> None:
self.session = session
def endpoint(self) -> str | None:
configured_endpoint = os.getenv("FIVEM_SERVER_ENDPOINT", "").strip()
if configured_endpoint:
return configured_endpoint
server_id = os.getenv("FIVEM_SERVER_ID", "").strip()
if server_id:
return f"https://servers-frontend.fivem.net/api/servers/single/{server_id}"
return None
async def fetch_status(self) -> FiveMStatus:
if self.session is None:
raise FiveMUnavailableError("FiveM client is not initialized")
endpoint = self.endpoint()
if endpoint is None:
raise FiveMUnavailableError(
"Configure FIVEM_SERVER_ID or FIVEM_SERVER_ENDPOINT in .env"
)
try:
timeout = aiohttp.ClientTimeout(total=10)
async with self.session.get(
endpoint,
timeout=timeout,
headers={"User-Agent": "FiveM Discord Bot/1.0"},
) as response:
if response.status != 200:
raise FiveMUnavailableError(
f"FiveM API returned HTTP {response.status}"
)
payload = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as error:
raise FiveMUnavailableError("FiveM server could not be reached") from error
data = payload.get("Data", payload)
players = data.get("players", [])
if not isinstance(players, list):
players = []
variables = data.get("vars", {})
max_players_value = data.get("clients") or variables.get("sv_maxClients")
try:
max_players = int(max_players_value or CONFIG.get("max_players_fallback", 0))
except (TypeError, ValueError):
max_players = 0
endpoints = data.get("connectEndPoints", [])
if not isinstance(endpoints, list):
endpoints = []
return FiveMStatus(
hostname=str(data.get("hostname") or CONFIG.get("server_name", "FiveM Server")),
players=players,
max_players=max_players,
endpoints=[str(endpoint) for endpoint in endpoints],
)
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
fivem = FiveMClient()
server_group = app_commands.Group(name="server", description="FiveM server commands")
def embed_color() -> discord.Colour:
return discord.Colour(int(CONFIG.get("embed_color", 0x5865F2)))
@server_group.command(name="status", description="Show the FiveM server status")
async def server_status(interaction: discord.Interaction) -> None:
await interaction.response.defer()
try:
status = await fivem.fetch_status()
except FiveMUnavailableError as error:
await interaction.followup.send(f"Unable to read the FiveM server: {error}")
return
max_players = str(status.max_players) if status.max_players else "unknown"
embed = discord.Embed(title=status.hostname, colour=embed_color())
embed.add_field(
name="Players",
value=f"{status.player_count}/{max_players}",
inline=True,
)
embed.add_field(name="Status", value="Online", inline=True)
if status.endpoints:
embed.add_field(name="Connect", value=f"`connect {status.endpoints[0]}`", inline=False)
await interaction.followup.send(embed=embed)
@server_group.command(name="players", description="List players currently on the FiveM server")
async def server_players(interaction: discord.Interaction) -> None:
await interaction.response.defer()
try:
status = await fivem.fetch_status()
except FiveMUnavailableError as error:
await interaction.followup.send(f"Unable to read the FiveM server: {error}")
return
if not status.players:
await interaction.followup.send("The FiveM server is online, but nobody is connected.")
return
player_lines = []
for player in status.players[:50]:
name = str(player.get("name", "Unknown player")).replace("@", "@\u200b")
player_lines.append(f"`{player.get('id', '?')}` {name}")
remaining = len(status.players) - len(player_lines)
description = "\n".join(player_lines)
if remaining > 0:
description += f"\n…and {remaining} more."
embed = discord.Embed(
title=f"Players online ({status.player_count})",
description=description,
colour=embed_color(),
)
await interaction.followup.send(embed=embed)
@bot.tree.command(name="announce", description="Send an announcement to this channel")
@app_commands.checks.has_permissions(manage_guild=True)
@app_commands.describe(message="The announcement to send")
async def announce(interaction: discord.Interaction, message: str) -> None:
embed = discord.Embed(
title=CONFIG.get("server_name", "FiveM Server") + " Announcement",
description=message,
colour=embed_color(),
)
embed.set_footer(text=f"Posted by {interaction.user.display_name}")
await interaction.response.send_message(embed=embed)