Implement /servers command

This commit is contained in:
Norbi Peti 2024-10-11 00:34:33 +02:00
parent 198f0b165e
commit 9c671f47c5
4 changed files with 47 additions and 25 deletions

View file

@ -1,8 +1,9 @@
from discord.ext import commands
from utils import handle_api_request
import logging import logging
from discord.ext import commands
from utils import about_me_embed from utils import about_me_embed
from utils import handle_api_request
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -24,15 +25,31 @@ class Info(commands.Cog):
async def info_bot(self, ctx): async def info_bot(self, ctx):
# see utils.py # see utils.py
embed = about_me_embed(self.bot) embed = about_me_embed(self.bot)
await ctx.send(embed=embed) await ctx.send(embed=embed, ephemeral=True)
@commands.hybrid_command( @commands.hybrid_command(
name="server_status", description="Fetches the game server status" name="servers", description="Fetches info about the game servers",
aliases=["server_list"]
) )
async def server_status(self, ctx): async def servers(self, ctx):
result, message = handle_api_request("server_status") result, message = handle_api_request("servers")
if result: if result:
status = result.get("status", "Unknown") response = "Servers:"
await ctx.send(f"Server status: {status}") for server in result:
name = server.get("name", "Unknown")
online_players = server.get("onlinePlayers", -1)
game_state = server.get("gameState", "Unknown")
map = server.get("mapAliasAndVersion", "Unknown")
game_settings = server.get("gameSettings", {})
max_players = game_settings.get("maxPlayers", -1)
response += f"\n* {name} - {game_state} - {map} - {online_players}/{max_players}"
await ctx.send(response, ephemeral=True)
else: else:
await ctx.send(f"Failed to retrieve server status: {message}") await ctx.send(f"Failed to retrieve server status: {message}", ephemeral=True)
@commands.command()
@commands.is_owner()
async def sync(self, ctx: commands.Context) -> None:
"""Sync commands"""
synced = await ctx.bot.tree.sync()
await ctx.send(f"Synced {len(synced)} commands for the server")

View file

@ -1,7 +1,9 @@
from discord.ext import commands
from utils import is_mod, handle_api_request
import logging import logging
from discord.ext import commands
from utils import is_mod, handle_api_request
# didn't use discord apparently so i didn't import it. # didn't use discord apparently so i didn't import it.
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View file

@ -1,7 +1,7 @@
# Bot configuration # Bot configuration
prefix: ""
token: "Your token here!" token: "Your token here!"
github_url: "" prefix: "!"
github_url: "https://git.norbipeti.eu/ExMods/RC2Bot"
# A list of cogs to load at startup # A list of cogs to load at startup
# These are found in /cogs/ # These are found in /cogs/
@ -10,13 +10,13 @@ cogs:
- info - info
# API configuration # API configuration
api_url: "https://api.whofuckingknows.com/" api_url: "https://norbipeti.eu/rc2matchmaking"
# Add routes here. # Add routes here.
routes: routes:
start_server: "/server/start" start_server: "/server/start"
stop_server: "/server/stop" stop_server: "/server/stop"
change_map: "/server/change_map" change_map: "/server/change_map"
server_status: "/server/status" servers: "/servers"
# Mod IDs (for permissions) # Mod IDs (for permissions)
# Replicate if you want admins, gamemasters, etc. # Replicate if you want admins, gamemasters, etc.
@ -24,5 +24,5 @@ routes:
mods: mods:
- "123456789012345678" - "123456789012345678"
- "987654321098765432" - "987654321098765432"
- "406922163271106584" # Test role
- "1250589730203107428" # Archive server sus role

View file

@ -1,10 +1,11 @@
import yaml
import logging import logging
import requests
import discord import discord
import datetime
import psutil
import humanfriendly import humanfriendly
import psutil
import requests
import yaml
from discord.utils import utcnow
# imagine a world where devs imported exactly what they needed # imagine a world where devs imported exactly what they needed
# but it's just not possible /s # but it's just not possible /s
@ -74,7 +75,7 @@ def mod_only():
# Gross function, but it works. # Gross function, but it works.
def handle_api_request(route_key, data=None): def handle_api_request(route_key, data=None) -> tuple[dict | list | None, str]:
# route_key is your YAML key # route_key is your YAML key
# Data defaults to None so we don't have to set it # Data defaults to None so we don't have to set it
@ -82,6 +83,7 @@ def handle_api_request(route_key, data=None):
# If you wanted to set up multiple API URLS, you could use them like routes (a list), or just copy how api_url is setup. # If you wanted to set up multiple API URLS, you could use them like routes (a list), or just copy how api_url is setup.
api_url = config.get("api_url") api_url = config.get("api_url")
api_token = config.get("api_token")
routes = config.get("routes", {}) routes = config.get("routes", {})
if not api_url: # you fucked up if not api_url: # you fucked up
@ -94,12 +96,13 @@ def handle_api_request(route_key, data=None):
route = routes[route_key] route = routes[route_key]
url = f"{api_url}{route}" url = f"{api_url}{route}"
headers = {"Authorization": api_token}
try: # Very prone to errors. Server shite. try: # Very prone to errors. Server shite.
if data: if data:
response = requests.post(url, json=data) response = requests.post(url, json=data, headers=headers)
else: else:
response = requests.post(url) response = requests.get(url, headers=headers)
if response.status_code == 200: if response.status_code == 200:
logger.info(f"API request to {url} succeeded.") logger.info(f"API request to {url} succeeded.")
@ -123,7 +126,7 @@ def about_me_embed(bot):
"available_gb": round(disk.free / (1024.0**3), 2), "available_gb": round(disk.free / (1024.0**3), 2),
"total_gb": round(disk.total / (1024.0**3), 2), "total_gb": round(disk.total / (1024.0**3), 2),
} }
uptime = datetime.utcnow() - bot.uptime uptime = utcnow() - bot.uptime
if bot.src: # remember that? if bot.src: # remember that?
description = f"This bot is [**Open Source!**](<{bot.src}>)" description = f"This bot is [**Open Source!**](<{bot.src}>)"
else: else: