Skip to content

Commit dd3e42f

Browse files
authored
Improved /stats command (#427)
* Improved `stats` command * Update clean_tempfile to properly clean
1 parent 1a60460 commit dd3e42f

2 files changed

Lines changed: 63 additions & 11 deletions

File tree

ytdlbot/utils.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ def sizeof_fmt(num: int, suffix="B"):
5252
return "%.1f%s%s" % (num, "Yi", suffix)
5353

5454

55+
def timeof_fmt(seconds: int):
56+
periods = [("d", 86400), ("h", 3600), ("m", 60), ("s", 1)]
57+
result = ""
58+
for period_name, period_seconds in periods:
59+
if seconds >= period_seconds:
60+
period_value, seconds = divmod(seconds, period_seconds)
61+
result += f"{int(period_value)}{period_name}"
62+
return result
63+
64+
5565
def is_youtube(url: str):
5666
if url.startswith("https://www.youtube.com/") or url.startswith("https://youtu.be/"):
5767
return True
@@ -220,9 +230,13 @@ def auto_restart():
220230

221231

222232
def clean_tempfile():
223-
for item in pathlib.Path(TMPFILE_PATH or tempfile.gettempdir()).glob("ytdl-*"):
224-
if time.time() - item.stat().st_ctime > 3600:
225-
shutil.rmtree(item, ignore_errors=True)
233+
patterns = ["ytdl*", "spdl*", "leech*", "direct*"]
234+
temp_path = pathlib.Path(TMPFILE_PATH or tempfile.gettempdir())
235+
236+
for pattern in patterns:
237+
for item in temp_path.glob(pattern):
238+
if time.time() - item.stat().st_ctime > 3600:
239+
shutil.rmtree(item, ignore_errors=True)
226240

227241

228242
def parse_cookie_file(cookiefile):

ytdlbot/ytdl_bot.py

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import json
1212
import logging
1313
import os
14+
import psutil
1415
import threading
1516
import random
1617
import re
@@ -62,6 +63,8 @@
6263
spdl_download_entrance,
6364
)
6465
from utils import (
66+
sizeof_fmt,
67+
timeof_fmt,
6568
auto_restart,
6669
clean_tempfile,
6770
customize_logger,
@@ -232,18 +235,52 @@ def send_message_and_measure_ping():
232235

233236
@app.on_message(filters.command(["stats"]))
234237
def stats_handler(client: Client, message: types.Message):
235-
redis = Redis()
236238
chat_id = message.chat.id
237239
client.send_chat_action(chat_id, enums.ChatAction.TYPING)
238-
if os.uname().sysname == "Darwin" or ".heroku" in os.getenv("PYTHONHOME", ""):
239-
bot_info = "Stats Unavailable."
240-
else:
241-
bot_info = get_runtime("ytdlbot_ytdl_1", "YouTube-dl")
240+
cpu_usage = psutil.cpu_percent()
241+
total, used, free, disk = psutil.disk_usage("/")
242+
swap = psutil.swap_memory()
243+
memory = psutil.virtual_memory()
244+
boot_time = psutil.boot_time()
245+
246+
owner_stats = (
247+
"\n\n⌬─────「 Stats 」─────⌬\n\n"
248+
f"<b>╭🖥️ **CPU Usage »**</b> __{cpu_usage}%__\n"
249+
f"<b>├💾 **RAM Usage »**</b> __{memory.percent}%__\n"
250+
f"<b>╰🗃️ **DISK Usage »**</b> __{disk}%__\n\n"
251+
f"<b>╭📤Upload:</b> {sizeof_fmt(psutil.net_io_counters().bytes_sent)}\n"
252+
f"<b>╰📥Download:</b> {sizeof_fmt(psutil.net_io_counters().bytes_recv)}\n\n\n"
253+
f"<b>Memory Total:</b> {sizeof_fmt(memory.total)}\n"
254+
f"<b>Memory Free:</b> {sizeof_fmt(memory.available)}\n"
255+
f"<b>Memory Used:</b> {sizeof_fmt(memory.used)}\n"
256+
f"<b>SWAP Total:</b> {sizeof_fmt(swap.total)} | <b>SWAP Usage:</b> {swap.percent}%\n\n"
257+
f"<b>Total Disk Space:</b> {sizeof_fmt(total)}\n"
258+
f"<b>Used:</b> {sizeof_fmt(used)} | <b>Free:</b> {sizeof_fmt(free)}\n\n"
259+
f"<b>Physical Cores:</b> {psutil.cpu_count(logical=False)}\n"
260+
f"<b>Total Cores:</b> {psutil.cpu_count(logical=True)}\n\n"
261+
f"<b>🤖Bot Uptime:</b> {timeof_fmt(time.time() - botStartTime)}\n"
262+
f"<b>⏲️OS Uptime:</b> {timeof_fmt(time.time() - boot_time)}\n"
263+
)
264+
265+
user_stats = (
266+
"\n\n⌬─────「 Stats 」─────⌬\n\n"
267+
f"<b>╭🖥️ **CPU Usage »**</b> __{cpu_usage}%__\n"
268+
f"<b>├💾 **RAM Usage »**</b> __{memory.percent}%__\n"
269+
f"<b>╰🗃️ **DISK Usage »**</b> __{disk}%__\n\n"
270+
f"<b>╭📤Upload:</b> {sizeof_fmt(psutil.net_io_counters().bytes_sent)}\n"
271+
f"<b>╰📥Download:</b> {sizeof_fmt(psutil.net_io_counters().bytes_recv)}\n\n\n"
272+
f"<b>Memory Total:</b> {sizeof_fmt(memory.total)}\n"
273+
f"<b>Memory Free:</b> {sizeof_fmt(memory.available)}\n"
274+
f"<b>Memory Used:</b> {sizeof_fmt(memory.used)}\n"
275+
f"<b>Total Disk Space:</b> {sizeof_fmt(total)}\n"
276+
f"<b>Used:</b> {sizeof_fmt(used)} | <b>Free:</b> {sizeof_fmt(free)}\n\n"
277+
f"<b>🤖Bot Uptime:</b> {timeof_fmt(time.time() - botStartTime)}\n"
278+
)
279+
242280
if message.chat.username == OWNER:
243-
stats = BotText.ping_worker()[:1000]
244-
client.send_document(chat_id, redis.generate_file(), caption=f"{bot_info}\n\n{stats}")
281+
message.reply_text(owner_stats, quote=True)
245282
else:
246-
client.send_message(chat_id, f"{bot_info.split('CPU')[0]}")
283+
message.reply_text(user_stats, quote=True)
247284

248285

249286
@app.on_message(filters.command(["sub_count"]))
@@ -709,6 +746,7 @@ def trx_notify(_, **kwargs):
709746

710747

711748
if __name__ == "__main__":
749+
botStartTime = time.time()
712750
MySQL()
713751
TRX_SIGNAL.connect(trx_notify)
714752
scheduler = BackgroundScheduler(timezone="Europe/London")

0 commit comments

Comments
 (0)