refactor(system-check): Improve system status view layout

Refactor the system status view to enhance readability and organization.

- Introduce `_create_aligned_block` helper for consistent, aligned text formatting.
- Consolidate bot, system, and hardware information into new aligned blocks.
- Remove redundant separators and improve overall view structure.
- Adjust progress bar length for better fit.
- Optimize user count gathering using a set for unique users.
- Improve Windows version detection and Linux motherboard info fallback.
This commit is contained in:
Slipstreamm 2025-06-14 13:18:02 -06:00
parent 96fdf225a8
commit 74be8ecb45

View File

@ -15,7 +15,7 @@ except ImportError:
WMI_AVAILABLE = False WMI_AVAILABLE = False
def create_progress_bar(value: float, total: float, length: int = 12) -> str: def create_progress_bar(value: float, total: float, length: int = 10) -> str:
"""Creates a text-based progress bar.""" """Creates a text-based progress bar."""
if total == 0: if total == 0:
percentage = 0 percentage = 0
@ -46,7 +46,6 @@ class SystemStatusView(ui.LayoutView):
cpu_usage: float, cpu_usage: float,
ram_used: int, ram_used: int,
ram_total: int, ram_total: int,
ram_percent: float,
gpu_info: str, gpu_info: str,
requester: discord.User, requester: discord.User,
) -> None: ) -> None:
@ -65,13 +64,20 @@ class SystemStatusView(ui.LayoutView):
self.cpu_usage = cpu_usage self.cpu_usage = cpu_usage
self.ram_used = ram_used self.ram_used = ram_used
self.ram_total = ram_total self.ram_total = ram_total
self.ram_percent = ram_percent
self.gpu_info = gpu_info self.gpu_info = gpu_info
self.requester = requester self.requester = requester
# --- Build the UI --- # --- Build the UI ---
self._build_ui() self._build_ui()
def _create_aligned_block(self, data: dict) -> str:
"""Creates a neatly aligned text block inside a markdown code block."""
max_key_len = max(len(k) for k in data.keys())
lines = []
for key, value in data.items():
lines.append(f"{key.ljust(max_key_len)} : {value}")
return "```\n" + "\n".join(lines) + "\n```"
def _build_ui(self): def _build_ui(self):
"""Constructs the UI elements of the view.""" """Constructs the UI elements of the view."""
# Main container with Discord's "Blurple" color # Main container with Discord's "Blurple" color
@ -79,20 +85,14 @@ class SystemStatusView(ui.LayoutView):
# --- Header --- # --- Header ---
header = ui.Section(accessory=ui.Thumbnail(media=self.bot_user.display_avatar.url)) header = ui.Section(accessory=ui.Thumbnail(media=self.bot_user.display_avatar.url))
header.add_item(ui.TextDisplay("**📊 System & Bot Status**")) header.add_item(ui.TextDisplay("**📊 System Status**"))
container.add_item(header) container.add_item(header)
container.add_item(ui.Separator(spacing=discord.SeparatorSpacing.small))
# --- Bot & System Info --- # --- Bot & System Info ---
self._add_bot_system_info(container) self._add_bot_system_info(container)
container.add_item(ui.Separator(spacing=discord.SeparatorSpacing.small))
# --- Hardware Info --- # --- Hardware Info ---
self._add_hardware_info(container) self._add_hardware_info(container)
container.add_item(ui.Separator(spacing=discord.SeparatorSpacing.small))
# --- Footer --- # --- Footer ---
self._add_footer(container) self._add_footer(container)
@ -101,49 +101,43 @@ class SystemStatusView(ui.LayoutView):
def _add_bot_system_info(self, container: ui.Container): def _add_bot_system_info(self, container: ui.Container):
"""Adds bot and system information fields.""" """Adds bot and system information fields."""
bot_info = ( container.add_item(ui.Separator(spacing=discord.SeparatorSpacing.small))
f"**🤖 Bot Information**\n"
f"`Servers :` {self.guild_count}\n" bot_data = {
f"`Users :` {self.user_count}\n" "Servers": self.guild_count,
) "Users": self.user_count
container.add_item(ui.TextDisplay(bot_info)) }
container.add_item(ui.TextDisplay("**🤖 Bot Info**" + self._create_aligned_block(bot_data)))
system_info = ( system_data = {
f"**🖥️ System Information**\n" "OS": f"{self.os_info}{self.distro_info}",
f"`OS :` {self.os_info}{self.distro_info}\n" "Hostname": self.hostname,
f"`Hostname:` {self.hostname}\n" "Uptime": self.uptime
f"`Uptime :` {self.uptime}" }
) container.add_item(ui.TextDisplay("**🖥️ System Info**" + self._create_aligned_block(system_data)))
container.add_item(ui.TextDisplay(system_info))
def _add_hardware_info(self, container: ui.Container): def _add_hardware_info(self, container: ui.Container):
"""Adds hardware information with progress bars.""" """Adds hardware information with progress bars."""
container.add_item(ui.TextDisplay("**⚙️ Hardware Utilization**")) container.add_item(ui.Separator(spacing=discord.SeparatorSpacing.small))
# RAM usage text ram_usage_text = f"{self.ram_used // (1024**2):,}MB / {self.ram_total // (1024**2):,}MB"
ram_usage_text = f"{self.ram_used // (1024**2)}MB / {self.ram_total // (1024**2)}MB"
# Progress Bars
cpu_bar = create_progress_bar(self.cpu_usage, 100.0) cpu_bar = create_progress_bar(self.cpu_usage, 100.0)
ram_bar = create_progress_bar(self.ram_used, self.ram_total) ram_bar = create_progress_bar(self.ram_used, self.ram_total)
hardware_details = ( hardware_data = {
f"`CPU ` {cpu_bar}\n" "CPU Usage": cpu_bar,
f"`RAM ` {ram_bar}\n" "RAM Usage": f"{ram_bar}\n{''.ljust(len('RAM Usage'))}{ram_usage_text}",
f"{ram_usage_text}" "Board": self.motherboard_info,
) "CPU": self.cpu_name,
container.add_item(ui.TextDisplay(hardware_details)) "GPU": self.gpu_info
}
hardware_specs = ( container.add_item(ui.TextDisplay("**⚙️ Hardware Info**" + self._create_aligned_block(hardware_data)))
f"**📋 Hardware Specifications**\n"
f"`Board:` {self.motherboard_info}\n"
f"`CPU :` {self.cpu_name}\n"
f"`GPU :` {self.gpu_info}"
)
container.add_item(ui.TextDisplay(hardware_specs))
def _add_footer(self, container: ui.Container): def _add_footer(self, container: ui.Container):
"""Adds the footer with timestamp and requester info.""" """Adds the footer with timestamp and requester info."""
container.add_item(ui.Separator(spacing=discord.SeparatorSpacing.small))
timestamp = discord.utils.format_dt(discord.utils.utcnow(), style="R") timestamp = discord.utils.format_dt(discord.utils.utcnow(), style="R")
footer_text = f"Updated: {timestamp} | Requested by: {self.requester.display_name}" footer_text = f"Updated: {timestamp} | Requested by: {self.requester.display_name}"
container.add_item(ui.TextDisplay(f"_{footer_text}_")) container.add_item(ui.TextDisplay(f"_{footer_text}_"))
@ -157,6 +151,7 @@ class SystemCheckCog(commands.Cog):
"""Gathers all system data and returns the constructed view.""" """Gathers all system data and returns the constructed view."""
# Bot information # Bot information
guild_count = len(self.bot.guilds) guild_count = len(self.bot.guilds)
# A more efficient way to get unique users, avoiding large member lists in memory
user_ids = {member.id for guild in self.bot.guilds for member in guild.members if not member.bot} user_ids = {member.id for guild in self.bot.guilds for member in guild.members if not member.bot}
user_count = len(user_ids) user_count = len(user_ids)
@ -174,8 +169,9 @@ class SystemCheckCog(commands.Cog):
distro_info_str = "" # Fail silently distro_info_str = "" # Fail silently
elif system == "Windows": elif system == "Windows":
try: try:
win_ver = platform.version() # Use a more reliable way to get Windows version
os_info = f"Windows {win_ver}" win_ver = platform.win32_ver()
os_info = f"Windows {win_ver[0]} {win_ver[2]}"
except Exception: except Exception:
pass # Fail silently pass # Fail silently
@ -189,6 +185,7 @@ class SystemCheckCog(commands.Cog):
cpu_usage = psutil.cpu_percent(interval=0.1) cpu_usage = psutil.cpu_percent(interval=0.1)
try: try:
cpu_name_base = "N/A"
if system == "Linux": if system == "Linux":
with open("/proc/cpuinfo") as f: with open("/proc/cpuinfo") as f:
for line in f: for line in f:
@ -211,8 +208,9 @@ class SystemCheckCog(commands.Cog):
try: try:
gpus = GPUtil.getGPUs() gpus = GPUtil.getGPUs()
if gpus: if gpus:
# Format multi-GPU info on new lines for readability
gpu_info_lines = [f"{gpu.name} ({gpu.load*100:.1f}% Load)" for gpu in gpus] gpu_info_lines = [f"{gpu.name} ({gpu.load*100:.1f}% Load)" for gpu in gpus]
gpu_info = " | ".join(gpu_info_lines) gpu_info = "\n".join(gpu_info_lines)
else: else:
gpu_info = "No dedicated GPU detected" gpu_info = "No dedicated GPU detected"
except Exception: except Exception:
@ -234,7 +232,6 @@ class SystemCheckCog(commands.Cog):
cpu_usage=cpu_usage, cpu_usage=cpu_usage,
ram_used=memory.used, ram_used=memory.used,
ram_total=memory.total, ram_total=memory.total,
ram_percent=memory.percent,
gpu_info=gpu_info, gpu_info=gpu_info,
requester=user, requester=user,
) )
@ -248,8 +245,13 @@ class SystemCheckCog(commands.Cog):
board = w.Win32_BaseBoard()[0] board = w.Win32_BaseBoard()[0]
return f"{board.Manufacturer} {board.Product}" return f"{board.Manufacturer} {board.Product}"
elif system == "Linux": elif system == "Linux":
with open("/sys/devices/virtual/dmi/id/product_name", "r") as f: # Check for product_name first, then fallback to board_name
return f.read().strip() try:
with open("/sys/devices/virtual/dmi/id/product_name", "r") as f:
return f.read().strip()
except FileNotFoundError:
with open("/sys/devices/virtual/dmi/id/board_name", "r") as f:
return f.read().strip()
return "N/A" return "N/A"
except Exception: except Exception:
return "N/A" return "N/A"
@ -269,4 +271,4 @@ class SystemCheckCog(commands.Cog):
async def setup(bot): async def setup(bot):
await bot.add_cog(SystemCheckCog(bot)) await bot.add_cog(SystemCheckCog(bot))