From 24e8d385d9f12237d42151e2e0a94bb0ff9baa43 Mon Sep 17 00:00:00 2001 From: Levi <57452819+l3v11@users.noreply.github.com> Date: Tue, 20 Sep 2022 21:47:34 +0600 Subject: [PATCH] Rename AUTHORIZED_CHATS env variable to AUTHORIZED_USERS --- bot/__init__.py | 174 ++++++------------- bot/__main__.py | 8 +- bot/helper/download_utils/ddl_generator.py | 7 +- bot/helper/drive_utils/gdriveTools.py | 19 +- bot/helper/ext_utils/database.py | 10 +- bot/helper/telegram_helper/bot_commands.py | 5 +- bot/helper/telegram_helper/button_builder.py | 22 ++- bot/helper/telegram_helper/filters.py | 16 +- bot/helper/telegram_helper/message_utils.py | 26 +-- bot/modules/archive.py | 6 +- bot/modules/auth.py | 24 +-- bot/modules/cancel.py | 2 +- bot/modules/clone.py | 2 +- bot/modules/count.py | 2 +- bot/modules/list.py | 2 +- bot/modules/permission.py | 2 +- bot/modules/status.py | 14 +- config_sample.env | 4 +- 18 files changed, 145 insertions(+), 200 deletions(-) diff --git a/bot/__init__.py b/bot/__init__.py index bbf12f8b..a7a176a9 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -28,24 +28,17 @@ LOGGER = logging.getLogger(__name__) -def get_config(name: str): - return os.environ[name] - -try: - CONFIG_ENV_URL = get_config('CONFIG_ENV_URL') - if len(CONFIG_ENV_URL) == 0: - raise KeyError +CONFIG_ENV_URL = os.environ.get('CONFIG_ENV_URL', '') +if len(CONFIG_ENV_URL) != 0: try: res = requests.get(CONFIG_ENV_URL) if res.status_code == 200: with open('config.env', 'wb+') as f: f.write(res.content) else: - LOGGER.error(f"Failed to load config.env file [{res.status_code}]") - except Exception as e: - LOGGER.error(f"CONFIG_ENV_URL: {e}") -except: - pass + LOGGER.error(f"Failed to load the config.env file [{res.status_code}]") + except Exception as err: + LOGGER.error(f"CONFIG_ENV_URL: {err}") load_dotenv('config.env', override=True) @@ -55,7 +48,8 @@ def get_config(name: str): INDEX_URLS = [] TELEGRAPH = [] -AUTHORIZED_CHATS = set() +def get_config(name: str): + return os.environ[name] download_dict_lock = Lock() status_reply_dict_lock = Lock() @@ -92,153 +86,97 @@ def get_config(name: str): LOGGER.error("DOWNLOAD_DIR env variable is missing") exit(1) -try: - users = get_config('AUTHORIZED_CHATS') - users = users.split() - for user in users: - AUTHORIZED_CHATS.add(int(user.strip())) -except: - pass +users = os.environ.get('AUTHORIZED_USERS', '') +if len(users) != 0: + AUTHORIZED_USERS = {int(user.strip()) for user in users.split()} +else: + AUTHORIZED_USERS = set() -try: - DATABASE_URL = get_config('DATABASE_URL') - if len(DATABASE_URL) == 0: - raise KeyError -except: +DATABASE_URL = os.environ.get('DATABASE_URL', '') +if len(DATABASE_URL) == 0: DATABASE_URL = None -try: - IS_TEAM_DRIVE = get_config('IS_TEAM_DRIVE') - IS_TEAM_DRIVE = IS_TEAM_DRIVE.lower() == 'true' -except: - IS_TEAM_DRIVE = False +IS_TEAM_DRIVE = os.environ.get('IS_TEAM_DRIVE', '') +IS_TEAM_DRIVE = IS_TEAM_DRIVE.lower() == 'true' -try: - USE_SERVICE_ACCOUNTS = get_config('USE_SERVICE_ACCOUNTS') - USE_SERVICE_ACCOUNTS = USE_SERVICE_ACCOUNTS.lower() == 'true' -except: - USE_SERVICE_ACCOUNTS = False +USE_SERVICE_ACCOUNTS = os.environ.get('USE_SERVICE_ACCOUNTS', '') +USE_SERVICE_ACCOUNTS = USE_SERVICE_ACCOUNTS.lower() == 'true' -try: - STATUS_UPDATE_INTERVAL = get_config('STATUS_UPDATE_INTERVAL') - if len(STATUS_UPDATE_INTERVAL) == 0: - raise KeyError - STATUS_UPDATE_INTERVAL = int(STATUS_UPDATE_INTERVAL) -except: - STATUS_UPDATE_INTERVAL = 10 +STATUS_UPDATE_INTERVAL = os.environ.get('STATUS_UPDATE_INTERVAL', '') +STATUS_UPDATE_INTERVAL = 10 if len(STATUS_UPDATE_INTERVAL) == 0 else int(STATUS_UPDATE_INTERVAL) -try: - TELEGRAPH_ACCS = get_config('TELEGRAPH_ACCS') - if len(TELEGRAPH_ACCS) == 0: - raise KeyError - TELEGRAPH_ACCS = int(TELEGRAPH_ACCS) -except: - TELEGRAPH_ACCS = 1 +TELEGRAPH_ACCS = os.environ.get('TELEGRAPH_ACCS', '') +TELEGRAPH_ACCS = 1 if len(TELEGRAPH_ACCS) == 0 else int(TELEGRAPH_ACCS) -try: - INDEX_URL = get_config('INDEX_URL').rstrip("/") - if len(INDEX_URL) == 0: - raise KeyError -except: +INDEX_URL = os.environ.get('INDEX_URL', '').rstrip("/") +if len(INDEX_URL) == 0: INDEX_URL = None -try: - CLONE_LIMIT = get_config('CLONE_LIMIT') - if len(CLONE_LIMIT) == 0: - raise KeyError - CLONE_LIMIT = float(CLONE_LIMIT) -except: - CLONE_LIMIT = None +ARCHIVE_LIMIT = os.environ.get('ARCHIVE_LIMIT', '') +ARCHIVE_LIMIT = None if len(ARCHIVE_LIMIT) == 0 else float(ARCHIVE_LIMIT) -try: - ARCHIVE_LIMIT = get_config('ARCHIVE_LIMIT') - if len(ARCHIVE_LIMIT) == 0: - raise KeyError - ARCHIVE_LIMIT = float(ARCHIVE_LIMIT) -except: - ARCHIVE_LIMIT = None +CLONE_LIMIT = os.environ.get('CLONE_LIMIT', '') +CLONE_LIMIT = None if len(CLONE_LIMIT) == 0 else float(CLONE_LIMIT) -try: - TOKEN_JSON_URL = get_config('TOKEN_JSON_URL') - if len(TOKEN_JSON_URL) == 0: - raise KeyError +TOKEN_JSON_URL = os.environ.get('TOKEN_JSON_URL', '') +if len(TOKEN_JSON_URL) != 0: try: res = requests.get(TOKEN_JSON_URL) if res.status_code == 200: with open('token.json', 'wb+') as f: f.write(res.content) else: - LOGGER.error(f"Failed to load token.json file [{res.status_code}]") - except Exception as e: - LOGGER.error(f"TOKEN_JSON_URL: {e}") -except: - pass + LOGGER.error(f"Failed to load the token.json file [{res.status_code}]") + except Exception as err: + LOGGER.error(f"TOKEN_JSON_URL: {err}") -try: - ACCOUNTS_ZIP_URL = get_config('ACCOUNTS_ZIP_URL') - if len(ACCOUNTS_ZIP_URL) == 0: - raise KeyError +ACCOUNTS_ZIP_URL = os.environ.get('ACCOUNTS_ZIP_URL', '') +if len(ACCOUNTS_ZIP_URL) != 0: try: res = requests.get(ACCOUNTS_ZIP_URL) if res.status_code == 200: with open('accounts.zip', 'wb+') as f: f.write(res.content) + subprocess.run(["unzip", "-q", "-o", "accounts.zip"]) + subprocess.run(["chmod", "-R", "777", "accounts"]) + os.remove("accounts.zip") else: - LOGGER.error(f"Failed to load accounts.zip file [{res.status_code}]") - except Exception as e: - LOGGER.error(f"ACCOUNTS_ZIP_URL: {e}") - raise KeyError - subprocess.run(["unzip", "-q", "-o", "accounts.zip"]) - subprocess.run(["chmod", "-R", "777", "accounts"]) - os.remove("accounts.zip") -except: - pass + LOGGER.error(f"Failed to load the accounts.zip file [{res.status_code}]") + except Exception as err: + LOGGER.error(f"ACCOUNTS_ZIP_URL: {err}") -try: - DRIVE_LIST_URL = get_config('DRIVE_LIST_URL') - if len(DRIVE_LIST_URL) == 0: - raise KeyError +DRIVE_LIST_URL = os.environ.get('DRIVE_LIST_URL', '') +if len(DRIVE_LIST_URL) != 0: try: res = requests.get(DRIVE_LIST_URL) if res.status_code == 200: with open('drive_list', 'wb+') as f: f.write(res.content) else: - LOGGER.error(f"Failed to load drive_list file [{res.status_code}]") - except Exception as e: - LOGGER.error(f"DRIVE_LIST_URL: {e}") -except: - pass + LOGGER.error(f"Failed to load the drive_list file [{res.status_code}]") + except Exception as err: + LOGGER.error(f"DRIVE_LIST_URL: {err}") -try: - APPDRIVE_EMAIL = get_config('APPDRIVE_EMAIL') - APPDRIVE_PASS = get_config('APPDRIVE_PASS') - if len(APPDRIVE_EMAIL) == 0 or len(APPDRIVE_PASS) == 0: - raise KeyError -except: +APPDRIVE_EMAIL = os.environ.get('APPDRIVE_EMAIL', '') +APPDRIVE_PASS = os.environ.get('APPDRIVE_PASS', '') +if len(APPDRIVE_EMAIL) == 0 or len(APPDRIVE_PASS) == 0: APPDRIVE_EMAIL = None APPDRIVE_PASS = None -try: - GDTOT_CRYPT = get_config('GDTOT_CRYPT') - if len(GDTOT_CRYPT) == 0: - raise KeyError -except: +GDTOT_CRYPT = os.environ.get('GDTOT_CRYPT', '') +if len(GDTOT_CRYPT) == 0: GDTOT_CRYPT = None if os.path.exists('drive_list'): with open('drive_list', 'r+') as f: lines = f.readlines() for line in lines: - try: - temp = line.strip().split() - DRIVE_NAMES.append(temp[0].replace("_", " ")) - DRIVE_IDS.append(temp[1]) - except: - pass - try: + temp = line.strip().split() + DRIVE_NAMES.append(temp[0].replace("_", " ")) + DRIVE_IDS.append(temp[1]) + if len(temp) > 2: INDEX_URLS.append(temp[2]) - except IndexError: + else: INDEX_URLS.append(None) def create_account(sname): diff --git a/bot/__main__.py b/bot/__main__.py index 002d17a5..945c5ffb 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -6,7 +6,7 @@ from sys import executable from telegram.ext import CommandHandler -from bot import bot, LOGGER, botStartTime, AUTHORIZED_CHATS, TELEGRAPH, Interval, dispatcher, updater +from bot import bot, LOGGER, botStartTime, TELEGRAPH, Interval, dispatcher, updater from bot.modules import archive, auth, cancel, clone, count, delete, eval, list, permission, shell, status from bot.helper.ext_utils.bot_utils import get_readable_file_size, get_readable_time from bot.helper.ext_utils.fs_utils import start_cleanup, clean_all, exit_clean_up @@ -143,15 +143,15 @@ def main(): start_handler = CommandHandler(BotCommands.StartCommand, start, run_async=True) ping_handler = CommandHandler(BotCommands.PingCommand, ping, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) stats_handler = CommandHandler(BotCommands.StatsCommand, stats, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter, run_async=True) restart_handler = CommandHandler(BotCommands.RestartCommand, restart, filters=CustomFilters.owner_filter, run_async=True) help_handler = CommandHandler(BotCommands.HelpCommand, bot_help, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(start_handler) dispatcher.add_handler(ping_handler) dispatcher.add_handler(stats_handler) diff --git a/bot/helper/download_utils/ddl_generator.py b/bot/helper/download_utils/ddl_generator.py index bbd1bc50..e8cab2f5 100644 --- a/bot/helper/download_utils/ddl_generator.py +++ b/bot/helper/download_utils/ddl_generator.py @@ -8,11 +8,6 @@ from bot import APPDRIVE_EMAIL, APPDRIVE_PASS, GDTOT_CRYPT from bot.helper.ext_utils.exceptions import DDLExceptionHandler -account = { - 'email': APPDRIVE_EMAIL, - 'passwd': APPDRIVE_PASS -} - def account_login(client, url, email, password): data = { 'email': email, @@ -35,7 +30,7 @@ def appdrive(url: str) -> str: client.headers.update({ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36" }) - account_login(client, url, account['email'], account['passwd']) + account_login(client, url, APPDRIVE_EMAIL, APPDRIVE_PASS) res = client.get(url) try: key = re.findall(r'"key",\s+"(.*?)"', res.text)[0] diff --git a/bot/helper/drive_utils/gdriveTools.py b/bot/helper/drive_utils/gdriveTools.py index f639df97..6e0389e2 100644 --- a/bot/helper/drive_utils/gdriveTools.py +++ b/bot/helper/drive_utils/gdriveTools.py @@ -8,11 +8,10 @@ from io import FileIO from urllib.parse import parse_qs, urlparse from random import randrange +from telegraph.exceptions import RetryAfterError from tenacity import retry, wait_exponential, stop_after_attempt, \ retry_if_exception_type, RetryError -from telegraph.exceptions import RetryAfterError - from google.auth.transport.requests import Request from google.oauth2 import service_account from google.oauth2.credentials import Credentials @@ -123,7 +122,7 @@ def __switchServiceAccount(self): else: self.__service_account_index += 1 self.__sa_count += 1 - LOGGER.info(f"Authorizing with {self.__service_account_index}.json file") + LOGGER.info(f"Switching SA to {self.__service_account_index}.json file") self.__service = self.__authorize() @staticmethod @@ -222,6 +221,7 @@ def helper(self, link): msg = "File not found" else: msg = err + LOGGER.error(msg) return msg, "", "", "" return "", size, name, files @@ -234,9 +234,9 @@ def deleteFile(self, link: str): return msg msg = '' try: - res = self.__service.files().delete( - fileId=file_id, - supportsAllDrives=IS_TEAM_DRIVE).execute() + self.__service.files().delete( + fileId=file_id, + supportsAllDrives=IS_TEAM_DRIVE).execute() msg = "Permanently deleted" except HttpError as err: err = str(err).replace('>', '').replace('<', '') @@ -302,6 +302,7 @@ def setPermission(self, link, access): msg = "Insufficient file permissions" else: msg = err + LOGGER.error(msg) return msg @retry(wait=wait_exponential(multiplier=2, min=3, max=6), @@ -348,7 +349,7 @@ def __copyFile(self, file_id, dest_id): return self.__copyFile(file_id, dest_id) else: self.__is_cancelled = True - LOGGER.info(f"Warning: {reason}") + LOGGER.error(f"Warning: {reason}") raise err else: raise err @@ -436,6 +437,7 @@ def clone(self, link, dest_id): msg = "File not found" else: msg = err + LOGGER.error(msg) return msg def count(self, link): @@ -477,6 +479,7 @@ def count(self, link): msg = "File not found" else: msg = err + LOGGER.error(msg) return msg def _progress(self): @@ -857,7 +860,7 @@ def drive_list(self, file_name): self.telegraph_content[i-1] += f' | Next' self.__edit_page( - TELEGRAPH[(acc_no - 1) if i % page_per_acc == 0 else acc_no], + TELEGRAPH[(acc_no-1) if i % page_per_acc == 0 else acc_no], self.telegraph_content[i-1], self.telegraph_path[i-1]) diff --git a/bot/helper/ext_utils/database.py b/bot/helper/ext_utils/database.py index 215fa4df..6ae866c6 100644 --- a/bot/helper/ext_utils/database.py +++ b/bot/helper/ext_utils/database.py @@ -1,8 +1,9 @@ from pymongo import MongoClient -from bot import AUTHORIZED_CHATS, DATABASE_URL +from bot import AUTHORIZED_USERS, DATABASE_URL class DatabaseHelper: + def __init__(self): self.mongodb = MongoClient(host=DATABASE_URL)["SearchX"] self.col = self.mongodb["users"] @@ -15,13 +16,10 @@ def unauth_user(self, user_id: int): self.col.delete_many({"user_id": user_id}) return 'Authorization revoked' - def get_users(self): - return self.col.find().sort("user_id") - def load_users(self): - users = self.get_users() + users = self.col.find().sort("user_id") for user in users: - AUTHORIZED_CHATS.add(user['user_id']) + AUTHORIZED_USERS.add(user['user_id']) if DATABASE_URL is not None: DatabaseHelper().load_users() diff --git a/bot/helper/telegram_helper/bot_commands.py b/bot/helper/telegram_helper/bot_commands.py index 675c83b4..81681b43 100644 --- a/bot/helper/telegram_helper/bot_commands.py +++ b/bot/helper/telegram_helper/bot_commands.py @@ -1,4 +1,5 @@ -class _BotCommands: +class __BotCommands: + def __init__(self): self.StartCommand = 'start' self.ListCommand = 'find' @@ -23,4 +24,4 @@ def __init__(self): self.RestartCommand = 'restart' self.HelpCommand = 'help' -BotCommands = _BotCommands() +BotCommands = __BotCommands() diff --git a/bot/helper/telegram_helper/button_builder.py b/bot/helper/telegram_helper/button_builder.py index 19c511be..e31d0d24 100644 --- a/bot/helper/telegram_helper/button_builder.py +++ b/bot/helper/telegram_helper/button_builder.py @@ -1,16 +1,24 @@ from telegram import InlineKeyboardButton, InlineKeyboardMarkup class ButtonMaker: + def __init__(self): self.button = [] + self.header_button = [] + self.footer_button = [] - def build_button(self, key, link): - self.button.append(InlineKeyboardButton(text=key, url=link)) + def build_button(self, key, link, footer=False, header=False): + if not footer and not header: + self.button.append(InlineKeyboardButton(text=key, url=link)) + elif header: + self.header_button.append(InlineKeyboardButton(text=key, url=link)) + elif footer: + self.footer_button.append(InlineKeyboardButton(text=key, url=link)) - def build_menu(self, n_cols, footer_buttons=None, header_buttons=None): + def build_menu(self, n_cols): menu = [self.button[i:i + n_cols] for i in range(0, len(self.button), n_cols)] - if header_buttons: - menu.insert(0, header_buttons) - if footer_buttons: - menu.append(footer_buttons) + if self.header_button: + menu.insert(0, self.header_button) + if self.footer_button: + menu.append(self.footer_button) return InlineKeyboardMarkup(menu) diff --git a/bot/helper/telegram_helper/filters.py b/bot/helper/telegram_helper/filters.py index 5e1a7fe5..b46a9db4 100644 --- a/bot/helper/telegram_helper/filters.py +++ b/bot/helper/telegram_helper/filters.py @@ -1,24 +1,28 @@ from telegram import Message from telegram.ext import MessageFilter -from bot import AUTHORIZED_CHATS, OWNER_ID +from bot import AUTHORIZED_USERS, OWNER_ID class CustomFilters: + class __OwnerFilter(MessageFilter): + def filter(self, message: Message): return message.from_user.id == OWNER_ID owner_filter = __OwnerFilter() class __AuthorizedUserFilter(MessageFilter): + def filter(self, message: Message): - uid = message.from_user.id - return uid in AUTHORIZED_CHATS or uid == OWNER_ID + user_id = message.from_user.id + return user_id in AUTHORIZED_USERS or user_id == OWNER_ID authorized_user = __AuthorizedUserFilter() - class __AuthorizedChat(MessageFilter): + class __AuthorizedChatFilter(MessageFilter): + def filter(self, message: Message): - return message.chat.id in AUTHORIZED_CHATS + return message.chat.id in AUTHORIZED_USERS - authorized_chat = __AuthorizedChat() + authorized_chat = __AuthorizedChatFilter() diff --git a/bot/helper/telegram_helper/message_utils.py b/bot/helper/telegram_helper/message_utils.py index 6d85f043..ceff0dae 100644 --- a/bot/helper/telegram_helper/message_utils.py +++ b/bot/helper/telegram_helper/message_utils.py @@ -11,9 +11,9 @@ def sendMessage(text: str, bot, message: Message): try: return bot.sendMessage(message.chat_id, - reply_to_message_id=message.message_id, - text=text, parse_mode='HTML', - disable_web_page_preview=True) + reply_to_message_id=message.message_id, + text=text, parse_mode='HTML', + disable_web_page_preview=True) except RetryAfter as r: LOGGER.warning(str(r)) time.sleep(r.retry_after * 1.5) @@ -25,9 +25,9 @@ def sendMessage(text: str, bot, message: Message): def sendMarkup(text: str, bot, message: Message, reply_markup: InlineKeyboardMarkup): try: return bot.sendMessage(message.chat_id, - reply_to_message_id=message.message_id, - text=text, reply_markup=reply_markup, - parse_mode='HTML', disable_web_page_preview=True) + reply_to_message_id=message.message_id, + text=text, reply_markup=reply_markup, + parse_mode='HTML', disable_web_page_preview=True) except RetryAfter as r: LOGGER.warning(str(r)) time.sleep(r.retry_after * 1.5) @@ -39,9 +39,9 @@ def sendMarkup(text: str, bot, message: Message, reply_markup: InlineKeyboardMar def editMessage(text: str, message: Message, reply_markup=None): try: bot.editMessageText(text=text, message_id=message.message_id, - chat_id=message.chat.id, - reply_markup=reply_markup, parse_mode='HTML', - disable_web_page_preview=True) + chat_id=message.chat.id, + reply_markup=reply_markup, parse_mode='HTML', + disable_web_page_preview=True) except RetryAfter as r: LOGGER.warning(str(r)) time.sleep(r.retry_after * 1.5) @@ -53,15 +53,15 @@ def editMessage(text: str, message: Message, reply_markup=None): def deleteMessage(bot, message: Message): try: bot.deleteMessage(chat_id=message.chat.id, - message_id=message.message_id) + message_id=message.message_id) except Exception as err: - LOGGER.error(str(err)) + pass def sendLogFile(bot, message: Message): with open('log.txt', 'rb') as f: bot.sendDocument(document=f, filename=f.name, - reply_to_message_id=message.message_id, - chat_id=message.chat_id) + reply_to_message_id=message.message_id, + chat_id=message.chat_id) def delete_all_messages(): with status_reply_dict_lock: diff --git a/bot/modules/archive.py b/bot/modules/archive.py index 6e64e982..3624fef6 100644 --- a/bot/modules/archive.py +++ b/bot/modules/archive.py @@ -46,6 +46,8 @@ def onDownloadComplete(self): download = download_dict[self.uid] name = str(download.name()).replace('/', '') gid = download.gid() + if name == 'None' or not os.path.exists(f'{self.dir}/{name}'): + name = os.listdir(self.dir)[-1] m_path = f'{self.dir}/{name}' size = get_path_size(m_path) if self.is_compress: @@ -245,8 +247,8 @@ def extract_data(update, context): _archive(context.bot, update.message, is_extract=True) compress_handler = CommandHandler(BotCommands.CompressCommand, compress_data, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) extract_handler = CommandHandler(BotCommands.ExtractCommand, extract_data, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(compress_handler) dispatcher.add_handler(extract_handler) diff --git a/bot/modules/auth.py b/bot/modules/auth.py index e13fbfbc..a4755154 100644 --- a/bot/modules/auth.py +++ b/bot/modules/auth.py @@ -1,6 +1,6 @@ from telegram.ext import CommandHandler -from bot import dispatcher, AUTHORIZED_CHATS, DATABASE_URL +from bot import dispatcher, AUTHORIZED_USERS, DATABASE_URL from bot.helper.telegram_helper.bot_commands import BotCommands from bot.helper.telegram_helper.filters import CustomFilters from bot.helper.telegram_helper.message_utils import sendMessage @@ -14,23 +14,23 @@ def authorize(update, context): elif reply_message: user_id = reply_message.from_user.id if user_id: - if user_id in AUTHORIZED_CHATS: + if user_id in AUTHORIZED_USERS: msg = 'Already authorized' elif DATABASE_URL is not None: msg = DatabaseHelper().auth_user(user_id) - AUTHORIZED_CHATS.add(user_id) + AUTHORIZED_USERS.add(user_id) else: - AUTHORIZED_CHATS.add(user_id) + AUTHORIZED_USERS.add(user_id) msg = 'Authorization granted' else: chat_id = update.effective_chat.id - if chat_id in AUTHORIZED_CHATS: + if chat_id in AUTHORIZED_USERS: msg = 'Already authorized' elif DATABASE_URL is not None: msg = DatabaseHelper().auth_user(chat_id) - AUTHORIZED_CHATS.add(chat_id) + AUTHORIZED_USERS.add(chat_id) else: - AUTHORIZED_CHATS.add(chat_id) + AUTHORIZED_USERS.add(chat_id) msg = 'Authorization granted' sendMessage(msg, context.bot, update.message) @@ -42,29 +42,29 @@ def unauthorize(update, context): elif reply_message: user_id = reply_message.from_user.id if user_id: - if user_id in AUTHORIZED_CHATS: + if user_id in AUTHORIZED_USERS: if DATABASE_URL is not None: msg = DatabaseHelper().unauth_user(user_id) else: msg = 'Authorization revoked' - AUTHORIZED_CHATS.remove(user_id) + AUTHORIZED_USERS.remove(user_id) else: msg = 'Already unauthorized' else: chat_id = update.effective_chat.id - if chat_id in AUTHORIZED_CHATS: + if chat_id in AUTHORIZED_USERS: if DATABASE_URL is not None: msg = DatabaseHelper().unauth_user(chat_id) else: msg = 'Authorization revoked' - AUTHORIZED_CHATS.remove(chat_id) + AUTHORIZED_USERS.remove(chat_id) else: msg = 'Already unauthorized' sendMessage(msg, context.bot, update.message) def auth_users(update, context): users = '' - users += '\n'.join(f"{uid}" for uid in AUTHORIZED_CHATS) + users += '\n'.join(f"{user}" for user in AUTHORIZED_USERS) msg = f'Authorized Users\n{users}' sendMessage(msg, context.bot, update.message) diff --git a/bot/modules/cancel.py b/bot/modules/cancel.py index f3588ed2..05f79ca1 100644 --- a/bot/modules/cancel.py +++ b/bot/modules/cancel.py @@ -33,5 +33,5 @@ def cancelNode(update, context): dl.download().cancel_task() cancel_handler = CommandHandler(BotCommands.CancelCommand, cancelNode, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(cancel_handler) diff --git a/bot/modules/clone.py b/bot/modules/clone.py index e992f0c1..6cee1e85 100644 --- a/bot/modules/clone.py +++ b/bot/modules/clone.py @@ -104,5 +104,5 @@ def cloneNode(update, context): sendMessage(help_msg, context.bot, update.message) clone_handler = CommandHandler(BotCommands.CloneCommand, cloneNode, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(clone_handler) diff --git a/bot/modules/count.py b/bot/modules/count.py index c31a593f..2b3e1f42 100644 --- a/bot/modules/count.py +++ b/bot/modules/count.py @@ -26,5 +26,5 @@ def countNode(update, context): sendMessage("Send a Drive link along with command", context.bot, update.message) count_handler = CommandHandler(BotCommands.CountCommand, countNode, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(count_handler) diff --git a/bot/modules/list.py b/bot/modules/list.py index c70e5cd3..83306090 100644 --- a/bot/modules/list.py +++ b/bot/modules/list.py @@ -31,5 +31,5 @@ def list_drive(update, context): sendMessage(help_msg, context.bot, update.message) list_handler = CommandHandler(BotCommands.ListCommand, list_drive, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(list_handler) diff --git a/bot/modules/permission.py b/bot/modules/permission.py index ef534562..123424ff 100644 --- a/bot/modules/permission.py +++ b/bot/modules/permission.py @@ -36,5 +36,5 @@ def permissionNode(update, context): sendMessage("Send a Drive link along with command", context.bot, update.message) permission_handler = CommandHandler(BotCommands.PermissionCommand, permissionNode, - filters=CustomFilters.owner_filter, run_async=True) + filters=CustomFilters.owner_filter, run_async=True) dispatcher.add_handler(permission_handler) diff --git a/bot/modules/status.py b/bot/modules/status.py index db1bdbb4..b7c53a87 100644 --- a/bot/modules/status.py +++ b/bot/modules/status.py @@ -2,8 +2,8 @@ from telegram.ext import CommandHandler -from bot import dispatcher, Interval, STATUS_UPDATE_INTERVAL, download_dict, download_dict_lock, \ - status_reply_dict, status_reply_dict_lock +from bot import dispatcher, Interval, STATUS_UPDATE_INTERVAL, download_dict, \ + download_dict_lock, status_reply_dict_lock from bot.helper.ext_utils.bot_utils import SetInterval from bot.helper.telegram_helper.message_utils import sendMessage, deleteMessage, \ update_all_messages, sendStatusMessage @@ -16,11 +16,9 @@ def statusNode(update, context): if count == 0: return sendMessage("No active task", context.bot, update.message) else: - index = update.effective_chat.id + sendStatusMessage(update.message, context.bot) + deleteMessage(context.bot, update.message) with status_reply_dict_lock: - if index in status_reply_dict: - deleteMessage(context.bot, status_reply_dict[index][0]) - del status_reply_dict[index] try: if Interval: Interval[0].cancel() @@ -29,9 +27,7 @@ def statusNode(update, context): pass finally: Interval.append(SetInterval(STATUS_UPDATE_INTERVAL, update_all_messages)) - sendStatusMessage(update.message, context.bot) - deleteMessage(context.bot, update.message) status_handler = CommandHandler(BotCommands.StatusCommand, statusNode, - filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True) + filters=CustomFilters.authorized_user | CustomFilters.authorized_chat, run_async=True) dispatcher.add_handler(status_handler) diff --git a/config_sample.env b/config_sample.env index 0f480668..853441f3 100644 --- a/config_sample.env +++ b/config_sample.env @@ -4,15 +4,15 @@ OWNER_ID= DRIVE_FOLDER_ID= DOWNLOAD_DIR=/usr/src/app/downloads # OPTIONAL CONFIG -AUTHORIZED_CHATS= +AUTHORIZED_USERS= DATABASE_URL= IS_TEAM_DRIVE= USE_SERVICE_ACCOUNTS= STATUS_UPDATE_INTERVAL= TELEGRAPH_ACCS= INDEX_URL= -CLONE_LIMIT= ARCHIVE_LIMIT= +CLONE_LIMIT= TOKEN_JSON_URL= ACCOUNTS_ZIP_URL= DRIVE_LIST_URL=