From 47251ad9cc815b6c75a2585d4637224869b9ef67 Mon Sep 17 00:00:00 2001 From: Dawn India Date: Wed, 14 Aug 2024 20:12:05 +0530 Subject: [PATCH] Minor Switched to NekoZee Signed-off-by: Dawn India --- bot/__init__.py | 5 + bot/__main__.py | 12 +- bot/helper/common.py | 21 +- bot/helper/ext_utils/bot_utils.py | 9 +- bot/helper/ext_utils/db_handler.py | 30 +- bot/helper/ext_utils/files_utils.py | 6 +- bot/helper/ext_utils/media_utils.py | 6 + bot/helper/listeners/ytdlp_listener.py | 10 +- .../download_utils/direct_link_generator.py | 5 +- .../task_utils/download_utils/jd_download.py | 12 +- .../download_utils/telegram_download.py | 21 +- bot/helper/task_utils/gdrive_utils/list.py | 16 +- .../status_utils/telegram_status.py | 4 +- bot/helper/task_utils/telegram_uploader.py | 10 +- bot/helper/telegram_helper/bot_commands.py | 2 +- bot/modules/authorize.py | 12 +- bot/modules/bot_settings.py | 300 +++++----- bot/modules/cancel_task.py | 6 +- bot/modules/clone.py | 3 +- bot/modules/exec.py | 9 +- bot/modules/file_selector.py | 3 +- bot/modules/force_start.py | 3 +- bot/modules/gd_count.py | 3 +- bot/modules/gd_delete.py | 3 +- bot/modules/gd_search.py | 3 +- bot/modules/leech_del.py | 3 +- bot/modules/mirror_leech.py | 24 +- bot/modules/rmdb.py | 6 +- bot/modules/rss.py | 217 ++++--- bot/modules/shell.py | 6 +- bot/modules/status.py | 22 +- bot/modules/torrent_search.py | 3 +- bot/modules/users_settings.py | 543 ++++++++++-------- bot/modules/ytdlp.py | 6 +- update.py | 1 + 35 files changed, 704 insertions(+), 641 deletions(-) diff --git a/bot/__init__.py b/bot/__init__.py index 2e0d892e5d55..8b83bfb71209 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -8,6 +8,7 @@ Lock, get_event_loop ) +from concurrent.futures import ThreadPoolExecutor from dotenv import ( load_dotenv, dotenv_values @@ -40,6 +41,7 @@ Popen, run ) +from sys import exit from time import time from tzlocal import get_localzone from uvloop import install @@ -60,6 +62,8 @@ botStartTime = time() bot_loop = get_event_loop() +THREADPOOL = ThreadPoolExecutor(max_workers=99999) +bot_loop.set_default_executor(THREADPOOL) basicConfig( format="%(levelname)s | From %(name)s -> %(module)s line no: %(lineno)d | %(message)s", @@ -1271,6 +1275,7 @@ app_version="@Z_Mirror Session", device_model="@Z_Mirror Bot", system_version="@Z_Mirror Server", + workers=99999, ).start() BASE += ("oAtiUyppVYRQkuWg8DG2p") diff --git a/bot/__main__.py b/bot/__main__.py index fbae7282dd31..99a93e369d16 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -316,7 +316,8 @@ async def main(): MessageHandler( log, filters=command( - BotCommands.LogCommand + BotCommands.LogCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) @@ -324,7 +325,8 @@ async def main(): MessageHandler( restart, filters=command( - BotCommands.RestartCommand + BotCommands.RestartCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) @@ -332,7 +334,8 @@ async def main(): MessageHandler( ping, filters=command( - BotCommands.PingCommand + BotCommands.PingCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) @@ -340,7 +343,8 @@ async def main(): MessageHandler( bot_help, filters=command( - BotCommands.HelpCommand + BotCommands.HelpCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/helper/common.py b/bot/helper/common.py index ac42788a74ba..038d6d5f23a0 100644 --- a/bot/helper/common.py +++ b/bot/helper/common.py @@ -233,15 +233,20 @@ def getConfigPath(self, dest): ) async def isTokenExists(self, path, status): + if not self.upDest: + raise ValueError("No Upload Destination!") + if ( + not is_gdrive_id(self.upDest) # type: ignore + and not is_rclone_path(self.upDest) # type: ignore + ): + raise ValueError("Wrong Upload Destination!") if is_rclone_path(path): config_path = self.getConfigPath(path) - if ( config_path != "rclone.conf" and status == "up" ): self.privateLink = True - if not await aiopath.exists(config_path): raise ValueError(f"Rclone Config: {config_path} not Exists!") @@ -401,6 +406,11 @@ async def beforeStart(self): if ( not self.isYtDlp and not self.isJd + and ( + is_gdrive_id(self.link) + or is_rclone_path(self.link) + or is_gdrive_link(self.link) + ) ): await self.isTokenExists( self.link, @@ -467,13 +477,6 @@ async def beforeStart(self): self.userDict.get("gdrive_id") or config_dict["GDRIVE_ID"] ) - if not self.upDest: - raise ValueError("No Upload Destination!") - if ( - not is_gdrive_id(str(self.upDest)) - and not is_rclone_path(str(self.upDest)) - ): - raise ValueError("Wrong Upload Destination!") if ( self.upDest not in [ diff --git a/bot/helper/ext_utils/bot_utils.py b/bot/helper/ext_utils/bot_utils.py index 71f0af8dec26..fc5257ace281 100644 --- a/bot/helper/ext_utils/bot_utils.py +++ b/bot/helper/ext_utils/bot_utils.py @@ -5,7 +5,6 @@ sleep, ) from asyncio.subprocess import PIPE -from concurrent.futures import ThreadPoolExecutor from functools import partial, wraps from pyrogram.types import BotCommand @@ -26,8 +25,6 @@ from bot.helper.telegram_helper.button_build import ButtonMaker from bot.helper.telegram_helper.bot_commands import BotCommands -THREADPOOL = ThreadPoolExecutor(max_workers=1000) - COMMAND_USAGE = {} @@ -211,10 +208,6 @@ async def set_commands(client): f"{BotCommands.StatsCommand[0]}", "ᴄʜᴇᴄᴋ ʙᴏᴛ ꜱᴛᴀᴛꜱ" ), - BotCommand( - f"{BotCommands.SelectCommand}", - "ꜱᴇʟᴇᴄᴛ ꜰɪʟᴇꜱ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ" - ), BotCommand( f"{BotCommands.CancelTaskCommand[0]}", "ᴄᴀɴᴄᴇʟ ᴀ ᴛᴀꜱᴋ" @@ -435,7 +428,7 @@ async def sync_to_async(func, *args, wait=True, **kwargs): **kwargs ) future = bot_loop.run_in_executor( - THREADPOOL, + None, pfunc ) return ( diff --git a/bot/helper/ext_utils/db_handler.py b/bot/helper/ext_utils/db_handler.py index 9937c20b6dcc..8648831f9f93 100644 --- a/bot/helper/ext_utils/db_handler.py +++ b/bot/helper/ext_utils/db_handler.py @@ -51,7 +51,6 @@ async def db_load(self): ) except Exception as e: LOGGER.error(f"DataBase Collection Error: {e}") - self._conn.close # type: ignore return # Save Aria2c options if await self._db.settings.aria2c.find_one({"_id": bot_id}) is None: # type: ignore @@ -121,7 +120,6 @@ async def db_load(self): user_id = row["_id"] del row["_id"] rss_dict[user_id] = row - self._conn.close # type: ignore async def update_deploy_config(self): if self._err: @@ -132,7 +130,6 @@ async def update_deploy_config(self): current_config, upsert=True ) - self._conn.close # type: ignore async def update_config(self, dict_): if self._err: @@ -142,7 +139,6 @@ async def update_config(self, dict_): {"$set": dict_}, upsert=True ) - self._conn.close # type: ignore async def update_aria2(self, key, value): if self._err: @@ -152,7 +148,6 @@ async def update_aria2(self, key, value): {"$set": {key: value}}, upsert=True ) - self._conn.close # type: ignore async def update_qbittorrent(self, key, value): if self._err: @@ -162,7 +157,6 @@ async def update_qbittorrent(self, key, value): {"$set": {key: value}}, upsert=True ) - self._conn.close # type: ignore async def save_qbit_settings(self): if self._err: @@ -172,7 +166,6 @@ async def save_qbit_settings(self): qbit_options, upsert=True ) - self._conn.close # type: ignore async def update_private_file(self, path): if self._err: @@ -190,8 +183,6 @@ async def update_private_file(self, path): ) if path == "config.env": await self.update_deploy_config() - else: - self._conn.close # type: ignore async def update_nzb_config(self): async with aiopen( @@ -223,7 +214,6 @@ async def update_user_data(self, user_id): data, upsert=True ) - self._conn.close # type: ignore async def update_user_doc(self, user_id, key, path=""): if self._err: @@ -241,7 +231,6 @@ async def update_user_doc(self, user_id, key, path=""): {"$set": {key: doc_bin}}, upsert=True ) - self._conn.close # type: ignore async def rss_update_all(self): if self._err: @@ -252,7 +241,6 @@ async def rss_update_all(self): rss_dict[user_id], upsert=True ) - self._conn.close # type: ignore async def rss_update(self, user_id): if self._err: @@ -262,13 +250,11 @@ async def rss_update(self, user_id): rss_dict[user_id], upsert=True ) - self._conn.close # type: ignore async def rss_delete(self, user_id): if self._err: return await self._db.rss[bot_id].delete_one({"_id": user_id}) # type: ignore - self._conn.close # type: ignore async def add_incomplete_task(self, cid, link, tag): if self._err: @@ -280,13 +266,11 @@ async def add_incomplete_task(self, cid, link, tag): "tag": tag } ) - self._conn.close # type: ignore async def rm_complete_task(self, link): if self._err: return await self._db.tasks[bot_id].delete_one({"_id": link}) # type: ignore - self._conn.close # type: ignore async def get_incomplete_tasks(self): notifier_dict = {} @@ -304,14 +288,12 @@ async def get_incomplete_tasks(self): else: notifier_dict[row["cid"]] = {row["tag"]: [row["_id"]]} await self._db.tasks[bot_id].drop() # type: ignore - self._conn.close # type: ignore return notifier_dict # return a dict ==> {cid: {tag: [_id, _id, ...]}} async def trunc_table(self, name): if self._err: return await self._db[name][bot_id].drop() # type: ignore - self._conn.close # type: ignore async def add_download_url(self, url: str, tag: str): if self._err: @@ -326,13 +308,11 @@ async def add_download_url(self, url: str, tag: str): {"$set": download}, upsert=True ) - self._conn.close # type: ignore async def check_download(self, url: str): if self._err: return exist = await self._db.download_links.find_one({"_id": url}) # type: ignore - self._conn.close # type: ignore return exist async def clear_download_links(self, botName=None): @@ -341,13 +321,11 @@ async def clear_download_links(self, botName=None): if not botName: botName = bot_name await self._db.download_links.delete_many({"botname": botName}) # type: ignore - self._conn.close # type: ignore async def remove_download(self, url: str): if self._err: return await self._db.download_links.delete_one({"_id": url}) # type: ignore - self._conn.close # type: ignore async def update_user_tdata(self, user_id, token, time): if self._err: @@ -357,7 +335,6 @@ async def update_user_tdata(self, user_id, token, time): {"$set": {"token": token, "time": time}}, upsert=True ) - self._conn.close # type: ignore async def update_user_token(self, user_id, token, inittime): if self._err: @@ -367,7 +344,6 @@ async def update_user_token(self, user_id, token, inittime): {"$set": {"token": token, "inittime": inittime}}, upsert=True ) - self._conn.close # type: ignore async def get_token_expire_time(self, user_id): if self._err: @@ -375,7 +351,6 @@ async def get_token_expire_time(self, user_id): user_data = await self._db.access_token.find_one({"_id": user_id}) # type: ignore if user_data: return user_data.get("time") - self._conn.close # type: ignore return None async def get_user_token(self, user_id): @@ -384,7 +359,6 @@ async def get_user_token(self, user_id): user_data = await self._db.access_token.find_one({"_id": user_id}) # type: ignore if user_data: return user_data.get("token") - self._conn.close # type: ignore return None async def get_token_init_time(self, user_id): @@ -393,11 +367,9 @@ async def get_token_init_time(self, user_id): user_data = await self._db.access_token.find_one({"_id": user_id}) # type: ignore if user_data: return user_data.get("inittime") - self._conn.close # type: ignore return None async def delete_all_access_tokens(self): if self._err: return - await self._db.access_token.delete_many({}) # type: ignore - self._conn.close # type: ignore \ No newline at end of file + await self._db.access_token.delete_many({}) # type: ignore \ No newline at end of file diff --git a/bot/helper/ext_utils/files_utils.py b/bot/helper/ext_utils/files_utils.py index 98824509a419..0929615b5de9 100644 --- a/bot/helper/ext_utils/files_utils.py +++ b/bot/helper/ext_utils/files_utils.py @@ -22,7 +22,7 @@ rmtree ) from subprocess import run as srun -from sys import exit as sexit +from sys import exit from bot import ( aria2, @@ -156,10 +156,10 @@ def exit_clean_up(signal, frame): "-f", "gunicorn|aria2c|qbittorrent-nox|ffmpeg|java" ]) - sexit(0) + exit(0) except KeyboardInterrupt: LOGGER.warning("Force Exiting before the cleanup finishes!") - sexit(1) + exit(1) async def clean_unwanted(path, custom_list=None): diff --git a/bot/helper/ext_utils/media_utils.py b/bot/helper/ext_utils/media_utils.py index bd7615124449..773b0cc8b7b7 100644 --- a/bot/helper/ext_utils/media_utils.py +++ b/bot/helper/ext_utils/media_utils.py @@ -396,6 +396,8 @@ async def take_ss(video_file, ss_nb) -> bool: "1", "-frames:v", "1", + "-threads", + f"{cpu_count() // 2}", # type: ignore output, ] cap_time += interval @@ -450,6 +452,8 @@ async def get_audio_thumb(audio_file): "-an", "-vcodec", "copy", + "-threads", + f"{cpu_count() // 2}", # type: ignore des_dir, ] ( @@ -493,6 +497,8 @@ async def create_thumbnail(video_file, duration): "thumbnail", "-frames:v", "1", + "-threads", + f"{cpu_count() // 2}", # type: ignore des_dir, ] try: diff --git a/bot/helper/listeners/ytdlp_listener.py b/bot/helper/listeners/ytdlp_listener.py index 43efd255ec84..9508446445dd 100644 --- a/bot/helper/listeners/ytdlp_listener.py +++ b/bot/helper/listeners/ytdlp_listener.py @@ -3,13 +3,8 @@ from asyncio import ( Event, wait_for, - wrap_future ) -from bot.helper.ext_utils.bot_utils import ( - new_task, - new_thread -) from bot.helper.ext_utils.status_utils import ( get_readable_file_size, get_readable_time @@ -33,7 +28,6 @@ from yt_dlp import YoutubeDL -@new_task async def select_format(_, query, obj): data = query.data.split() message = query.message @@ -92,7 +86,6 @@ def __init__( self.qual = None self.tag = listener.tag - @new_thread async def _event_handler(self): pfunc = partial( select_format, @@ -130,7 +123,6 @@ async def _event_handler(self): await delete_links(self.listener.message) async def get_quality(self, result): - future = self._event_handler() buttons = ButtonMaker() if "entries" in result: self._is_playlist = True @@ -278,7 +270,7 @@ async def get_quality(self, result): msg, self._main_buttons ) - await wrap_future(future) # type: ignore + await self._event_handler() if not self.listener.isCancelled: await deleteMessage(self._reply_to) return self.qual diff --git a/bot/helper/task_utils/download_utils/direct_link_generator.py b/bot/helper/task_utils/download_utils/direct_link_generator.py index ea5782ce1ee4..0782c7115076 100644 --- a/bot/helper/task_utils/download_utils/direct_link_generator.py +++ b/bot/helper/task_utils/download_utils/direct_link_generator.py @@ -234,7 +234,10 @@ def direct_link_generator(link): def get_captcha_token(session, params): recaptcha_api = "https://www.google.com/recaptcha/api2" - res = session.get(f"{recaptcha_api}/anchor", params=params) + res = session.get( + f"{recaptcha_api}/anchor", + params=params + ) anchor_html = HTML(res.text) if not (anchor_token := anchor_html.xpath('//input[@id="recaptcha-token"]/@value')): return diff --git a/bot/helper/task_utils/download_utils/jd_download.py b/bot/helper/task_utils/download_utils/jd_download.py index 9c55a2447b84..446d2b82f762 100644 --- a/bot/helper/task_utils/download_utils/jd_download.py +++ b/bot/helper/task_utils/download_utils/jd_download.py @@ -2,7 +2,6 @@ Event, sleep, wait_for, - wrap_future, ) from functools import partial from pyrogram.filters import ( @@ -24,11 +23,7 @@ jd_lock, jd_downloads, ) -from bot.helper.ext_utils.bot_utils import ( - new_thread, - retry_function, - new_task -) +from bot.helper.ext_utils.bot_utils import retry_function from bot.helper.ext_utils.jdownloader_booter import jdownloader from bot.helper.ext_utils.task_manager import ( check_running_tasks, @@ -51,7 +46,6 @@ ) -@new_task async def configureDownload(_, query, obj): data = query.data.split() message = query.message @@ -74,7 +68,6 @@ def __init__(self, listener): self.listener = listener self.event = Event() - @new_thread async def _event_handler(self): pfunc = partial( configureDownload, @@ -108,7 +101,6 @@ async def _event_handler(self): self.listener.client.remove_handler(*handler) async def waitForConfigurations(self): - future = self._event_handler() buttons = ButtonMaker() buttons.ubutton( "Select", @@ -131,7 +123,7 @@ async def waitForConfigurations(self): msg, button ) - await wrap_future(future) # type: ignore + await self._event_handler() if not self.listener.isCancelled: await deleteMessage(self._reply_to) return self.listener.isCancelled diff --git a/bot/helper/task_utils/download_utils/telegram_download.py b/bot/helper/task_utils/download_utils/telegram_download.py index 67cfafa455ad..1ca691360916 100644 --- a/bot/helper/task_utils/download_utils/telegram_download.py +++ b/bot/helper/task_utils/download_utils/telegram_download.py @@ -3,7 +3,10 @@ sleep ) from time import time -from pyrogram.errors import FloodWait +from pyrogram.errors import ( + FloodWait, + FloodPremiumWait +) from bot import ( config_dict, @@ -15,10 +18,16 @@ bot, user, ) -from bot.helper.ext_utils.task_manager import check_running_tasks, stop_duplicate_check +from bot.helper.ext_utils.task_manager import ( + check_running_tasks, + stop_duplicate_check +) from bot.helper.task_utils.status_utils.queue_status import QueueStatus from bot.helper.task_utils.status_utils.telegram_status import TelegramStatus -from bot.helper.telegram_helper.message_utils import sendMessage, sendStatusMessage +from bot.helper.telegram_helper.message_utils import ( + sendMessage, + sendStatusMessage +) global_lock = Lock() GLOBAL_GID = set() @@ -89,7 +98,11 @@ async def _download(self, message, path): if self._listener.isCancelled: await self._onDownloadError("Cancelled by user!") return - except FloodWait as f: + + except ( + FloodWait, + FloodPremiumWait + ) as f: LOGGER.warning(str(f)) await sleep(f.value) # type: ignore except Exception as e: diff --git a/bot/helper/task_utils/gdrive_utils/list.py b/bot/helper/task_utils/gdrive_utils/list.py index 22776f927e56..c46aa2e11c1f 100644 --- a/bot/helper/task_utils/gdrive_utils/list.py +++ b/bot/helper/task_utils/gdrive_utils/list.py @@ -1,9 +1,8 @@ from aiofiles.os import path as aiopath from asyncio import ( - wait_for, Event, - wrap_future, - gather + gather, + wait_for ) from functools import partial from logging import getLogger @@ -17,11 +16,7 @@ from time import time from bot import config_dict -from bot.helper.ext_utils.bot_utils import ( - new_thread, - new_task, - update_user_ldata -) +from bot.helper.ext_utils.bot_utils import update_user_ldata from bot.helper.ext_utils.db_handler import DbManager from bot.helper.ext_utils.status_utils import ( get_readable_file_size, @@ -41,7 +36,6 @@ LIST_LIMIT = 6 -@new_task async def id_updates(_, query, obj): await query.answer() message = query.message @@ -168,7 +162,6 @@ def __init__(self, listener): self.page_step = 1 super().__init__() - @new_thread async def _event_handler(self): pfunc = partial(id_updates, obj=self) handler = self.listener.client.add_handler( @@ -571,7 +564,6 @@ async def get_pevious_id(self): async def get_target_id(self, status, token_path=None): self.list_status = status - future = self._event_handler() if token_path is None: ( self._token_user, @@ -594,7 +586,7 @@ async def get_target_id(self, status, token_path=None): self.token_path = token_path self.use_sa = self.token_path == "accounts" await self.list_drives() - await wrap_future(future) # type: ignore + await self._event_handler() if self._reply_to: await deleteMessage(self._reply_to) if not self.listener.isCancelled: diff --git a/bot/helper/task_utils/status_utils/telegram_status.py b/bot/helper/task_utils/status_utils/telegram_status.py index 9fd6ec3e515c..22ef95e71c1c 100644 --- a/bot/helper/task_utils/status_utils/telegram_status.py +++ b/bot/helper/task_utils/status_utils/telegram_status.py @@ -13,10 +13,10 @@ def __init__(self, listener, obj, gid, status): self._size = self.listener.size self._gid = gid self._status = status - self.engine = f"PyroZee v{self._eng_ver()}" + self.engine = f"NekoZee v{self._eng_ver()}" def _eng_ver(self): - return get_distribution("pyrozee").version + return get_distribution("nekozee").version def processed_bytes(self): return get_readable_file_size(self._obj.processed_bytes) diff --git a/bot/helper/task_utils/telegram_uploader.py b/bot/helper/task_utils/telegram_uploader.py index ac4e034b6042..ab4168ae811b 100644 --- a/bot/helper/task_utils/telegram_uploader.py +++ b/bot/helper/task_utils/telegram_uploader.py @@ -19,7 +19,9 @@ ) from pyrogram.errors import ( FloodWait, - RPCError + FloodPremiumWait, + RPCError, + SlowmodeWait ) from pyrogram.types import ( InputMediaVideo, @@ -810,7 +812,11 @@ async def _upload_file(self, cap_mono, file, o_path, force_document=False): and await aiopath.exists(thumb) ): await remove(thumb) - except FloodWait as f: + except ( + FloodWait, + FloodPremiumWait, + SlowmodeWait + ) as f: LOGGER.warning(str(f)) await sleep(f.value * 1.3) # type: ignore if ( diff --git a/bot/helper/telegram_helper/bot_commands.py b/bot/helper/telegram_helper/bot_commands.py index c26cb9ec6b9b..60fe3482c810 100644 --- a/bot/helper/telegram_helper/bot_commands.py +++ b/bot/helper/telegram_helper/bot_commands.py @@ -49,7 +49,7 @@ def __init__(self): self.DeleteCommand = f"del{CMD_SUFFIX}" self.CancelTaskCommand = [ f"abort{CMD_SUFFIX}", - f"a{CMD_SUFFIX}", + f"A{CMD_SUFFIX}", ] self.CancelAllCommand = f"cancelall{CMD_SUFFIX}" self.ForceStartCommand = [ diff --git a/bot/modules/authorize.py b/bot/modules/authorize.py index 00debc574b2b..83fa4a822910 100644 --- a/bot/modules/authorize.py +++ b/bot/modules/authorize.py @@ -147,7 +147,8 @@ async def removeSudo(client, message): MessageHandler( authorize, filters=command( - BotCommands.AuthorizeCommand + BotCommands.AuthorizeCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) @@ -155,7 +156,8 @@ async def removeSudo(client, message): MessageHandler( unauthorize, filters=command( - BotCommands.UnAuthorizeCommand + BotCommands.UnAuthorizeCommand, + case_sensitive=True ) & CustomFilters.sudo, ) ) @@ -163,7 +165,8 @@ async def removeSudo(client, message): MessageHandler( addSudo, filters=command( - BotCommands.AddSudoCommand + BotCommands.AddSudoCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) @@ -171,7 +174,8 @@ async def removeSudo(client, message): MessageHandler( removeSudo, filters=command( - BotCommands.RmSudoCommand + BotCommands.RmSudoCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) diff --git a/bot/modules/bot_settings.py b/bot/modules/bot_settings.py index 1e6da88f0e25..54610162edac 100644 --- a/bot/modules/bot_settings.py +++ b/bot/modules/bot_settings.py @@ -8,7 +8,6 @@ from asyncio import ( create_subprocess_exec, create_subprocess_shell, - sleep, gather, wait_for, ) @@ -19,16 +18,15 @@ environ, getcwd ) -from pyrogram.filters import ( - command, - regex, - create -) +from pyrogram import filters from pyrogram.handlers import ( MessageHandler, CallbackQueryHandler ) -from time import time +from pyrogram.errors import ( + ListenerTimeout, + ListenerStopped +) from bot import ( config_dict, @@ -61,7 +59,6 @@ set_commands, setInterval, sync_to_async, - new_thread, retry_function, ) from bot.helper.ext_utils.db_handler import DbManager @@ -84,7 +81,6 @@ START = 0 STATE = "view" -handler_dict = {} default_values = { "DOWNLOAD_DIR": "/usr/src/app/downloads/", "LEECH_SPLIT_SIZE": MAX_SPLIT_SIZE, @@ -524,8 +520,7 @@ async def update_buttons(message, key=None, edit_type=None): ) -async def edit_variable(client, message, pre_message, key): - handler_dict[message.chat.id] = False +async def edit_variable(message, pre_message, key): value = message.text if value.lower() == "true": value = True @@ -690,8 +685,7 @@ async def edit_variable(client, message, pre_message, key): await set_commands(client) -async def edit_aria(_, message, pre_message, key): - handler_dict[message.chat.id] = False +async def edit_aria(message, pre_message, key): value = message.text if key == "newkey": key, value = [ @@ -736,8 +730,7 @@ async def edit_aria(_, message, pre_message, key): ) -async def edit_qbit(_, message, pre_message, key): - handler_dict[message.chat.id] = False +async def edit_qbit(message, pre_message, key): value = message.text if value.lower() == "true": value = True @@ -764,8 +757,7 @@ async def edit_qbit(_, message, pre_message, key): ) -async def edit_nzb(_, message, pre_message, key): - handler_dict[message.chat.id] = False +async def edit_nzb(message, pre_message, key): value = message.text if value.isdigit(): value = int(value) @@ -789,8 +781,7 @@ async def edit_nzb(_, message, pre_message, key): await DbManager().update_nzb_config() -async def edit_nzb_server(_, message, pre_message, key, index=0): - handler_dict[message.chat.id] = False +async def edit_nzb_server(message, pre_message, key, index=0): value = message.text if ( value.startswith("{") and @@ -896,8 +887,7 @@ async def sync_jdownloader(): await DbManager().update_private_file("cfg.zip") -async def update_private_file(_, message, pre_message): - handler_dict[message.chat.id] = False +async def update_private_file(message, pre_message): if not message.media and (file_name := message.text): fn = file_name.rsplit( ".zip", @@ -1093,46 +1083,26 @@ async def update_private_file(_, message, pre_message): await remove("accounts.zip") -async def event_handler(client, query, pfunc, rfunc, document=False): - chat_id = query.message.chat.id - handler_dict[chat_id] = True - start_time = time() - - async def event_filter(_, __, event): - user = ( - event.from_user or - event.sender_chat - ) - return bool( - user.id == query.from_user.id - and event.chat.id == chat_id - and ( - event.text or - event.document and - document - ) - ) - - handler = client.add_handler( - MessageHandler( - pfunc, - filters=create(event_filter) - ), - group=-1 +async def event_handler(client, query, document=False): + event_filter = ( + filters.text | filters.document + if document + else filters.text + ) + return await client.listen( + chat_id=query.message.chat.id, + user_id=query.from_user.id, + filters=event_filter, + timeout=60, ) - while handler_dict[chat_id]: - await sleep(0.5) - if time() - start_time > 60: - handler_dict[chat_id] = False - await rfunc() - client.remove_handler(*handler) - -@new_thread async def edit_bot_settings(client, query): - data = query.data.split() message = query.message - handler_dict[message.chat.id] = False + await client.stop_listening( + chat_id=message.chat.id, + user_id=query.from_user.id + ) + data = query.data.split() if data[1] == "close": await query.answer() await deleteMessage(message.reply_to_message) @@ -1426,21 +1396,21 @@ async def edit_bot_settings(client, query): message, data[1] ) - pfunc = partial( - update_private_file, - pre_message=message - ) - rfunc = partial( - update_buttons, - message - ) - await event_handler( - client, - query, - pfunc, - rfunc, - True - ) + try: + event = await event_handler( + client, + query, + True + ) + except ListenerTimeout: + await update_buttons(message) + except ListenerStopped: + pass + else: + await update_private_file( + event, + message + ) elif ( data[1] == "botvar" and STATE == "edit" @@ -1451,22 +1421,24 @@ async def edit_bot_settings(client, query): data[2], data[1] ) - pfunc = partial( - edit_variable, - pre_message=message, - key=data[2] - ) - rfunc = partial( - update_buttons, - message, - "var" - ) - await event_handler( - client, - query, - pfunc, - rfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_buttons( + message, + "var" + ) + except ListenerStopped: + pass + else: + await edit_variable( + event, + message, + data[2] + ) elif ( data[1] == "botvar" and STATE == "view" @@ -1525,22 +1497,24 @@ async def edit_bot_settings(client, query): data[2], data[1] ) - pfunc = partial( - edit_aria, - pre_message=message, - key=data[2] - ) - rfunc = partial( - update_buttons, - message, - "aria" - ) - await event_handler( - client, - query, - pfunc, - rfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_buttons( + message, + "aria" + ) + except ListenerStopped: + pass + else: + await edit_aria( + event, + message, + data[2] + ) elif ( data[1] == "ariavar" and STATE == "view" @@ -1571,22 +1545,24 @@ async def edit_bot_settings(client, query): data[2], data[1] ) - pfunc = partial( - edit_qbit, - pre_message=message, - key=data[2] - ) - rfunc = partial( - update_buttons, - message, - "qbit" - ) - await event_handler( - client, - query, - pfunc, - rfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_buttons( + message, + "qbit" + ) + except ListenerStopped: + pass + else: + await edit_qbit( + event, + message, + data[2] + ) elif ( data[1] == "qbitvar" and STATE == "view" @@ -1617,22 +1593,24 @@ async def edit_bot_settings(client, query): data[2], data[1] ) - pfunc = partial( - edit_nzb, - pre_message=message, - key=data[2] - ) - rfunc = partial( - update_buttons, - message, - "nzb" - ) - await event_handler( - client, - query, - pfunc, - rfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_buttons( + message, + "nzb" + ) + except ListenerStopped: + pass + else: + await edit_nzb( + event, + message, + data[2] + ) elif ( data[1] == "nzbvar" and STATE == "view" @@ -1694,23 +1672,25 @@ async def edit_bot_settings(client, query): data[2], data[1] ) - pfunc = partial( - edit_nzb_server, - pre_message=message, - key=data[2], - index=index - ) - rfunc = partial( - update_buttons, - message, - data[1] - ) - await event_handler( - client, - query, - pfunc, - rfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_buttons( + message, + data[1] + ) + except ListenerStopped: + pass + else: + await edit_nzb_server( + event, + message, + data[2], + index + ) elif ( data[1].startswith("nzbsevar") and STATE == "view" @@ -1780,8 +1760,11 @@ async def edit_bot_settings(client, query): await deleteMessage(message) -async def bot_settings(_, message): - handler_dict[message.chat.id] = False +async def bot_settings(client, message): + await client.stop_listening( + chat_id=message.chat.id, + user_id=message.from_user.id + ) ( msg, button @@ -2789,15 +2772,16 @@ async def load_config(): bot.add_handler( # type: ignore MessageHandler( bot_settings, - filters=command( - BotCommands.BotSetCommand + filters=filters.command( + BotCommands.BotSetCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) bot.add_handler( # type: ignore CallbackQueryHandler( edit_bot_settings, - filters=regex( + filters=filters.regex( "^botset" ) & CustomFilters.sudo ) diff --git a/bot/modules/cancel_task.py b/bot/modules/cancel_task.py index c7fded52fda5..68bd6e189638 100644 --- a/bot/modules/cancel_task.py +++ b/bot/modules/cancel_task.py @@ -374,7 +374,8 @@ async def cancel_all_update(_, query): MessageHandler( cancel_task, filters=command( - BotCommands.CancelTaskCommand + BotCommands.CancelTaskCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) @@ -390,7 +391,8 @@ async def cancel_all_update(_, query): MessageHandler( cancell_all_buttons, filters=command( - BotCommands.CancelAllCommand + BotCommands.CancelAllCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/modules/clone.py b/bot/modules/clone.py index e6c21564a57b..b999cba573aa 100644 --- a/bot/modules/clone.py +++ b/bot/modules/clone.py @@ -464,7 +464,8 @@ async def clone(client, message): MessageHandler( clone, filters=command( - BotCommands.CloneCommand + BotCommands.CloneCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) diff --git a/bot/modules/exec.py b/bot/modules/exec.py index 0db01e2f4d60..942b6b51273a 100644 --- a/bot/modules/exec.py +++ b/bot/modules/exec.py @@ -175,7 +175,8 @@ async def clear(_, message): MessageHandler( aioexecute, filters=command( - BotCommands.AExecCommand + BotCommands.AExecCommand, + case_sensitive=True ) & CustomFilters.owner ) ) @@ -183,7 +184,8 @@ async def clear(_, message): MessageHandler( execute, filters=command( - BotCommands.ExecCommand + BotCommands.ExecCommand, + case_sensitive=True ) & CustomFilters.owner ) ) @@ -191,7 +193,8 @@ async def clear(_, message): MessageHandler( clear, filters=command( - BotCommands.ClearLocalsCommand + BotCommands.ClearLocalsCommand, + case_sensitive=True ) & CustomFilters.owner ) ) diff --git a/bot/modules/file_selector.py b/bot/modules/file_selector.py index a481735ac2d7..1ccc1ce86145 100644 --- a/bot/modules/file_selector.py +++ b/bot/modules/file_selector.py @@ -302,7 +302,8 @@ async def get_confirm(_, query): MessageHandler( select, filters=command( - BotCommands.SelectCommand + BotCommands.SelectCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) diff --git a/bot/modules/force_start.py b/bot/modules/force_start.py index 3d1fe17e9dde..59d98a93398a 100644 --- a/bot/modules/force_start.py +++ b/bot/modules/force_start.py @@ -140,7 +140,8 @@ async def remove_from_queue(_, message): MessageHandler( remove_from_queue, filters=command( - BotCommands.ForceStartCommand + BotCommands.ForceStartCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/modules/gd_count.py b/bot/modules/gd_count.py index a7432c86bce7..1c933f1c8ed0 100644 --- a/bot/modules/gd_count.py +++ b/bot/modules/gd_count.py @@ -92,7 +92,8 @@ async def countNode(_, message): MessageHandler( countNode, filters=command( - BotCommands.CountCommand + BotCommands.CountCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) diff --git a/bot/modules/gd_delete.py b/bot/modules/gd_delete.py index d6021a1dddaf..2a08af5601a4 100644 --- a/bot/modules/gd_delete.py +++ b/bot/modules/gd_delete.py @@ -54,7 +54,8 @@ async def deletefile(_, message): MessageHandler( deletefile, filters=command( - BotCommands.DeleteCommand + BotCommands.DeleteCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/modules/gd_search.py b/bot/modules/gd_search.py index 0d19761e9af0..52f57c4f9ba6 100644 --- a/bot/modules/gd_search.py +++ b/bot/modules/gd_search.py @@ -239,7 +239,8 @@ async def gdrive_search(_, message): MessageHandler( gdrive_search, filters=command( - BotCommands.ListCommand + BotCommands.ListCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/modules/leech_del.py b/bot/modules/leech_del.py index 29736174b621..7f39157abd3c 100644 --- a/bot/modules/leech_del.py +++ b/bot/modules/leech_del.py @@ -108,7 +108,8 @@ async def deleting(client, chat_id, message_id, message): MessageHandler( delete_leech, filters=command( - f"leech{BotCommands.DeleteCommand}" + f"leech{BotCommands.DeleteCommand}", + case_sensitive=True ) & CustomFilters.sudo ) ) diff --git a/bot/modules/mirror_leech.py b/bot/modules/mirror_leech.py index 1781f27685af..e1368ca3d3a9 100644 --- a/bot/modules/mirror_leech.py +++ b/bot/modules/mirror_leech.py @@ -603,7 +603,8 @@ async def nzb_leech(client, message): MessageHandler( mirror, filters=command( - BotCommands.MirrorCommand + BotCommands.MirrorCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) @@ -611,7 +612,8 @@ async def nzb_leech(client, message): MessageHandler( qb_mirror, filters=command( - BotCommands.QbMirrorCommand + BotCommands.QbMirrorCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) @@ -619,7 +621,8 @@ async def nzb_leech(client, message): MessageHandler( jd_mirror, filters=command( - BotCommands.JdMirrorCommand + BotCommands.JdMirrorCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) @@ -627,7 +630,8 @@ async def nzb_leech(client, message): MessageHandler( nzb_mirror, filters=command( - BotCommands.NzbMirrorCommand + BotCommands.NzbMirrorCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) @@ -635,7 +639,8 @@ async def nzb_leech(client, message): MessageHandler( leech, filters=command( - BotCommands.LeechCommand + BotCommands.LeechCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) @@ -643,7 +648,8 @@ async def nzb_leech(client, message): MessageHandler( qb_leech, filters=command( - BotCommands.QbLeechCommand + BotCommands.QbLeechCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) @@ -651,7 +657,8 @@ async def nzb_leech(client, message): MessageHandler( jd_leech, filters=command( - BotCommands.JdLeechCommand + BotCommands.JdLeechCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) @@ -659,7 +666,8 @@ async def nzb_leech(client, message): MessageHandler( nzb_leech, filters=command( - BotCommands.NzbLeechCommand + BotCommands.NzbLeechCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/modules/rmdb.py b/bot/modules/rmdb.py index ab5bd568fbf2..1ebd084a9ca2 100644 --- a/bot/modules/rmdb.py +++ b/bot/modules/rmdb.py @@ -122,7 +122,8 @@ async def rmdbNode(_, message): MessageHandler( rmdbNode, filters=command( - BotCommands.RmdbCommand + BotCommands.RmdbCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) @@ -130,7 +131,8 @@ async def rmdbNode(_, message): MessageHandler( rmAllTokens, filters=command( - BotCommands.RmalltokensCommand + BotCommands.RmalltokensCommand, + case_sensitive=True ) & CustomFilters.sudo ) ) diff --git a/bot/modules/rss.py b/bot/modules/rss.py index 9695cdb23a53..f640acc20658 100644 --- a/bot/modules/rss.py +++ b/bot/modules/rss.py @@ -1,20 +1,25 @@ from httpx import AsyncClient from apscheduler.triggers.interval import IntervalTrigger -from asyncio import Lock, sleep +from asyncio import ( + Lock, + sleep, + gather +) from datetime import datetime, timedelta from feedparser import parse as feedparse -from functools import partial from io import BytesIO from pyrogram.filters import ( command, - regex, - create + regex ) from pyrogram.handlers import ( MessageHandler, CallbackQueryHandler ) -from time import time +from pyrogram.errors import ( + ListenerTimeout, + ListenerStopped +) from bot import ( scheduler, @@ -24,10 +29,7 @@ config_dict, bot ) -from bot.helper.ext_utils.bot_utils import ( - new_thread, - arg_parser -) +from bot.helper.ext_utils.bot_utils import arg_parser from bot.helper.ext_utils.db_handler import DbManager from bot.helper.ext_utils.exceptions import RssShutdownException from bot.helper.ext_utils.help_messages import RSS_HELP_MESSAGE @@ -43,7 +45,6 @@ ) rss_dict_lock = Lock() -handler_dict = {} async def rssMenu(event): @@ -132,8 +133,15 @@ async def updateRssMenu(query): ) -async def getRssMenu(_, message): - msg, button = await rssMenu(message) +async def getRssMenu(client, message): + await client.stop_listening( + chat_id=message.chat.id, + user_id=message.from_user.id + ) + ( + msg, + button + ) = await rssMenu(message) await sendMessage( message, msg, @@ -141,9 +149,8 @@ async def getRssMenu(_, message): ) -async def rssSub(_, message, pre_event): +async def rssSub(message): user_id = message.from_user.id - handler_dict[user_id] = False if username := message.from_user.username: tag = f"@{username}" else: @@ -301,7 +308,6 @@ async def rssSub(_, message, pre_event): elif is_sudo and not scheduler.running: addJob() scheduler.start() - await updateRssMenu(pre_event) async def getUserId(title): @@ -320,9 +326,8 @@ async def getUserId(title): ) -async def rssUpdate(_, message, pre_event, state): +async def rssUpdate(message, state): user_id = message.from_user.id - handler_dict[user_id] = False titles = message.text.split() is_sudo = await CustomFilters.sudo( "", # type: ignore @@ -389,7 +394,6 @@ async def rssUpdate(_, message, pre_event, state): rss_dict.get(user_id) ): await DbManager().rss_update(user_id) - await updateRssMenu(pre_event) async def rssList(query, start, all_users=False): @@ -468,16 +472,14 @@ async def rssList(query, start, all_users=False): ) -async def rssGet(_, message, pre_event): +async def rssGet(message): user_id = message.from_user.id - handler_dict[user_id] = False args = message.text.split() if len(args) < 2: await sendMessage( message, f"{args}. Wrong Input format. You should add number of the items you want to get. Read help message before adding new subcription!", ) - await updateRssMenu(pre_event) return try: title = args[0] @@ -537,12 +539,10 @@ async def rssGet(_, message, pre_event): message, f"Enter a valid value!. {e}" ) - await updateRssMenu(pre_event) -async def rssEdit(_, message, pre_event): +async def rssEdit(message): user_id = message.from_user.id - handler_dict[user_id] = False items = message.text.split("\n") updated = False for item in items: @@ -604,11 +604,9 @@ async def rssEdit(_, message, pre_event): rss_dict[user_id][title]["exf"] = exf_lists if DATABASE_URL and updated: await DbManager().rss_update(user_id) - await updateRssMenu(pre_event) -async def rssDelete(_, message, pre_event): - handler_dict[message.from_user.id] = False +async def rssDelete(message): users = message.text.split() for user in users: user = int(user) @@ -616,41 +614,16 @@ async def rssDelete(_, message, pre_event): del rss_dict[user] if DATABASE_URL: await DbManager().rss_delete(user) - await updateRssMenu(pre_event) -async def event_handler(client, query, pfunc): - user_id = query.from_user.id - handler_dict[user_id] = True - start_time = time() - - async def event_filter(_, __, event): - user = ( - event.from_user or - event.sender_chat - ) - return bool( - user.id == user_id - and event.chat.id == query.message.chat.id - and event.text - ) - - handler = client.add_handler( - MessageHandler( - pfunc, - create(event_filter) - ), - group=-1 +async def event_handler(client, query): + return await client.listen( + chat_id=query.message.chat.id, + user_id=query.from_user.id, + timeout=60 ) - while handler_dict[user_id]: - await sleep(0.5) - if time() - start_time > 60: - handler_dict[user_id] = False - await updateRssMenu(query) - client.remove_handler(*handler) -@new_thread async def rssListener(client, query): user_id = query.from_user.id message = query.message @@ -668,16 +641,13 @@ async def rssListener(client, query): ) elif data[1] == "close": await query.answer() - handler_dict[user_id] = False await deleteMessage(message.reply_to_message) await deleteMessage(message) elif data[1] == "back": await query.answer() - handler_dict[user_id] = False await updateRssMenu(query) elif data[1] == "sub": await query.answer() - handler_dict[user_id] = False buttons = ButtonMaker() buttons.ibutton( "Back", @@ -693,17 +663,21 @@ async def rssListener(client, query): RSS_HELP_MESSAGE, button ) - pfunc = partial( - rssSub, - pre_event=query - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await updateRssMenu(query) + except ListenerStopped: + pass + else: + await gather( + rssSub(event), + updateRssMenu(query) + ) elif data[1] == "list": - handler_dict[user_id] = False if len(rss_dict.get(int(data[2]), {})) == 0: await query.answer( text="No subscriptions!", @@ -717,7 +691,6 @@ async def rssListener(client, query): start ) elif data[1] == "get": - handler_dict[user_id] = False if len(rss_dict.get(int(data[2]), {})) == 0: await query.answer( text="No subscriptions!", @@ -740,21 +713,25 @@ async def rssListener(client, query): "Send one title with value separated by space get last X items.\nTitle Value\nTimeout: 60 sec.", button, ) - pfunc = partial( - rssGet, - pre_event=query - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await updateRssMenu(query) + except ListenerStopped: + pass + else: + await gather( + rssGet(event), + updateRssMenu(query) + ) elif data[1] in [ "unsubscribe", "pause", "resume" ]: - handler_dict[user_id] = False if len(rss_dict.get(int(data[2]), {})) == 0: await query.answer( text="No subscriptions!", @@ -792,18 +769,24 @@ async def rssListener(client, query): f"Send one or more rss titles separated by space to {data[1]}.\nTimeout: 60 sec.", button, ) - pfunc = partial( - rssUpdate, - pre_event=query, - state=data[1] - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await updateRssMenu(query) + except ListenerStopped: + pass + else: + await gather( + rssUpdate( + event, + data[1] + ), + updateRssMenu(query) + ) elif data[1] == "edit": - handler_dict[user_id] = False if len(rss_dict.get(int(data[2]), {})) == 0: await query.answer( text="No subscriptions!", @@ -834,17 +817,21 @@ async def rssListener(client, query): msg, button ) - pfunc = partial( - rssEdit, - pre_event=query - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await updateRssMenu(query) + except ListenerStopped: + pass + else: + await gather( + rssEdit(event), + updateRssMenu(query) + ) elif data[1].startswith("uall"): - handler_dict[user_id] = False if len(rss_dict.get(int(data[2]), {})) == 0: await query.answer( text="No subscriptions!", @@ -931,15 +918,20 @@ async def rssListener(client, query): msg, button ) - pfunc = partial( - rssDelete, - pre_event=query - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await updateRssMenu(query) + except ListenerStopped: + pass + else: + await gather( + rssDelete(event), + updateRssMenu(query) + ) elif data[1] == "listall": if not rss_dict: await query.answer( @@ -1132,7 +1124,8 @@ def addJob(): MessageHandler( getRssMenu, filters=command( - BotCommands.RssCommand + BotCommands.RssCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) diff --git a/bot/modules/shell.py b/bot/modules/shell.py index 23aaae9b0ebd..a8cee68ddbec 100644 --- a/bot/modules/shell.py +++ b/bot/modules/shell.py @@ -66,7 +66,8 @@ async def shell(_, message): MessageHandler( shell, filters=command( - BotCommands.ShellCommand + BotCommands.ShellCommand, + case_sensitive=True ) & CustomFilters.owner ) ) @@ -74,7 +75,8 @@ async def shell(_, message): EditedMessageHandler( shell, filters=command( - BotCommands.ShellCommand + BotCommands.ShellCommand, + case_sensitive=True ) & CustomFilters.owner ) ) diff --git a/bot/modules/status.py b/bot/modules/status.py index 2a4aa98c049c..a9276a959c84 100644 --- a/bot/modules/status.py +++ b/bot/modules/status.py @@ -583,11 +583,22 @@ async def send_close_signal(_, query): MessageHandler( stats, filters=command( - BotCommands.StatsCommand + BotCommands.StatsCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) +bot.add_handler( # type: ignore + MessageHandler( + mirror_status, + filters=command( + BotCommands.StatusCommand, + case_sensitive=True + ) & CustomFilters.authorized, + ) +) + bot.add_handler( # type: ignore CallbackQueryHandler( send_close_signal, @@ -633,15 +644,6 @@ async def send_close_signal(_, query): ) ) -bot.add_handler( # type: ignore - MessageHandler( - mirror_status, - filters=command( - BotCommands.StatusCommand - ) & CustomFilters.authorized, - ) -) - bot.add_handler( # type: ignore CallbackQueryHandler( status_pages, diff --git a/bot/modules/torrent_search.py b/bot/modules/torrent_search.py index 971bdeb1a144..84ddb12d5276 100644 --- a/bot/modules/torrent_search.py +++ b/bot/modules/torrent_search.py @@ -518,7 +518,8 @@ async def torrentSearchUpdate(_, query): MessageHandler( torrentSearch, filters=command( - BotCommands.SearchCommand + BotCommands.SearchCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/bot/modules/users_settings.py b/bot/modules/users_settings.py index 9fbc023780df..099d86a328c4 100644 --- a/bot/modules/users_settings.py +++ b/bot/modules/users_settings.py @@ -1,26 +1,24 @@ +from asyncio import gather from aiofiles.os import ( remove, path as aiopath, makedirs ) -from asyncio import sleep -from functools import partial from html import escape from io import BytesIO from math import ceil from os import getcwd, path as os_path -from pyrogram.filters import ( - command, - regex, - create -) +from pyrogram import filters from pyrogram.handlers import ( MessageHandler, CallbackQueryHandler ) from pyrogram.types import InputMediaPhoto from re import search as re_search -from time import time +from pyrogram.errors import ( + ListenerTimeout, + ListenerStopped +) from bot import ( bot, @@ -32,10 +30,7 @@ MAX_SPLIT_SIZE, GLOBAL_EXTENSION_FILTER, ) -from bot.helper.ext_utils.bot_utils import ( - update_user_ldata, - new_thread, -) +from bot.helper.ext_utils.bot_utils import update_user_ldata from bot.helper.ext_utils.db_handler import DbManager from bot.helper.ext_utils.media_utils import createThumb from bot.helper.ext_utils.status_utils import get_readable_file_size @@ -52,8 +47,6 @@ ) from bot.helper.z_utils import def_media -handler_dict = {} - async def get_user_settings(from_user): user_id = from_user.id @@ -400,13 +393,15 @@ async def update_user_settings(query): ) -@new_thread -async def user_settings(_, message): +async def user_settings(client, message): + await client.stop_listening( + chat_id=message.chat.id, + user_id=message.from_user.id + ) from_user = message.from_user if not from_user: from_user = await anno_checker(message) user_id = from_user.id - handler_dict[user_id] = False msg, button = await get_user_settings(from_user) media = ( f"Thumbnails/{user_id}.jpg" @@ -424,9 +419,8 @@ async def user_settings(_, message): ) -async def set_thumb(_, message, pre_event): +async def set_thumb(message): user_id = message.from_user.id - handler_dict[user_id] = False des_dir = await createThumb( message, user_id @@ -437,7 +431,6 @@ async def set_thumb(_, message, pre_event): des_dir ) await deleteMessage(message) - await update_user_settings(pre_event) if DATABASE_URL: await DbManager().update_user_doc( user_id, @@ -446,9 +439,8 @@ async def set_thumb(_, message, pre_event): ) -async def add_rclone(_, message, pre_event): +async def add_rclone(message): user_id = message.from_user.id - handler_dict[user_id] = False rpath = f"{getcwd()}/rclone/" await makedirs(rpath, exist_ok=True) des_dir = f"{rpath}{user_id}.conf" @@ -459,7 +451,6 @@ async def add_rclone(_, message, pre_event): f"rclone/{user_id}.conf" ) await deleteMessage(message) - await update_user_settings(pre_event) if DATABASE_URL: await DbManager().update_user_doc( user_id, @@ -468,9 +459,8 @@ async def add_rclone(_, message, pre_event): ) -async def add_token_pickle(_, message, pre_event): +async def add_token_pickle(message): user_id = message.from_user.id - handler_dict[user_id] = False tpath = f"{getcwd()}/tokens/" await makedirs(tpath, exist_ok=True) des_dir = f"{tpath}{user_id}.pickle" @@ -481,7 +471,6 @@ async def add_token_pickle(_, message, pre_event): f"tokens/{user_id}.pickle" ) await deleteMessage(message) - await update_user_settings(pre_event) if DATABASE_URL: await DbManager().update_user_doc( user_id, @@ -490,9 +479,8 @@ async def add_token_pickle(_, message, pre_event): ) -async def delete_path(_, message, pre_event): +async def delete_path(message): user_id = message.from_user.id - handler_dict[user_id] = False user_dict = user_data.get(user_id, {}) names = message.text.split() for name in names: @@ -505,7 +493,6 @@ async def delete_path(_, message, pre_event): new_value ) await deleteMessage(message) - await update_user_settings(pre_event) if DATABASE_URL: await DbManager().update_user_doc( user_id, @@ -514,9 +501,8 @@ async def delete_path(_, message, pre_event): ) -async def set_option(_, message, pre_event, option): +async def set_option(message, option): user_id = message.from_user.id - handler_dict[user_id] = False value = message.text if option == "split_size": if re_search(r"[a-zA-Z]", value): @@ -528,7 +514,6 @@ async def set_option(_, message, pre_event, option): message, smsg ) - await update_user_settings(pre_event) return value = min( ceil(float(value) * 1024 ** 3), @@ -559,7 +544,6 @@ async def set_option(_, message, pre_event, option): message, smsg ) - await update_user_settings(pre_event) return ( name, @@ -573,61 +557,42 @@ async def set_option(_, message, pre_event, option): value ) await deleteMessage(message) - await update_user_settings(pre_event) if DATABASE_URL: await DbManager().update_user_data(user_id) -async def event_handler(client, query, pfunc, photo=False, document=False): - user_id = query.from_user.id - handler_dict[user_id] = True - start_time = time() - - async def event_filter(_, __, event): - if photo: - mtype = event.photo - elif document: - mtype = event.document - else: - mtype = event.text - user = ( - event.from_user or - event.sender_chat - ) - return bool( - user.id == user_id - and event.chat.id == query.message.chat.id - and mtype - ) - - handler = client.add_handler( - MessageHandler( - pfunc, - filters=create(event_filter) - ), - group=-1 +async def event_handler(client, query, photo=False, document=False): + if photo: + event_filter = filters.photo + elif document: + event_filter = filters.document + else: + event_filter = filters.text + return await client.listen( + chat_id=query.message.chat.id, + user_id=query.from_user.id, + filters=event_filter, + timeout=60, ) - while handler_dict[user_id]: - await sleep(0.5) - if time() - start_time > 60: - handler_dict[user_id] = False - await update_user_settings(query) - client.remove_handler(*handler) - -@new_thread async def edit_user_settings(client, query): from_user = query.from_user user_id = from_user.id name = from_user.mention message = query.message data = query.data.split() - handler_dict[user_id] = False thumb_path = f"Thumbnails/{user_id}.jpg" rclone_conf = f"rclone/{user_id}.conf" token_pickle = f"tokens/{user_id}.pickle" - user_dict = user_data.get(user_id, {}) + user_dict = user_data.get( + user_id, + {} + ) + await client.stop_listening( + chat_id=message.chat.id, + user_id=query.from_user.id + ) if user_id != int(data[1]): await query.answer( "Not Yours!", @@ -1090,16 +1055,21 @@ async def edit_user_settings(client, query): "Send a photo to save it as custom thumbnail. Timeout: 60 sec", buttons.build_menu(2), ) - pfunc = partial( - set_thumb, - pre_event=query - ) - await event_handler( - client, - query, - pfunc, - True - ) + try: + event = await event_handler( + client, + query, + True + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_thumb(event), + update_user_settings(query) + ) elif data[2] == "yto": await query.answer() buttons = ButtonMaker() @@ -1137,16 +1107,23 @@ async def edit_user_settings(client, query): rmsg, buttons.build_menu(2) ) - pfunc = partial( - set_option, - pre_event=query, - option="yt_opt" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "yt_opt" + ), + update_user_settings(query) + ) elif data[2] == "lss": await query.answer() buttons = ButtonMaker() @@ -1175,16 +1152,23 @@ async def edit_user_settings(client, query): sp_msg, buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="split_size" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "split_size" + ), + update_user_settings(query) + ) elif data[2] == "rcc": await query.answer() buttons = ButtonMaker() @@ -1208,16 +1192,21 @@ async def edit_user_settings(client, query): "Send rclone.conf. Timeout: 60 sec", buttons.build_menu(2) ) - pfunc = partial( - add_rclone, - pre_event=query - ) - await event_handler( - client, - query, - pfunc, - document=True - ) + try: + event = await event_handler( + client, + query, + document=True + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + add_rclone(event), + update_user_settings(query) + ) elif data[2] == "rcp": await query.answer() buttons = ButtonMaker() @@ -1245,16 +1234,23 @@ async def edit_user_settings(client, query): rmsg, buttons.build_menu(2) ) - pfunc = partial( - set_option, - pre_event=query, - option="rclone_path" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "rclone_path" + ), + update_user_settings(query) + ) elif data[2] == "token": await query.answer() buttons = ButtonMaker() @@ -1278,16 +1274,21 @@ async def edit_user_settings(client, query): "Send token.pickle.\n\nTimeout: 60 sec", buttons.build_menu(2) ) - pfunc = partial( - add_token_pickle, - pre_event=query - ) - await event_handler( - client, - query, - pfunc, - document=True - ) + try: + event = await event_handler( + client, + query, + document=True + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + add_token_pickle(event), + update_user_settings(query) + ) elif data[2] == "gdid": await query.answer() buttons = ButtonMaker() @@ -1315,16 +1316,23 @@ async def edit_user_settings(client, query): rmsg, buttons.build_menu(2) ) - pfunc = partial( - set_option, - pre_event=query, - option="gdrive_id" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "gdrive_id" + ), + update_user_settings(query) + ) elif data[2] == "index": await query.answer() buttons = ButtonMaker() @@ -1352,16 +1360,23 @@ async def edit_user_settings(client, query): rmsg, buttons.build_menu(2) ) - pfunc = partial( - set_option, - pre_event=query, - option="index_url" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "index_url" + ), + update_user_settings(query) + ) elif data[2] == "leech_prefix": await query.answer() buttons = ButtonMaker() @@ -1392,16 +1407,23 @@ async def edit_user_settings(client, query): "Send Leech Filename Prefix.\nYou can add HTML tags.\n\nTimeout: 60 sec", buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="lprefix" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "lprefix" + ), + update_user_settings(query) + ) elif data[2] == "leech_suffix": await query.answer() buttons = ButtonMaker() @@ -1432,16 +1454,23 @@ async def edit_user_settings(client, query): "Send Leech Filename Suffix.\nYou can add HTML tags.\n\nTimeout: 60 sec", buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="lsuffix" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "lsuffix" + ), + update_user_settings(query) + ) elif data[2] == "leech_cap_font": await query.answer() buttons = ButtonMaker() @@ -1487,16 +1516,23 @@ async def edit_user_settings(client, query): msg, buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="lcapfont" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "lcapfont" + ), + update_user_settings(query) + ) elif data[2] == "ldest": await query.answer() buttons = ButtonMaker() @@ -1527,16 +1563,23 @@ async def edit_user_settings(client, query): "Send leech destination\nID or USERNAME or PM.\n\nTimeout: 60 sec", buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="leech_dest" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "leech_dest" + ), + update_user_settings(query) + ) elif data[2] == "ex_ex": await query.answer() buttons = ButtonMaker() @@ -1570,16 +1613,23 @@ async def edit_user_settings(client, query): ex_msg, buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="excluded_extensions" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "excluded_extensions" + ), + update_user_settings(query) + ) elif data[2] == "name_substitute": await query.answer() buttons = ButtonMaker() @@ -1624,16 +1674,23 @@ async def edit_user_settings(client, query): emsg, buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="name_sub" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "name_sub" + ), + update_user_settings(query) + ) elif data[2] in [ "gd", "rc" @@ -1708,16 +1765,23 @@ async def edit_user_settings(client, query): ), buttons.build_menu(2), ) - pfunc = partial( - set_option, - pre_event=query, - option="upload_paths" - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + set_option( + event, + "upload_paths" + ), + update_user_settings(query) + ) elif data[2] == "rm_path": await query.answer() buttons = ButtonMaker() @@ -1736,15 +1800,20 @@ async def edit_user_settings(client, query): "Send paths names which you want to delete, separated by space.\n\nTimeout: 60 sec", buttons.build_menu(2), ) - pfunc = partial( - delete_path, - pre_event=query - ) - await event_handler( - client, - query, - pfunc - ) + try: + event = await event_handler( + client, + query + ) + except ListenerTimeout: + await update_user_settings(query) + except ListenerStopped: + pass + else: + await gather( + delete_path(event), + update_user_settings(query) + ) elif data[2] == "show_path": await query.answer() buttons = ButtonMaker() @@ -1843,22 +1912,24 @@ async def send_users_settings(_, message): bot.add_handler( # type: ignore MessageHandler( send_users_settings, - filters=command( - BotCommands.UsersCommand + filters=filters.command( + BotCommands.UsersCommand, + case_sensitive=True ) & CustomFilters.sudo, ) ) bot.add_handler( # type: ignore MessageHandler( user_settings, - filters=command( - BotCommands.UserSetCommand + filters=filters.command( + BotCommands.UserSetCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) bot.add_handler( # type: ignore CallbackQueryHandler( edit_user_settings, - filters=regex("^userset") + filters=filters.regex("^userset") ) ) diff --git a/bot/modules/ytdlp.py b/bot/modules/ytdlp.py index 1f3ec6a92a57..f4c6d6aca469 100644 --- a/bot/modules/ytdlp.py +++ b/bot/modules/ytdlp.py @@ -350,7 +350,8 @@ async def ytdlleech(client, message): MessageHandler( ytdl, filters=command( - BotCommands.YtdlCommand + BotCommands.YtdlCommand, + case_sensitive=True ) & CustomFilters.authorized ) ) @@ -359,7 +360,8 @@ async def ytdlleech(client, message): MessageHandler( ytdlleech, filters=command( - BotCommands.YtdlLeechCommand + BotCommands.YtdlLeechCommand, + case_sensitive=True ) & CustomFilters.authorized, ) ) diff --git a/update.py b/update.py index d01b14ef48f3..1e3c13c282f0 100644 --- a/update.py +++ b/update.py @@ -16,6 +16,7 @@ from pymongo.mongo_client import MongoClient from pymongo.server_api import ServerApi from subprocess import run as srun +from sys import exit getLogger("pymongo").setLevel(ERROR)