From dd3e42ff911d388755b9e4014bf7503689349c29 Mon Sep 17 00:00:00 2001
From: Sanuja Seneviratne <66342986+SanujaNS@users.noreply.github.com>
Date: Sat, 21 Sep 2024 20:26:15 +0530
Subject: [PATCH] Improved `/stats` command (#427)
* Improved `stats` command
* Update clean_tempfile to properly clean
---
ytdlbot/utils.py | 20 ++++++++++++++---
ytdlbot/ytdl_bot.py | 54 ++++++++++++++++++++++++++++++++++++++-------
2 files changed, 63 insertions(+), 11 deletions(-)
diff --git a/ytdlbot/utils.py b/ytdlbot/utils.py
index 1075578c..4ec317d4 100644
--- a/ytdlbot/utils.py
+++ b/ytdlbot/utils.py
@@ -52,6 +52,16 @@ def sizeof_fmt(num: int, suffix="B"):
return "%.1f%s%s" % (num, "Yi", suffix)
+def timeof_fmt(seconds: int):
+ periods = [("d", 86400), ("h", 3600), ("m", 60), ("s", 1)]
+ result = ""
+ for period_name, period_seconds in periods:
+ if seconds >= period_seconds:
+ period_value, seconds = divmod(seconds, period_seconds)
+ result += f"{int(period_value)}{period_name}"
+ return result
+
+
def is_youtube(url: str):
if url.startswith("https://www.youtube.com/") or url.startswith("https://youtu.be/"):
return True
@@ -220,9 +230,13 @@ def auto_restart():
def clean_tempfile():
- for item in pathlib.Path(TMPFILE_PATH or tempfile.gettempdir()).glob("ytdl-*"):
- if time.time() - item.stat().st_ctime > 3600:
- shutil.rmtree(item, ignore_errors=True)
+ patterns = ["ytdl*", "spdl*", "leech*", "direct*"]
+ temp_path = pathlib.Path(TMPFILE_PATH or tempfile.gettempdir())
+
+ for pattern in patterns:
+ for item in temp_path.glob(pattern):
+ if time.time() - item.stat().st_ctime > 3600:
+ shutil.rmtree(item, ignore_errors=True)
def parse_cookie_file(cookiefile):
diff --git a/ytdlbot/ytdl_bot.py b/ytdlbot/ytdl_bot.py
index ebcdc0ad..7e296743 100644
--- a/ytdlbot/ytdl_bot.py
+++ b/ytdlbot/ytdl_bot.py
@@ -11,6 +11,7 @@
import json
import logging
import os
+import psutil
import threading
import random
import re
@@ -62,6 +63,8 @@
spdl_download_entrance,
)
from utils import (
+ sizeof_fmt,
+ timeof_fmt,
auto_restart,
clean_tempfile,
customize_logger,
@@ -232,18 +235,52 @@ def send_message_and_measure_ping():
@app.on_message(filters.command(["stats"]))
def stats_handler(client: Client, message: types.Message):
- redis = Redis()
chat_id = message.chat.id
client.send_chat_action(chat_id, enums.ChatAction.TYPING)
- if os.uname().sysname == "Darwin" or ".heroku" in os.getenv("PYTHONHOME", ""):
- bot_info = "Stats Unavailable."
- else:
- bot_info = get_runtime("ytdlbot_ytdl_1", "YouTube-dl")
+ cpu_usage = psutil.cpu_percent()
+ total, used, free, disk = psutil.disk_usage("/")
+ swap = psutil.swap_memory()
+ memory = psutil.virtual_memory()
+ boot_time = psutil.boot_time()
+
+ owner_stats = (
+ "\n\n⌬─────「 Stats 」─────⌬\n\n"
+ f"╭🖥️ **CPU Usage »** __{cpu_usage}%__\n"
+ f"├💾 **RAM Usage »** __{memory.percent}%__\n"
+ f"╰🗃️ **DISK Usage »** __{disk}%__\n\n"
+ f"╭📤Upload: {sizeof_fmt(psutil.net_io_counters().bytes_sent)}\n"
+ f"╰📥Download: {sizeof_fmt(psutil.net_io_counters().bytes_recv)}\n\n\n"
+ f"Memory Total: {sizeof_fmt(memory.total)}\n"
+ f"Memory Free: {sizeof_fmt(memory.available)}\n"
+ f"Memory Used: {sizeof_fmt(memory.used)}\n"
+ f"SWAP Total: {sizeof_fmt(swap.total)} | SWAP Usage: {swap.percent}%\n\n"
+ f"Total Disk Space: {sizeof_fmt(total)}\n"
+ f"Used: {sizeof_fmt(used)} | Free: {sizeof_fmt(free)}\n\n"
+ f"Physical Cores: {psutil.cpu_count(logical=False)}\n"
+ f"Total Cores: {psutil.cpu_count(logical=True)}\n\n"
+ f"🤖Bot Uptime: {timeof_fmt(time.time() - botStartTime)}\n"
+ f"⏲️OS Uptime: {timeof_fmt(time.time() - boot_time)}\n"
+ )
+
+ user_stats = (
+ "\n\n⌬─────「 Stats 」─────⌬\n\n"
+ f"╭🖥️ **CPU Usage »** __{cpu_usage}%__\n"
+ f"├💾 **RAM Usage »** __{memory.percent}%__\n"
+ f"╰🗃️ **DISK Usage »** __{disk}%__\n\n"
+ f"╭📤Upload: {sizeof_fmt(psutil.net_io_counters().bytes_sent)}\n"
+ f"╰📥Download: {sizeof_fmt(psutil.net_io_counters().bytes_recv)}\n\n\n"
+ f"Memory Total: {sizeof_fmt(memory.total)}\n"
+ f"Memory Free: {sizeof_fmt(memory.available)}\n"
+ f"Memory Used: {sizeof_fmt(memory.used)}\n"
+ f"Total Disk Space: {sizeof_fmt(total)}\n"
+ f"Used: {sizeof_fmt(used)} | Free: {sizeof_fmt(free)}\n\n"
+ f"🤖Bot Uptime: {timeof_fmt(time.time() - botStartTime)}\n"
+ )
+
if message.chat.username == OWNER:
- stats = BotText.ping_worker()[:1000]
- client.send_document(chat_id, redis.generate_file(), caption=f"{bot_info}\n\n{stats}")
+ message.reply_text(owner_stats, quote=True)
else:
- client.send_message(chat_id, f"{bot_info.split('CPU')[0]}")
+ message.reply_text(user_stats, quote=True)
@app.on_message(filters.command(["sub_count"]))
@@ -709,6 +746,7 @@ def trx_notify(_, **kwargs):
if __name__ == "__main__":
+ botStartTime = time.time()
MySQL()
TRX_SIGNAL.connect(trx_notify)
scheduler = BackgroundScheduler(timezone="Europe/London")