From 56e5d79e3e8571b83facf2dbcdf5f3fd2b3b98f2 Mon Sep 17 00:00:00 2001 From: mr-forust Date: Thu, 21 May 2026 22:14:29 +0200 Subject: [PATCH] refactor: improved error handling, timeouts and use temp files --- main.py | 18 +++++++++++++----- utils/config.py | 2 +- utils/scripts.py | 24 ++++++++++++------------ 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/main.py b/main.py index cc823b1..8e76c29 100644 --- a/main.py +++ b/main.py @@ -90,11 +90,19 @@ def load_missing_modules(): os.makedirs(custom_modules_path, exist_ok=True) try: - f = requests.get( - "https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt" - ).text - except Exception: - logging.error("Failed to fetch custom modules list") + resp = requests.get( + "https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt", + timeout=10, + ) + if not resp.ok: + logging.error( + "Failed to fetch custom modules list: HTTP %s", + resp.status_code, + ) + return + f = resp.text + except Exception as e: + logging.error("Failed to fetch custom modules list: %s", e) return modules_dict = { line.split("/")[-1].split()[0]: line.strip() for line in f.splitlines() diff --git a/utils/config.py b/utils/config.py index 4204e68..a8879d5 100644 --- a/utils/config.py +++ b/utils/config.py @@ -1,8 +1,8 @@ import os import environs +env = environs.Env() try: - env = environs.Env() env.read_env("./.env") except FileNotFoundError: print("No .env file found, using os.environ.") diff --git a/utils/scripts.py b/utils/scripts.py index 6dc7d44..cb9604e 100644 --- a/utils/scripts.py +++ b/utils/scripts.py @@ -22,6 +22,7 @@ import re import shlex import subprocess import sys +import tempfile import time import traceback from PIL import Image @@ -85,13 +86,17 @@ async def edit_or_send_as_file( return if len(tex) > 1024: await message.edit("OutPut is Too Large, Sending As File!") - file_names = f"{file_name}.txt" - with open(file_names, "w") as fn: + with tempfile.NamedTemporaryFile( + "w", delete=False, suffix=".txt", prefix=f"{file_name}_" + ) as fn: fn.write(tex) - await client.send_document(message.chat.id, file_names, caption=caption) - await message.delete() - if os.path.exists(file_names): - os.remove(file_names) + temp_path = fn.name + try: + await client.send_document(message.chat.id, temp_path, caption=caption) + await message.delete() + finally: + if os.path.exists(temp_path): + os.remove(temp_path) return return await message.edit(tex) @@ -249,12 +254,7 @@ def is_admin(func): chat_member = await client.get_chat_member( message.chat.id, message.from_user.id ) - chat_admins = [] - async for member in client.get_chat_members( - message.chat.id, filter=ChatMembersFilter.ADMINISTRATORS - ): - chat_admins.append(member) - if chat_member in chat_admins: + if chat_member.status in ("administrator", "creator"): return await func(client, message) await message.edit("You need to be an admin to perform this action.") except UserNotParticipant: