Skip to content

Commit

Permalink
Improved /stats command (#427)
Browse files Browse the repository at this point in the history
* Improved `stats` command

* Update clean_tempfile to properly clean
  • Loading branch information
SanujaNS authored Sep 21, 2024
1 parent 1a60460 commit dd3e42f
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 11 deletions.
20 changes: 17 additions & 3 deletions ytdlbot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
54 changes: 46 additions & 8 deletions ytdlbot/ytdl_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import json
import logging
import os
import psutil
import threading
import random
import re
Expand Down Expand Up @@ -62,6 +63,8 @@
spdl_download_entrance,
)
from utils import (
sizeof_fmt,
timeof_fmt,
auto_restart,
clean_tempfile,
customize_logger,
Expand Down Expand Up @@ -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"<b>╭🖥️ **CPU Usage »**</b> __{cpu_usage}%__\n"
f"<b>├💾 **RAM Usage »**</b> __{memory.percent}%__\n"
f"<b>╰🗃️ **DISK Usage »**</b> __{disk}%__\n\n"
f"<b>╭📤Upload:</b> {sizeof_fmt(psutil.net_io_counters().bytes_sent)}\n"
f"<b>╰📥Download:</b> {sizeof_fmt(psutil.net_io_counters().bytes_recv)}\n\n\n"
f"<b>Memory Total:</b> {sizeof_fmt(memory.total)}\n"
f"<b>Memory Free:</b> {sizeof_fmt(memory.available)}\n"
f"<b>Memory Used:</b> {sizeof_fmt(memory.used)}\n"
f"<b>SWAP Total:</b> {sizeof_fmt(swap.total)} | <b>SWAP Usage:</b> {swap.percent}%\n\n"
f"<b>Total Disk Space:</b> {sizeof_fmt(total)}\n"
f"<b>Used:</b> {sizeof_fmt(used)} | <b>Free:</b> {sizeof_fmt(free)}\n\n"
f"<b>Physical Cores:</b> {psutil.cpu_count(logical=False)}\n"
f"<b>Total Cores:</b> {psutil.cpu_count(logical=True)}\n\n"
f"<b>🤖Bot Uptime:</b> {timeof_fmt(time.time() - botStartTime)}\n"
f"<b>⏲️OS Uptime:</b> {timeof_fmt(time.time() - boot_time)}\n"
)

user_stats = (
"\n\n⌬─────「 Stats 」─────⌬\n\n"
f"<b>╭🖥️ **CPU Usage »**</b> __{cpu_usage}%__\n"
f"<b>├💾 **RAM Usage »**</b> __{memory.percent}%__\n"
f"<b>╰🗃️ **DISK Usage »**</b> __{disk}%__\n\n"
f"<b>╭📤Upload:</b> {sizeof_fmt(psutil.net_io_counters().bytes_sent)}\n"
f"<b>╰📥Download:</b> {sizeof_fmt(psutil.net_io_counters().bytes_recv)}\n\n\n"
f"<b>Memory Total:</b> {sizeof_fmt(memory.total)}\n"
f"<b>Memory Free:</b> {sizeof_fmt(memory.available)}\n"
f"<b>Memory Used:</b> {sizeof_fmt(memory.used)}\n"
f"<b>Total Disk Space:</b> {sizeof_fmt(total)}\n"
f"<b>Used:</b> {sizeof_fmt(used)} | <b>Free:</b> {sizeof_fmt(free)}\n\n"
f"<b>🤖Bot Uptime:</b> {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"]))
Expand Down Expand Up @@ -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")
Expand Down

0 comments on commit dd3e42f

Please sign in to comment.