From 082acc85cf4aecf4a76e198c205d3bf27755db67 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 27 Dec 2022 18:46:17 +0100 Subject: [PATCH] Added custom filters --- modules/commands/application.py | 143 +++++++++++++++---------------- modules/commands/applications.py | 32 +++---- modules/commands/label.py | 49 ++++++----- modules/commands/message.py | 41 +++++---- modules/commands/reboot.py | 14 +-- modules/commands/sponsorship.py | 18 ++-- modules/commands/warn.py | 18 ++-- modules/commands/warnings.py | 57 ++++++------ modules/custom_filters.py | 12 +++ modules/handlers/contact.py | 61 +++++++------ modules/inline.py | 5 +- 11 files changed, 229 insertions(+), 221 deletions(-) create mode 100644 modules/custom_filters.py diff --git a/modules/commands/application.py b/modules/commands/application.py index c079049..2f90f99 100644 --- a/modules/commands/application.py +++ b/modules/commands/application.py @@ -1,5 +1,5 @@ from datetime import datetime -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.enums.parse_mode import ParseMode from pyrogram.types import Message @@ -9,90 +9,89 @@ from classes.holo_user import HoloUser, UserNotFoundError from modules.utils import logWrite, locale, should_quote from dateutil.relativedelta import relativedelta from modules.database import col_applications +from modules import custom_filters # Applications command ========================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["application"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.command(["application"], prefixes=["/"])) async def cmd_application(app: Client, msg: Message): - if await isAnAdmin(msg.from_user.id) is True: + try: try: - + holo_user = HoloUser(int(msg.command[1])) + except (ValueError, UserNotFoundError): try: - holo_user = HoloUser(int(msg.command[1])) - except (ValueError, UserNotFoundError): - try: - holo_user = HoloUser((await app.get_users(msg.command[1])).id) - except (bad_request_400.UsernameInvalid, bad_request_400.PeerIdInvalid): - await msg.reply_text(locale("no_user_application", "message", locale=msg.from_user).format(msg.command[1]), quote=should_quote(msg)) - return - - application = col_applications.find_one({"user": holo_user.id}) - - if application is None: - logWrite(f"User {msg.from_user.id} requested application of {holo_user.id} but user does not exists") - await msg.reply_text(locale("user_invalid", "message", locale=msg.from_user), quote=should_quote(msg)) + holo_user = HoloUser((await app.get_users(msg.command[1])).id) + except (bad_request_400.UsernameInvalid, bad_request_400.PeerIdInvalid): + await msg.reply_text(locale("no_user_application", "message", locale=msg.from_user).format(msg.command[1]), quote=should_quote(msg)) return - application_content = [] - i = 1 + application = col_applications.find_one({"user": holo_user.id}) - for question in application['application']: + if application is None: + logWrite(f"User {msg.from_user.id} requested application of {holo_user.id} but user does not exists") + await msg.reply_text(locale("user_invalid", "message", locale=msg.from_user), quote=should_quote(msg)) + return - if i == 2: - age = relativedelta(datetime.now(), application['application']['2']) - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") - elif i == 3: - if application['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']}") - else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + application_content = [] + i = 1 + + for question in application['application']: + + if i == 2: + age = relativedelta(datetime.now(), application['application']['2']) + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") + elif i == 3: + if application['application']['3']['countryCode'] == "UA": + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']}") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application'][question]}") - - i += 1 + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application'][question]}") + + i += 1 - application_status = locale("application_status_accepted", "message", locale=msg.from_user).format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) + application_status = locale("application_status_accepted", "message", locale=msg.from_user).format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) - logWrite(f"User {msg.from_user.id} requested application of {holo_user.id}") - await msg.reply_text(locale("contact", "message", locale=msg.from_user).format(holo_user.id, "\n".join(application_content), application_status), parse_mode=ParseMode.MARKDOWN, quote=should_quote(msg)) + logWrite(f"User {msg.from_user.id} requested application of {holo_user.id}") + await msg.reply_text(locale("contact", "message", locale=msg.from_user).format(holo_user.id, "\n".join(application_content), application_status), parse_mode=ParseMode.MARKDOWN, quote=should_quote(msg)) - # if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json")["approved"]): - # user_id = int(msg.command[1]) - # else: - # list_of_users = [] - # async for m in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): - # list_of_users.append(m) - # user_id = list_of_users[0].user.id - # try: - # user_data = jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{user_id}.json") - # application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")[str(user_id)] - # application_content = [] - # i = 1 - # for question in configGet("application", file=str(msg.from_user.id)): - # if i == 2: - # age = relativedelta(datetime.now(), datetime.strptime(application['application']['2'], '%d.%m.%Y')) - # application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application']['2']} ({age.years} р.)") - # else: - # application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application'][question]}") - # i += 1 - # if user_data["sent"]: - # if user_data["approved"]: - # application_status = locale("application_status_accepted", "message").format((await app.get_users(application["approved_by"])).first_name, datetime.fromtimestamp(application["approval_date"]).strftime("%d.%m.%Y, %H:%M")) - # elif application["rejected"]: - # application_status = locale("application_status_rejected", "message").format((await app.get_users(application["rejected_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M")) - # else: - # application_status = locale("application_status_on_hold", "message") - # else: - # if user_data["approved"]: - # application_status = locale("application_status_accepted", "message").format((await app.get_users(application["approved_by"])).first_name, datetime.fromtimestamp(application["approval_date"]).strftime("%d.%m.%Y, %H:%M")) - # elif application["rejected"]: - # application_status = locale("application_status_rejected", "message").format((await app.get_users(application["rejected_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M")) - # else: - # application_status = locale("application_status_not_send", "message") - # logWrite(f"User {msg.from_user.id} requested application of {user_id}") - # await msg.reply_text(locale("contact", "message").format(str(user_id), "\n".join(application_content), application_status), quote=should_quote(msg)) - - except IndexError: - await msg.reply_text(locale("application_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) + # if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json")["approved"]): + # user_id = int(msg.command[1]) + # else: + # list_of_users = [] + # async for m in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): + # list_of_users.append(m) + # user_id = list_of_users[0].user.id + # try: + # user_data = jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{user_id}.json") + # application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json")[str(user_id)] + # application_content = [] + # i = 1 + # for question in configGet("application", file=str(msg.from_user.id)): + # if i == 2: + # age = relativedelta(datetime.now(), datetime.strptime(application['application']['2'], '%d.%m.%Y')) + # application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application']['2']} ({age.years} р.)") + # else: + # application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {application['application'][question]}") + # i += 1 + # if user_data["sent"]: + # if user_data["approved"]: + # application_status = locale("application_status_accepted", "message").format((await app.get_users(application["approved_by"])).first_name, datetime.fromtimestamp(application["approval_date"]).strftime("%d.%m.%Y, %H:%M")) + # elif application["rejected"]: + # application_status = locale("application_status_rejected", "message").format((await app.get_users(application["rejected_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M")) + # else: + # application_status = locale("application_status_on_hold", "message") + # else: + # if user_data["approved"]: + # application_status = locale("application_status_accepted", "message").format((await app.get_users(application["approved_by"])).first_name, datetime.fromtimestamp(application["approval_date"]).strftime("%d.%m.%Y, %H:%M")) + # elif application["rejected"]: + # application_status = locale("application_status_rejected", "message").format((await app.get_users(application["rejected_by"])).first_name, datetime.fromtimestamp(application["refusal_date"]).strftime("%d.%m.%Y, %H:%M")) + # else: + # application_status = locale("application_status_not_send", "message") + # logWrite(f"User {msg.from_user.id} requested application of {user_id}") + # await msg.reply_text(locale("contact", "message").format(str(user_id), "\n".join(application_content), application_status), quote=should_quote(msg)) + + except IndexError: + await msg.reply_text(locale("application_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/applications.py b/modules/commands/applications.py index a7b672c..f51a699 100644 --- a/modules/commands/applications.py +++ b/modules/commands/applications.py @@ -1,6 +1,6 @@ from os import sep, makedirs, remove from uuid import uuid1 -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client @@ -8,23 +8,23 @@ from pyrogram.enums.chat_action import ChatAction from modules.logging import logWrite from modules.utils import should_quote, jsonSave from modules.database import col_applications +from modules import custom_filters # Applications command ========================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["applications"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.command(["applications"], prefixes=["/"])) async def cmd_applications(app: Client, msg: Message): - if await isAnAdmin(msg.from_user.id) is True: - logWrite(f"Admin {msg.from_user.id} requested export of a database") - await app.send_chat_action(msg.chat.id, ChatAction.UPLOAD_DOCUMENT) - filename = uuid1() - output = [] - for entry in col_applications.find(): - del entry["_id"] - entry["date"] = entry["date"].strftime("%d.%m.%Y, %H:%M") - entry["application"]["2"] = entry["application"]["2"].strftime("%d.%m.%Y, %H:%M") - output.append(entry) - makedirs("tmp", exist_ok=True) - jsonSave(output, f"tmp{sep}{filename}.json") - await msg.reply_document(document=f"tmp{sep}{filename}.json", file_name="applications", quote=should_quote(msg)) - remove(f"tmp{sep}{filename}.json") + logWrite(f"Admin {msg.from_user.id} requested export of a database") + await app.send_chat_action(msg.chat.id, ChatAction.UPLOAD_DOCUMENT) + filename = uuid1() + output = [] + for entry in col_applications.find(): + del entry["_id"] + entry["date"] = entry["date"].strftime("%d.%m.%Y, %H:%M") + entry["application"]["2"] = entry["application"]["2"].strftime("%d.%m.%Y, %H:%M") + output.append(entry) + makedirs("tmp", exist_ok=True) + jsonSave(output, f"tmp{sep}{filename}.json") + await msg.reply_document(document=f"tmp{sep}{filename}.json", file_name="applications", quote=should_quote(msg)) + remove(f"tmp{sep}{filename}.json") # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/label.py b/modules/commands/label.py index 26dc16d..27636d0 100644 --- a/modules/commands/label.py +++ b/modules/commands/label.py @@ -1,38 +1,37 @@ -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client from modules.utils import locale, should_quote, find_user from classes.holo_user import HoloUser, LabelTooLongError +from modules import custom_filters -@app.on_message(~ filters.scheduled & filters.private & filters.command(["label"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.private & filters.command(["label"], prefixes=["/"])) async def cmd_label(app: Client, msg: Message): - if await isAnAdmin(msg.from_user.id) is True: + if len(msg.command) < 3: + await msg.reply_text("Invalid syntax:\n`/label USER LABEL`") + return - if len(msg.command) < 3: - await msg.reply_text("Invalid syntax:\n`/label USER LABEL`") - return + target = await find_user(app, msg.command[1]) - target = await find_user(app, msg.command[1]) + if target is not None: + + target = HoloUser(target) - if target is not None: + label = " ".join(msg.command[2:]) + + if label.lower() == "reset": + await target.label_reset(msg.chat) + await msg.reply_text(f"Resetting **{target.id}**'s label...", quote=should_quote(msg)) - target = HoloUser(target) - - label = " ".join(msg.command[2:]) - - if label.lower() == "reset": - await target.label_reset(msg.chat) - await msg.reply_text(f"Resetting **{target.id}**'s label...", quote=should_quote(msg)) - - else: - try: - await target.label_set(msg.chat, label) - except LabelTooLongError: - await msg.reply_text(locale("label_too_long", "message")) - return - await msg.reply_text(f"Setting **{target.id}**'s label to **{label}**...", quote=should_quote(msg)) - else: - await msg.reply_text(f"User not found") \ No newline at end of file + try: + await target.label_set(msg.chat, label) + except LabelTooLongError: + await msg.reply_text(locale("label_too_long", "message")) + return + await msg.reply_text(f"Setting **{target.id}**'s label to **{label}**...", quote=should_quote(msg)) + + else: + await msg.reply_text(f"User not found") \ No newline at end of file diff --git a/modules/commands/message.py b/modules/commands/message.py index 159fd52..265395c 100644 --- a/modules/commands/message.py +++ b/modules/commands/message.py @@ -1,34 +1,33 @@ -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client from classes.holo_user import HoloUser from modules.utils import logWrite, locale, should_quote +from modules import custom_filters # Message command ============================================================================================================== -@app.on_message(~ filters.scheduled & filters.command(["message"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.command(["message"], prefixes=["/"])) async def cmd_message(app: Client, msg: Message): - if await isAnAdmin(msg.from_user.id) is True: + try: try: - - try: - destination = HoloUser(int(msg.command[1])) - except ValueError: - destination = HoloUser(msg.command[1]) - - if ((msg.text is not None) and (len(msg.text.split()) > 2)): - await destination.message(context=msg, text=" ".join(msg.text.split()[2:]), caption=msg.caption, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) - elif ((msg.caption is not None) and (len(msg.caption.split()) > 2)): - await destination.message(context=msg, text=msg.text, caption=" ".join(msg.caption.split()[2:]), photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) - else: - await destination.message(context=msg, text=None, caption=None, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) - - except IndexError: - await msg.reply_text(locale("message_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) - logWrite(f"Admin {msg.from_user.id} tried to send message but 'IndexError'") + destination = HoloUser(int(msg.command[1])) except ValueError: - await msg.reply_text(locale("message_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) - logWrite(f"Admin {msg.from_user.id} tried to send message but 'ValueError'") + destination = HoloUser(msg.command[1]) + + if ((msg.text is not None) and (len(msg.text.split()) > 2)): + await destination.message(context=msg, text=" ".join(msg.text.split()[2:]), caption=msg.caption, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) + elif ((msg.caption is not None) and (len(msg.caption.split()) > 2)): + await destination.message(context=msg, text=msg.text, caption=" ".join(msg.caption.split()[2:]), photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) + else: + await destination.message(context=msg, text=None, caption=None, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) + + except IndexError: + await msg.reply_text(locale("message_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) + logWrite(f"Admin {msg.from_user.id} tried to send message but 'IndexError'") + except ValueError: + await msg.reply_text(locale("message_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) + logWrite(f"Admin {msg.from_user.id} tried to send message but 'ValueError'") # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/reboot.py b/modules/commands/reboot.py index 5c3d25a..d929e1a 100644 --- a/modules/commands/reboot.py +++ b/modules/commands/reboot.py @@ -1,4 +1,4 @@ -from app import app, isAnAdmin +from app import app from os import getpid from sys import exit from pyrogram import filters @@ -6,16 +6,16 @@ from pyrogram.types import Message from pyrogram.client import Client from modules.utils import locale, logWrite, should_quote from modules.scheduled import scheduler +from modules import custom_filters pid = getpid() # Shutdown command ============================================================================================================= -@app.on_message(~ filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"])) async def cmd_kill(app: Client, msg: Message): - if await isAnAdmin(msg.from_user.id) is True: - logWrite(f"Shutting down bot with pid {pid}") - await msg.reply_text(locale("shutdown", "message", locale=msg.from_user).format(pid), quote=should_quote(msg)) - scheduler.shutdown() - exit() + logWrite(f"Shutting down bot with pid {pid}") + await msg.reply_text(locale("shutdown", "message", locale=msg.from_user).format(pid), quote=should_quote(msg)) + scheduler.shutdown() + exit() # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/sponsorship.py b/modules/commands/sponsorship.py index d57a2ad..b8a3746 100644 --- a/modules/commands/sponsorship.py +++ b/modules/commands/sponsorship.py @@ -1,19 +1,19 @@ -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message from pyrogram.client import Client from classes.holo_user import HoloUser +from modules import custom_filters from modules.utils import locale, should_quote from modules.database import col_applications # Sponsorship command ========================================================================================================== -@app.on_message(~ filters.scheduled & filters.command(["sponsorship"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & (custom_filters.allowed | custom_filters.admin) & filters.command(["sponsorship"], prefixes=["/"])) async def cmd_sponsorship(app: Client, msg: Message): - if (await isAnAdmin(msg) is True) or (col_applications.find_one({"user": msg.from_user.id}) is not None): - if HoloUser(msg.from_user).application_state()[0] == "fill": - await msg.reply_text(locale("finish_application", "message"), quote=should_quote(msg)) - return - await msg.reply_text(locale("sponsorship_apply", "message"), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=str(locale("sponsor_apply", "button")), callback_data=f"sponsor_apply_{msg.from_user.id}")]]), quote=should_quote(msg)) - else: - await msg.reply_text(locale("sponsorship_application_empty", "message")) + if HoloUser(msg.from_user).application_state()[0] == "fill": + await msg.reply_text(locale("finish_application", "message"), quote=should_quote(msg)) + return + await msg.reply_text(locale("sponsorship_apply", "message"), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=str(locale("sponsor_apply", "button")), callback_data=f"sponsor_apply_{msg.from_user.id}")]]), quote=should_quote(msg)) + # else: + # await msg.reply_text(locale("sponsorship_application_empty", "message")) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/warn.py b/modules/commands/warn.py index 9227b47..0002b6d 100644 --- a/modules/commands/warn.py +++ b/modules/commands/warn.py @@ -1,22 +1,22 @@ from datetime import datetime -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client from modules.utils import configGet, locale from modules.database import col_warnings +from modules import custom_filters # Warn command ================================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["warn"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.command(["warn"], prefixes=["/"])) async def cmd_warn(app: Client, msg: Message): if msg.chat.id == configGet("destination_group"): if msg.reply_to_message_id != None: - if await isAnAdmin(msg.from_user.id) is True: - message = " ".join(msg.command[1:]) if len(msg.command) > 1 else "" - col_warnings.insert_one({"user": msg.reply_to_message.from_user.id, "admin": msg.from_user.id, "date": datetime.now(), "reason": message}) - if message == "": - await msg.reply_text(locale("warned", "message").format(msg.reply_to_message.from_user.first_name, msg.reply_to_message.from_user.id)) - else: - await msg.reply_text(locale("warned_reason", "message").format(msg.reply_to_message.from_user.first_name, msg.reply_to_message.from_user.id, message)) + message = " ".join(msg.command[1:]) if len(msg.command) > 1 else "" + col_warnings.insert_one({"user": msg.reply_to_message.from_user.id, "admin": msg.from_user.id, "date": datetime.now(), "reason": message}) + if message == "": + await msg.reply_text(locale("warned", "message").format(msg.reply_to_message.from_user.first_name, msg.reply_to_message.from_user.id)) + else: + await msg.reply_text(locale("warned_reason", "message").format(msg.reply_to_message.from_user.first_name, msg.reply_to_message.from_user.id, message)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/warnings.py b/modules/commands/warnings.py index 494f6e3..74d3e14 100644 --- a/modules/commands/warnings.py +++ b/modules/commands/warnings.py @@ -1,45 +1,44 @@ -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client from pyrogram.enums.chat_members_filter import ChatMembersFilter from modules.utils import configGet, locale, should_quote from modules.database import col_users, col_warnings +from modules import custom_filters # Warnings command ============================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["warnings"], prefixes=["/"])) +@app.on_message(~ filters.scheduled & custom_filters.admin & filters.command(["warnings"], prefixes=["/"])) async def cmd_warnings(app: Client, msg: Message): - if await isAnAdmin(msg.from_user.id) is True: + if len(msg.command) <= 1: + await msg.reply_text(locale("syntax_warnings", "message", locale=msg.from_user), quote=should_quote(msg)) + return - if len(msg.command) <= 1: - await msg.reply_text(locale("syntax_warnings", "message", locale=msg.from_user), quote=should_quote(msg)) + try: + user_db = col_users.find_one({"user": int(msg.command[1])}) + target_id = user_db["user"] + target_name = user_db["tg_name"] + except: + list_of_users = [] + async for m in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): + list_of_users.append(m) + + if len(list_of_users) != 0: + target = list_of_users[0].user + target_name = target.first_name + target_id = str(target.id) + else: + await msg.reply_text(locale("no_user_warnings", "message", locale=msg.from_user).format(msg.command[1])) return - try: - user_db = col_users.find_one({"user": int(msg.command[1])}) - target_id = user_db["user"] - target_name = user_db["tg_name"] - except: - list_of_users = [] - async for m in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): - list_of_users.append(m) + warns = len(list(col_warnings.find({"user": target_id}))) - if len(list_of_users) != 0: - target = list_of_users[0].user - target_name = target.first_name - target_id = str(target.id) - else: - await msg.reply_text(locale("no_user_warnings", "message", locale=msg.from_user).format(msg.command[1])) - return - - warns = len(list(col_warnings.find({"user": target_id}))) - - if warns == 0: - await msg.reply_text(locale("no_warnings", "message", locale=msg.from_user).format(target_name, target_id), quote=should_quote(msg)) + if warns == 0: + await msg.reply_text(locale("no_warnings", "message", locale=msg.from_user).format(target_name, target_id), quote=should_quote(msg)) + else: + if warns <= 5: + await msg.reply_text(locale("warnings_1", "message", locale=msg.from_user).format(target_name, target_id, warns), quote=should_quote(msg)) else: - if warns <= 5: - await msg.reply_text(locale("warnings_1", "message", locale=msg.from_user).format(target_name, target_id, warns), quote=should_quote(msg)) - else: - await msg.reply_text(locale("warnings_2", "message", locale=msg.from_user).format(target_name, target_id, warns), quote=should_quote(msg)) + await msg.reply_text(locale("warnings_2", "message", locale=msg.from_user).format(target_name, target_id, warns), quote=should_quote(msg)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/custom_filters.py b/modules/custom_filters.py new file mode 100644 index 0000000..8686fb8 --- /dev/null +++ b/modules/custom_filters.py @@ -0,0 +1,12 @@ +from app import isAnAdmin +from modules.database import col_applications +from pyrogram import filters + +async def admin_func(_, __, msg): + return await isAnAdmin(msg) + +async def allowed_func(_, __, msg): + return True if (col_applications.find_one({"user": msg.from_user.id}) is not None) else False + +admin = filters.create(admin_func) +allowed = filters.create(allowed_func) \ No newline at end of file diff --git a/modules/handlers/contact.py b/modules/handlers/contact.py index 4be02d5..bd51f1e 100644 --- a/modules/handlers/contact.py +++ b/modules/handlers/contact.py @@ -1,55 +1,54 @@ from dateutil.relativedelta import relativedelta from datetime import datetime -from app import app, isAnAdmin +from app import app from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client from modules.utils import locale, logWrite from modules.database import col_applications from classes.holo_user import HoloUser +from modules import custom_filters # Contact getting ============================================================================================================== -@app.on_message(~ filters.scheduled & filters.contact & filters.private) +@app.on_message(~ filters.scheduled & (custom_filters.allowed | custom_filters.admin) & filters.contact & filters.private) async def get_contact(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) - if holo_user.application_approved() or (await isAnAdmin(holo_user.id) is True): + if msg.contact.user_id != None: - if msg.contact.user_id != None: + application = col_applications.find_one({"user": msg.contact.user_id}) - application = col_applications.find_one({"user": msg.contact.user_id}) + if application is None: + logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id} but user does not exists") + await msg.reply_text(locale("contact_invalid", "message", locale=holo_user.locale)) + return - if application is None: - logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id} but user does not exists") - await msg.reply_text(locale("contact_invalid", "message", locale=holo_user.locale)) - return + application_content = [] + i = 1 - application_content = [] - i = 1 + for question in application['application']: - for question in application['application']: - - if i == 2: - age = relativedelta(datetime.now(), application['application']['2']) - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") - elif i == 3: - if application['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']}") - else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + if i == 2: + age = relativedelta(datetime.now(), application['application']['2']) + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") + elif i == 3: + if application['application']['3']['countryCode'] == "UA": + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']}") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application'][question]}") - - i += 1 + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application'][question]}") + + i += 1 - application_status = locale("application_status_accepted", "message", locale=holo_user.locale).format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) + application_status = locale("application_status_accepted", "message", locale=holo_user.locale).format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) - logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id}") - await msg.reply_text(locale("contact", "message", locale=holo_user.locale).format(str(msg.contact.user_id), "\n".join(application_content), application_status)) - + logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id}") + await msg.reply_text(locale("contact", "message", locale=holo_user.locale).format(str(msg.contact.user_id), "\n".join(application_content), application_status)) + - else: - logWrite(f"User {holo_user.id} requested application of someone but user is not telegram user") - await msg.reply_text(locale("contact_not_member", "message", locale=holo_user.locale)) + else: + logWrite(f"User {holo_user.id} requested application of someone but user is not telegram user") + await msg.reply_text(locale("contact_not_member", "message", locale=holo_user.locale)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/inline.py b/modules/inline.py index 851b42d..d0f1a8e 100644 --- a/modules/inline.py +++ b/modules/inline.py @@ -1,7 +1,8 @@ from datetime import datetime from os import path, sep from app import app, isAnAdmin -from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent +from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent, InlineQuery +from pyrogram.client import Client from pyrogram.enums.chat_type import ChatType from pyrogram.enums.chat_members_filter import ChatMembersFilter from dateutil.relativedelta import relativedelta @@ -10,7 +11,7 @@ from modules.utils import configGet, locale from modules.database import col_applications @app.on_inline_query() -async def inline_answer(client, inline_query): +async def inline_answer(client: Client, inline_query: InlineQuery): if inline_query.chat_type in [ChatType.CHANNEL]: await inline_query.answer(