From ee7f9712c8465f5ef4cc558f7fe5c4ed67ba2c68 Mon Sep 17 00:00:00 2001 From: profitroll Date: Tue, 3 Jan 2023 15:47:44 +0100 Subject: [PATCH 01/27] Updated to-do --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 42d5a35..47a0fa5 100644 --- a/README.md +++ b/README.md @@ -104,9 +104,10 @@ After all of that you're good to go! Happy using :) ## To-Do -* [x] Check sponsorship on Holo girls -* [ ] Stats and infographic -* [x] /nearby command +* [ ] Stats and infographics * [ ] Check group members without completed application +* [ ] Replicate some functions of @spoilerobot +* [x] Check sponsorship on Holo girls +* [x] /nearby command * [x] Complete messenger between user and admins * [x] Get application by id and user_id \ No newline at end of file From 3442a478d4b16262a8c2dd359cd5d8807ff4287c Mon Sep 17 00:00:00 2001 From: profitroll Date: Tue, 3 Jan 2023 15:48:33 +0100 Subject: [PATCH 02/27] Updated default config in README --- README.md | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 47a0fa5..1c09fab 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ You can see config file with all the comments below: "admin_group": 0, "destination_group": 0, "remove_application_time": -1, + "search_radius": 50, "admins": [], "bot": { "api_id": 0, @@ -67,35 +68,23 @@ You can see config file with all the comments below: "sponsorships": { "time": 9, "enabled": true + }, + "cache_avatars": { + "interval": 6, + "enabled": true + }, + "cache_members": { + "interval": 30, + "enabled": true + }, + "cache_admins": { + "interval": 120, + "enabled": true } }, "locations": { "cache": "cache", "locale": "locale" - }, - "commands": { - "rules": "Check out the rules", - "reapply": "Resubmit the application", - "sponsorship": "Apply for sponsor role" - }, - "commands_admin": { - "reboot": "Restart the bot", - "message": "Send a message", - "label": "Set user's nickname", - "warnings": "Check user's warnings", - "application": "Check user's application", - "applications": "Retrieve all applications as a JSON" - }, - "commands_group_admin": { - "reboot": "Restart the bot", - "message": "Send a message", - "label": "Set user's nickname", - "warnings": "Check user's warnings", - "application": "Check user's application", - "applications": "Retrieve all applications as a JSON" - }, - "commands_group_destination": { - "warn": "Warn a user" } } ``` From d7936fa600dfa77a4df602877e51a7cefdf5bfce Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 20:33:53 +0100 Subject: [PATCH 03/27] Added more custom filters --- modules/custom_filters.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/modules/custom_filters.py b/modules/custom_filters.py index 148b01c..fcb0e10 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -2,6 +2,7 @@ usage in context of Holo Users.""" from app import isAnAdmin +from modules.utils import configGet from modules.database import col_applications from pyrogram import filters from pyrogram.types import Message @@ -12,5 +13,14 @@ async def admin_func(_, __, msg: Message): async def allowed_func(_, __, msg: Message): return True if (col_applications.find_one({"user": msg.from_user.id}) is not None) else False +async def enabled_feature_func(_, __, msg: Message, feature: str): + return configGet("enabled", "features", feature) + admin = filters.create(admin_func) -allowed = filters.create(allowed_func) \ No newline at end of file +allowed = filters.create(allowed_func) + +enabled_applications = filters.create(enabled_feature_func, kwargs={"feature": "applications"}) +enabled_sponsorships = filters.create(enabled_feature_func, kwargs={"feature": "sponsorships"}) +enabled_warnings = filters.create(enabled_feature_func, kwargs={"feature": "warnings"}) +enabled_invites_check = filters.create(enabled_feature_func, kwargs={"feature": "invites_check"}) +enabled_dinovoice = filters.create(enabled_feature_func, kwargs={"feature": "dinovoice"}) \ No newline at end of file From 096a0498f8adef69cc5da182b33da75485db20f0 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 20:34:13 +0100 Subject: [PATCH 04/27] Now using custom filters --- modules/commands/application.py | 2 +- modules/commands/applications.py | 2 +- modules/commands/cancel.py | 3 +- modules/commands/identify.py | 2 +- modules/commands/label.py | 2 +- modules/commands/message.py | 2 +- modules/commands/nearby.py | 2 +- modules/commands/reapply.py | 3 +- modules/commands/reboot.py | 2 +- modules/commands/sponsorship.py | 2 +- modules/commands/start.py | 3 +- modules/commands/warn.py | 2 +- modules/commands/warnings.py | 2 +- modules/handlers/confirmation.py | 221 ++++++++++++++++--------------- modules/handlers/contact.py | 2 +- modules/handlers/everything.py | 8 +- modules/handlers/group_join.py | 3 +- modules/handlers/sponsorship.py | 4 +- modules/handlers/voice.py | 3 +- modules/handlers/welcome.py | 5 +- 20 files changed, 146 insertions(+), 129 deletions(-) diff --git a/modules/commands/application.py b/modules/commands/application.py index 2e8521b..fc6556e 100644 --- a/modules/commands/application.py +++ b/modules/commands/application.py @@ -12,7 +12,7 @@ from modules.database import col_applications from modules import custom_filters # Applications command ========================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["application"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.command(["application"], prefixes=["/"]) & custom_filters.admin) async def cmd_application(app: Client, msg: Message): try: diff --git a/modules/commands/applications.py b/modules/commands/applications.py index ba409e9..3f4feb3 100644 --- a/modules/commands/applications.py +++ b/modules/commands/applications.py @@ -11,7 +11,7 @@ from modules.database import col_applications from modules import custom_filters # Applications command ========================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["applications"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.command(["applications"], prefixes=["/"]) & custom_filters.admin) async def cmd_applications(app: Client, msg: Message): logWrite(f"Admin {msg.from_user.id} requested export of a database") diff --git a/modules/commands/cancel.py b/modules/commands/cancel.py index eca4630..4880b2d 100644 --- a/modules/commands/cancel.py +++ b/modules/commands/cancel.py @@ -4,8 +4,9 @@ from pyrogram.types import Message from pyrogram.client import Client from modules.utils import should_quote, logWrite, locale from modules.database import col_tmp +from modules import custom_filters -@app.on_message(~ filters.scheduled & filters.command("cancel", prefixes=["/"])) +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("cancel", prefixes=["/"])) async def command_cancel(app: Client, msg: Message): col_tmp.delete_many( {"user": msg.from_user.id} ) await msg.reply_text(locale("cancel", "message", locale=msg.from_user), quote=should_quote(msg)) diff --git a/modules/commands/identify.py b/modules/commands/identify.py index ad696c4..daf7acf 100644 --- a/modules/commands/identify.py +++ b/modules/commands/identify.py @@ -9,7 +9,7 @@ from classes.holo_user import HoloUser, UserNotFoundError, UserInvalidError from modules.utils import jsonLoad, should_quote, logWrite, locale, download_tmp, create_tmp from modules import custom_filters -@app.on_message(~ filters.scheduled & filters.command("identify", prefixes=["/"]) & custom_filters.admin) +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("identify", prefixes=["/"]) & custom_filters.admin) async def command_identify(app: Client, msg: Message): if len(msg.command) != 2: diff --git a/modules/commands/label.py b/modules/commands/label.py index 4382fe2..cfe5967 100644 --- a/modules/commands/label.py +++ b/modules/commands/label.py @@ -6,7 +6,7 @@ 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.command(["label"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.command(["label"], prefixes=["/"]) & custom_filters.admin) async def cmd_label(app: Client, msg: Message): if len(msg.command) < 3: diff --git a/modules/commands/message.py b/modules/commands/message.py index 60ce874..d7718aa 100644 --- a/modules/commands/message.py +++ b/modules/commands/message.py @@ -7,7 +7,7 @@ from modules.utils import logWrite, locale, should_quote from modules import custom_filters # Message command ============================================================================================================== -@app.on_message(~ filters.scheduled & filters.command(["message"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(~filters.scheduled & filters.command(["message"], prefixes=["/"]) & custom_filters.admin) async def cmd_message(app: Client, msg: Message): try: diff --git a/modules/commands/nearby.py b/modules/commands/nearby.py index c325564..5d2d5c3 100644 --- a/modules/commands/nearby.py +++ b/modules/commands/nearby.py @@ -11,7 +11,7 @@ from modules.database import col_applications, col_users from classes.errors.geo import PlaceNotFoundError # Nearby command =============================================================================================================== -@app.on_message(~ filters.scheduled & (filters.private | (filters.chat(configGet("admin_group")) | filters.chat(configGet("destination_group")))) & filters.command(["nearby"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & (filters.private | (filters.chat(configGet("admin_group")) | filters.chat(configGet("destination_group")))) & filters.command(["nearby"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) async def cmd_nearby(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) diff --git a/modules/commands/reapply.py b/modules/commands/reapply.py index 35192c7..7bd6d09 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -6,9 +6,10 @@ from classes.holo_user import HoloUser from modules.utils import configGet, locale, should_quote from modules.handlers.welcome import welcome_pass from modules.database import col_tmp +from modules import custom_filters # Reapply command ============================================================================================================== -@app.on_message(~ filters.scheduled & filters.private & filters.command(["reapply"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(["reapply"], prefixes=["/"])) async def cmd_reapply(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) diff --git a/modules/commands/reboot.py b/modules/commands/reboot.py index 0a5faf9..e832a15 100644 --- a/modules/commands/reboot.py +++ b/modules/commands/reboot.py @@ -11,7 +11,7 @@ from modules import custom_filters pid = getpid() # Shutdown command ============================================================================================================= -@app.on_message(~ filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(~filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"]) & custom_filters.admin) async def cmd_kill(app: Client, msg: Message): logWrite(f"Shutting down bot with pid {pid}") diff --git a/modules/commands/sponsorship.py b/modules/commands/sponsorship.py index 32e14dc..ea869b1 100644 --- a/modules/commands/sponsorship.py +++ b/modules/commands/sponsorship.py @@ -8,7 +8,7 @@ from modules.utils import locale, should_quote from modules.database import col_applications # Sponsorship command ========================================================================================================== -@app.on_message(~ filters.scheduled & filters.command(["sponsorship"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) +@app.on_message(custom_filters.enabled_sponsorships & ~filters.scheduled & filters.command(["sponsorship"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) async def cmd_sponsorship(app: Client, msg: Message): if HoloUser(msg.from_user).application_state()[0] == "fill": await msg.reply_text(locale("finish_application", "message", locale=msg.from_user), quote=should_quote(msg)) diff --git a/modules/commands/start.py b/modules/commands/start.py index ac26461..e51ac02 100644 --- a/modules/commands/start.py +++ b/modules/commands/start.py @@ -4,9 +4,10 @@ from pyrogram.types import ReplyKeyboardMarkup, Message from pyrogram.client import Client from modules.utils import locale, logWrite from modules.database import col_users +from modules import custom_filters # Start command ================================================================================================================ -@app.on_message(~ filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"])) async def cmd_start(app: Client, msg: Message): user = col_users.find_one({"user": msg.from_user.id}) diff --git a/modules/commands/warn.py b/modules/commands/warn.py index e974de6..6399212 100644 --- a/modules/commands/warn.py +++ b/modules/commands/warn.py @@ -8,7 +8,7 @@ from modules.database import col_warnings from modules import custom_filters # Warn command ================================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["warn"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_warnings & ~filters.scheduled & filters.command(["warn"], prefixes=["/"]) & custom_filters.admin) async def cmd_warn(app: Client, msg: Message): if msg.chat.id == configGet("destination_group"): diff --git a/modules/commands/warnings.py b/modules/commands/warnings.py index d2a9c7e..03fccfc 100644 --- a/modules/commands/warnings.py +++ b/modules/commands/warnings.py @@ -8,7 +8,7 @@ from modules.database import col_users, col_warnings from modules import custom_filters # Warnings command ============================================================================================================= -@app.on_message(~ filters.scheduled & filters.command(["warnings"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_warnings & ~filters.scheduled & filters.command(["warnings"], prefixes=["/"]) & custom_filters.admin) async def cmd_warnings(app: Client, msg: Message): if len(msg.command) <= 1: diff --git a/modules/handlers/confirmation.py b/modules/handlers/confirmation.py index 0878d05..b1c5fb7 100644 --- a/modules/handlers/confirmation.py +++ b/modules/handlers/confirmation.py @@ -12,150 +12,157 @@ from classes.holo_user import HoloUser from modules.utils import all_locales, configGet, locale, logWrite from modules.handlers.welcome import welcome_pass from modules.database import col_tmp +from modules import custom_filters # Confirmation ================================================================================================================= confirmation_1 = [] for pattern in all_locales("confirm", "keyboard"): confirmation_1.append(pattern[0][0]) -@app.on_message(~ filters.scheduled & filters.private & filters.command(confirmation_1, prefixes=[""])) -async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "sponsorship"] = "unknown"): +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.private & filters.command(confirmation_1, prefixes=[""])) +async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "sponsorship", "unknown"] = "unknown"): holo_user = HoloUser(msg.from_user) - if (kind == "application") or ((holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True)): + if configGet("enabled", "features", "applications") is True: - tmp_application = col_tmp.find_one({"user": holo_user.id, "type": "application"}) + if (kind == "application") or ((holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True)): - if tmp_application is None: - logWrite(f"Application of {holo_user.id} is nowhere to be found.") - return + tmp_application = col_tmp.find_one({"user": holo_user.id, "type": "application"}) - if tmp_application["sent"] is True: - return + if tmp_application is None: + logWrite(f"Application of {holo_user.id} is nowhere to be found.") + return - await msg.reply_text(locale("application_sent", "message"), reply_markup=ReplyKeyboardRemove()) + if tmp_application["sent"] is True: + return - application_content = [] - i = 1 + await msg.reply_text(locale("application_sent", "message"), reply_markup=ReplyKeyboardRemove()) - for question in tmp_application['application']: + application_content = [] + i = 1 - if i == 2: - age = relativedelta(datetime.now(), tmp_application['application']['2']) - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") - elif i == 3: - if tmp_application['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['3']['name']}") + for question in tmp_application['application']: + + if i == 2: + age = relativedelta(datetime.now(), tmp_application['application']['2']) + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") + elif i == 3: + if tmp_application['application']['3']['countryCode'] == "UA": + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['3']['name']}") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['3']['name']} ({tmp_application['application']['3']['adminName1']}, {tmp_application['application']['3']['countryName']})") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application']['3']['name']} ({tmp_application['application']['3']['adminName1']}, {tmp_application['application']['3']['countryName']})") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application'][question]}") + + i += 1 + + if tmp_application["reapply"]: + await app.send_message(chat_id=configGet("admin_group"), text=(locale("reapply_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(text=str(locale("reapply_yes", "button")), callback_data=f"reapply_yes_{holo_user.id}") + ], + [ + InlineKeyboardButton(text=str(locale("reapply_no", "button")), callback_data=f"reapply_no_{holo_user.id}") + ] + ] + ) + ) else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {tmp_application['application'][question]}") + await app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(text=str(locale("sub_yes", "button")), callback_data=f"sub_yes_{holo_user.id}") + ], + [ + InlineKeyboardButton(text=str(locale("sub_no", "button")), callback_data=f"sub_no_{holo_user.id}") + ], + [ + InlineKeyboardButton(text=str(locale("sub_aggressive", "button")), callback_data=f"sub_aggressive_{holo_user.id}") + ], + [ + InlineKeyboardButton(text=str(locale("sub_russian", "button")), callback_data=f"sub_russian_{holo_user.id}") + ] + ] + ) + ) + + logWrite(f"User {holo_user.id} sent his application and it will now be reviewed") + + col_tmp.update_one({"user": holo_user.id, "type": "application"}, {"$set": {"sent": True}}) + + return + + # configSet(["sent"], True, file=str(holo_user.id)) + # configSet(["confirmed"], True, file=str(holo_user.id)) + + if configGet("enabled", "features", "sponsorships") is True: + + if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)): + + tmp_sponsorship = col_tmp.find_one({"user": holo_user.id, "type": "sponsorship"}) + + if tmp_sponsorship is None: + logWrite(f"Sponsorship of {holo_user.id} is nowhere to be found.") + return + + if tmp_sponsorship["sent"] is True: + return + + await msg.reply_text(locale("sponsorship_sent", "message"), reply_markup=ReplyKeyboardRemove()) + + sponsorship_content = [] + + for question in tmp_sponsorship['sponsorship']: + + if question == "expires": + sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question].strftime('%d.%m.%Y')}") + elif question == "proof": + filename = uuid1() + with open(f"tmp{sep}{filename}.jpg", "wb") as f: + f.write(tmp_sponsorship['sponsorship']['proof']) + else: + sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question]}") - i += 1 - - if tmp_application["reapply"]: - await app.send_message(chat_id=configGet("admin_group"), text=(locale("reapply_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( + await app.send_photo(chat_id=configGet("admin_group"), photo=f"tmp{sep}{filename}.jpg", caption=(locale("sponsor_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(sponsorship_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [ [ - InlineKeyboardButton(text=str(locale("reapply_yes", "button")), callback_data=f"reapply_yes_{holo_user.id}") + InlineKeyboardButton(text=str(locale("sponsor_yes", "button")), callback_data=f"sponsor_yes_{holo_user.id}") ], [ - InlineKeyboardButton(text=str(locale("reapply_no", "button")), callback_data=f"reapply_no_{holo_user.id}") - ] - ] - ) - ) - else: - await app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton(text=str(locale("sub_yes", "button")), callback_data=f"sub_yes_{holo_user.id}") - ], - [ - InlineKeyboardButton(text=str(locale("sub_no", "button")), callback_data=f"sub_no_{holo_user.id}") - ], - [ - InlineKeyboardButton(text=str(locale("sub_aggressive", "button")), callback_data=f"sub_aggressive_{holo_user.id}") - ], - [ - InlineKeyboardButton(text=str(locale("sub_russian", "button")), callback_data=f"sub_russian_{holo_user.id}") + InlineKeyboardButton(text=str(locale("sponsor_no", "button")), callback_data=f"sponsor_no_{holo_user.id}") ] ] ) ) - logWrite(f"User {holo_user.id} sent his application and it will now be reviewed") + remove(f"tmp{sep}{filename}.jpg") - col_tmp.update_one({"user": holo_user.id, "type": "application"}, {"$set": {"sent": True}}) + logWrite(f"User {holo_user.id} sent his sponsorship application and it will now be reviewed") - return + col_tmp.update_one({"user": holo_user.id, "type": "sponsorship"}, {"$set": {"sent": True}}) - # configSet(["sent"], True, file=str(holo_user.id)) - # configSet(["confirmed"], True, file=str(holo_user.id)) - - if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)): - - tmp_sponsorship = col_tmp.find_one({"user": holo_user.id, "type": "sponsorship"}) - - if tmp_sponsorship is None: - logWrite(f"Sponsorship of {holo_user.id} is nowhere to be found.") return - if tmp_sponsorship["sent"] is True: - return - - await msg.reply_text(locale("sponsorship_sent", "message"), reply_markup=ReplyKeyboardRemove()) - - sponsorship_content = [] - - for question in tmp_sponsorship['sponsorship']: - - if question == "expires": - sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question].strftime('%d.%m.%Y')}") - elif question == "proof": - filename = uuid1() - with open(f"tmp{sep}{filename}.jpg", "wb") as f: - f.write(tmp_sponsorship['sponsorship']['proof']) - else: - sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question]}") - - await app.send_photo(chat_id=configGet("admin_group"), photo=f"tmp{sep}{filename}.jpg", caption=(locale("sponsor_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(sponsorship_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton(text=str(locale("sponsor_yes", "button")), callback_data=f"sponsor_yes_{holo_user.id}") - ], - [ - InlineKeyboardButton(text=str(locale("sponsor_no", "button")), callback_data=f"sponsor_no_{holo_user.id}") - ] - ] - ) - ) - - remove(f"tmp{sep}{filename}.jpg") - - logWrite(f"User {holo_user.id} sent his sponsorship application and it will now be reviewed") - - col_tmp.update_one({"user": holo_user.id, "type": "sponsorship"}, {"$set": {"sent": True}}) - - return - confirmation_2 = [] for pattern in all_locales("confirm", "keyboard"): confirmation_2.append(pattern[1][0]) -@app.on_message(~ filters.scheduled & filters.private & filters.command(confirmation_2, prefixes=[""])) -async def confirm_no(app: Client, msg: Message, kind: Literal["application", "sponsorship"] = "unknown"): +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.private & filters.command(confirmation_2, prefixes=[""])) +async def confirm_no(app: Client, msg: Message, kind: Literal["application", "sponsorship", "unknown"] = "unknown"): holo_user = HoloUser(msg.from_user) - if (kind == "application") or ((holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True)): - holo_user.application_restart() - await welcome_pass(app, msg, once_again=True) - logWrite(f"User {msg.from_user.id} restarted the application due to typo in it") - return + if configGet("enabled", "features", "applications") is True: + if (kind == "application") or ((holo_user.application_state()[0] == "fill") and (holo_user.application_state()[1] is True)): + holo_user.application_restart() + await welcome_pass(app, msg, once_again=True) + logWrite(f"User {msg.from_user.id} restarted the application due to typo in it") + return - if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)): - holo_user.sponsorship_restart() - await app.send_message(holo_user.id, locale(f"sponsor1", "message", locale=holo_user.locale), reply_markup=ForceReply(placeholder=str(locale(f"sponsor1", "force_reply", locale=holo_user.locale)))) - logWrite(f"User {msg.from_user.id} restarted the sponsorship application due to typo in it") - return + if configGet("enabled", "features", "sponsorships") is True: + if (kind == "sponsorship") or ((holo_user.sponsorship_state()[0] == "fill") and (holo_user.sponsorship_state()[1] is True)): + holo_user.sponsorship_restart() + await app.send_message(holo_user.id, locale(f"sponsor1", "message", locale=holo_user.locale), reply_markup=ForceReply(placeholder=str(locale(f"sponsor1", "force_reply", locale=holo_user.locale)))) + logWrite(f"User {msg.from_user.id} restarted the sponsorship application due to typo in it") + return # ============================================================================================================================== \ No newline at end of file diff --git a/modules/handlers/contact.py b/modules/handlers/contact.py index b6459a5..83f3122 100644 --- a/modules/handlers/contact.py +++ b/modules/handlers/contact.py @@ -10,7 +10,7 @@ from classes.holo_user import HoloUser from modules import custom_filters # Contact getting ============================================================================================================== -@app.on_message(~ filters.scheduled & filters.contact & filters.private & (custom_filters.allowed | custom_filters.admin)) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.contact & filters.private & (custom_filters.allowed | custom_filters.admin)) async def get_contact(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index d9de5c7..544b240 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -52,8 +52,12 @@ async def any_stage(app: Client, msg: Message): return if msg.text is not None: - await holo_user.application_next(msg.text, msg=msg) - await holo_user.sponsorship_next(msg.text, msg=msg) + + if configGet("enabled", "features", "applications") is True: + await holo_user.application_next(msg.text, msg=msg) + + if configGet("enabled", "features", "sponsorships") is True: + await holo_user.sponsorship_next(msg.text, msg=msg) # user_stage = configGet("stage", file=str(msg.from_user.id)) diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index d110573..82adfda 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -4,9 +4,10 @@ from pyrogram.client import Client from modules.utils import configGet, locale from modules.logging import logWrite from classes.holo_user import HoloUser +from modules import custom_filters # Filter users on join ========================================================================================================= -@app.on_chat_member_updated(group=configGet("destination_group")) +@app.on_chat_member_updated(custom_filters.enabled_invites_check, group=configGet("destination_group")) #@app.on_message(filters.new_chat_members, group=configGet("destination_group")) async def filter_join(app: Client, member: ChatMemberUpdated): diff --git a/modules/handlers/sponsorship.py b/modules/handlers/sponsorship.py index f78a6de..0c9c7d1 100644 --- a/modules/handlers/sponsorship.py +++ b/modules/handlers/sponsorship.py @@ -2,10 +2,10 @@ 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 import custom_filters -@app.on_message(~ filters.scheduled & filters.photo & filters.private) +@app.on_message(custom_filters.enabled_sponsorships & ~filters.scheduled & filters.photo & filters.private) async def sponsor_proof(app: Client, msg: Message): if msg.via_bot is None: diff --git a/modules/handlers/voice.py b/modules/handlers/voice.py index a6bb361..289fa03 100644 --- a/modules/handlers/voice.py +++ b/modules/handlers/voice.py @@ -5,8 +5,9 @@ from pyrogram.types import Message from pyrogram.client import Client from modules.logging import logWrite from modules.utils import configGet, locale +from modules import custom_filters -@app.on_message(~ filters.scheduled & filters.voice & filters.chat(configGet("destination_group"))) +@app.on_message(custom_filters.enabled_dinovoice & ~filters.scheduled & filters.voice & filters.chat(configGet("destination_group"))) async def voice_message(app: Client, msg: Message): logWrite(f"User {msg.from_user.id} sent voice message in destination group") await msg.reply_text(choice(locale("voice_message", "message"))) \ No newline at end of file diff --git a/modules/handlers/welcome.py b/modules/handlers/welcome.py index e902617..95ccf0f 100644 --- a/modules/handlers/welcome.py +++ b/modules/handlers/welcome.py @@ -4,6 +4,7 @@ from pyrogram.types import ForceReply, ReplyKeyboardMarkup, Message from pyrogram.client import Client from classes.holo_user import HoloUser from modules.utils import all_locales, locale, logWrite +from modules import custom_filters # Welcome check ================================================================================================================ welcome_1 = [] @@ -11,7 +12,7 @@ for pattern in all_locales("welcome", "keyboard"): welcome_1.append(pattern[0][0]) for pattern in all_locales("return", "keyboard"): welcome_1.append(pattern[0][0]) -@app.on_message(~ filters.scheduled & filters.private & filters.command(welcome_1, prefixes=[""])) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(welcome_1, prefixes=[""])) async def welcome_pass(app: Client, msg: Message, once_again: bool = True) -> None: """Set user's stage to 1 and start a fresh application @@ -36,7 +37,7 @@ async def welcome_pass(app: Client, msg: Message, once_again: bool = True) -> No welcome_2 = [] for pattern in all_locales("welcome", "keyboard"): welcome_2.append(pattern[1][0]) -@app.on_message(~ filters.scheduled & filters.private & filters.command(welcome_2, prefixes=[""])) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(welcome_2, prefixes=[""])) async def welcome_reject(app: Client, msg: Message): logWrite(f"User {msg.from_user.id} rejected to start the application") From b3c5f060a1dfa2914c53e733c3b22fc89acd3a1b Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 20:34:44 +0100 Subject: [PATCH 05/27] Now features can be turned off --- config_example.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/config_example.json b/config_example.json index 55bbd79..f1bdd55 100644 --- a/config_example.json +++ b/config_example.json @@ -30,6 +30,23 @@ "size": 512, "location": "logs" }, + "features": { + "applications": { + "enabled": true + }, + "sponsorships": { + "enabled": true + }, + "warnings": { + "enabled": false + }, + "invites_check": { + "enabled": true + }, + "dinovoice": { + "enabled": false + } + }, "scheduler": { "birthdays": { "time": 9, From ff95d9556de79830b2a598b83be4e34bdde0cdbf Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 20:48:35 +0100 Subject: [PATCH 06/27] Fixed some minor issues --- modules/custom_filters.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/modules/custom_filters.py b/modules/custom_filters.py index fcb0e10..89f771d 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -13,14 +13,26 @@ async def admin_func(_, __, msg: Message): async def allowed_func(_, __, msg: Message): return True if (col_applications.find_one({"user": msg.from_user.id}) is not None) else False -async def enabled_feature_func(_, __, msg: Message, feature: str): - return configGet("enabled", "features", feature) +async def enabled_applications_func(_, __, msg: Message): + return configGet("enabled", "features", "applications") + +async def enabled_sponsorships_func(_, __, msg: Message): + return configGet("enabled", "features", "sponsorships") + +async def enabled_warnings_func(_, __, msg: Message): + return configGet("enabled", "features", "warnings") + +async def enabled_invites_check_func(_, __, msg: Message): + return configGet("enabled", "features", "invites_check") + +async def enabled_dinovoice_func(_, __, msg: Message): + return configGet("enabled", "features", "dinovoice") admin = filters.create(admin_func) allowed = filters.create(allowed_func) -enabled_applications = filters.create(enabled_feature_func, kwargs={"feature": "applications"}) -enabled_sponsorships = filters.create(enabled_feature_func, kwargs={"feature": "sponsorships"}) -enabled_warnings = filters.create(enabled_feature_func, kwargs={"feature": "warnings"}) -enabled_invites_check = filters.create(enabled_feature_func, kwargs={"feature": "invites_check"}) -enabled_dinovoice = filters.create(enabled_feature_func, kwargs={"feature": "dinovoice"}) \ No newline at end of file +enabled_applications = filters.create(enabled_applications_func) +enabled_sponsorships = filters.create(enabled_sponsorships_func) +enabled_warnings = filters.create(enabled_warnings_func) +enabled_invites_check = filters.create(enabled_invites_check_func) +enabled_dinovoice = filters.create(enabled_dinovoice_func) \ No newline at end of file From 3d4dd292051bd17618ac80b92b863109b60dd8bf Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 21:36:26 +0100 Subject: [PATCH 07/27] Changed the way how commands work --- README.md | 132 +++++++++++++++++++++++++++++++++++- config_example.json | 113 +++++++++++++++++++++++++++++++ locale/uk.json | 31 +++------ modules/scheduled.py | 156 ++++++++++++++++++++++++------------------- 4 files changed, 338 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index 1c09fab..76278f6 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,23 @@ You can see config file with all the comments below: "size": 512, "location": "logs" }, + "features": { + "applications": { + "enabled": true + }, + "sponsorships": { + "enabled": true + }, + "warnings": { + "enabled": false + }, + "invites_check": { + "enabled": true + }, + "dinovoice": { + "enabled": false + } + }, "scheduler": { "birthdays": { "time": 9, @@ -85,6 +102,119 @@ You can see config file with all the comments below: "locations": { "cache": "cache", "locale": "locale" + }, + "commands": { + "rules": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "general" + ] + }, + "cancel": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "applications", + "sponsorships" + ] + }, + "nearby": { + "permissions": [ + "users", + "admins", + "group_users", + "group_admins" + ], + "modules": [ + "applications" + ] + }, + "warn": { + "permissions": [ + "group_users" + ], + "modules": [ + "warnings" + ] + }, + "reapply": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "applications" + ] + }, + "sponsorship": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "sponsorships" + ] + }, + "reboot": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "general" + ] + }, + "label": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications" + ] + }, + "message": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "general" + ] + }, + "identify": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications", + "sponsorships" + ] + }, + "application": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications" + ] + }, + "applications": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications" + ] + } } } ``` @@ -99,4 +229,4 @@ After all of that you're good to go! Happy using :) * [x] Check sponsorship on Holo girls * [x] /nearby command * [x] Complete messenger between user and admins -* [x] Get application by id and user_id \ No newline at end of file +* [x] Get application by id and user_id diff --git a/config_example.json b/config_example.json index f1bdd55..2861396 100644 --- a/config_example.json +++ b/config_example.json @@ -72,5 +72,118 @@ "locations": { "cache": "cache", "locale": "locale" + }, + "commands": { + "rules": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "general" + ] + }, + "cancel": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "applications", + "sponsorships" + ] + }, + "nearby": { + "permissions": [ + "users", + "admins", + "group_users", + "group_admins" + ], + "modules": [ + "applications" + ] + }, + "warn": { + "permissions": [ + "group_users" + ], + "modules": [ + "warnings" + ] + }, + "reapply": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "applications" + ] + }, + "sponsorship": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "sponsorships" + ] + }, + "reboot": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "general" + ] + }, + "label": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications" + ] + }, + "message": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "general" + ] + }, + "identify": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications", + "sponsorships" + ] + }, + "application": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications" + ] + }, + "applications": { + "permissions": [ + "admins", + "group_admins" + ], + "modules": [ + "applications" + ] + } } } \ No newline at end of file diff --git a/locale/uk.json b/locale/uk.json index 2ead0de..c5674a8 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -238,33 +238,18 @@ ], "rules_additional": "Додаткові правила, які несуть рекомендаційний характер, та не мають явних покарань за порушення:\n1️⃣) У чаті немає заборони на російську мову. Ми поважаємо кожного українця і не бажаємо розпалювати мовні конфлікти.\n2️⃣) У чаті немає заборони на російський контент. Але, майте на увазі, що учасники, здебільшого, не будуть зацікавлені у тому, щоб обговорювати його і він може бути проігнорованим.\n3️⃣) Не зловживайте матами. Намагайтесь спілкуватись чистою мовою.\n4️⃣) Поважайте авторські права контентмейкерів. Якщо ви знаходите арт, анімацію, музику тощо, на офіційних ресурсах (pixiv, twitter, deviantart тощо), відправляйте на нього посилання.\nЯкщо хтось із учасників відправив арт із не офіційного ресурсу і ви бажаєте дізнатись його автора, відправте у відповідь повідомлення із текстом `/search` на повідомлення із артом.", "commands": { - "rules": "Правила спільноти", + "application": "Переглянути анкету користувача", + "applications": "Отримати всі анкети як JSON", "cancel": "Відмінити актуальну дію", + "identify": "Дізнатись дані про користувача за айді", + "label": "Встановити нікнейм користувачу", + "message": "Надіслати користувачу повідомлення", "nearby": "Показати користувачів поблизу", "reapply": "Повторно заповнити анкету", - "sponsorship": "Отримати роль за спонсорство" - }, - "commands_admin": { "reboot": "Перезапустити бота", - "label": "Встановити нікнейм користувачу", - "message": "Надіслати користувачу повідомлення", - "identify": "Дізнатись дані про користувача за айді", - "warnings": "Переглянути попередження користувача", - "application": "Переглянути анкету користувача", - "applications": "Отримати всі анкети як JSON" - }, - "commands_group_admin": { - "reboot": "Перезапустити бота", - "label": "Встановити нікнейм користувачу", - "nearby": "Показати користувачів поблизу", - "message": "Надіслати користувачу повідомлення", - "identify": "Дізнатись дані про користувача за айді", - "warnings": "Переглянути попередження користувача", - "application": "Переглянути анкету користувача", - "applications": "Отримати всі анкети як JSON" - }, - "commands_group_destination": { + "rules": "Правила спільноти", + "sponsorship": "Отримати роль за спонсорство", "warn": "Попередити користувача", - "nearby": "Показати користувачів поблизу" + "warnings": "Переглянути попередження користувача" } } \ No newline at end of file diff --git a/modules/scheduled.py b/modules/scheduled.py index ce986ef..b5ea0c2 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -50,113 +50,129 @@ if configGet("enabled", "scheduler", "cache_avatars"): # Check for birthdays -if configGet("enabled", "scheduler", "birthdays"): - @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays")) - async def check_birthdays(): - for entry in col_applications.find(): - if entry["application"]["2"].strftime("%d.%m") == datetime.now().strftime("%d.%m"): - try: - tg_user = await app.get_users(entry["user"]) - await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), entry["application"]["2"], '%d.%m.%Y').years)) ) # type: ignore - logWrite(f"Notified admins about {entry['user']}'s birthday") - except Exception as exp: - logWrite(f"Could not find user {entry['user']} to send a message about birthday due to '{exp}'") - continue - logWrite("Birthdays check performed") +if configGet("enabled", "features", "applications") is True: + if configGet("enabled", "scheduler", "birthdays") is True: + @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays")) + async def check_birthdays(): + for entry in col_applications.find(): + if entry["application"]["2"].strftime("%d.%m") == datetime.now().strftime("%d.%m"): + try: + tg_user = await app.get_users(entry["user"]) + await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), entry["application"]["2"], '%d.%m.%Y').years)) ) # type: ignore + logWrite(f"Notified admins about {entry['user']}'s birthday") + except Exception as exp: + logWrite(f"Could not find user {entry['user']} to send a message about birthday due to '{exp}'") + continue + logWrite("Birthdays check performed") # Check for expired sponsorships -if configGet("enabled", "scheduler", "sponsorships"): - @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships")) - async def check_sponsors(): - for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()+timedelta(days=2)}}): - try: - tg_user = await app.get_users(entry["user"]) - until_expiry = relativedelta(datetime.now(), entry["sponsorship"]["expires"]).days - await app.send_message( tg_user, locale("sponsorships_expires", "message").format(until_expiry) ) # type: ignore - logWrite(f"Notified user that sponsorship expires in {until_expiry} days") - except Exception as exp: - logWrite(f"Could not find user {entry['user']} notify about sponsorship expiry due to '{exp}'") - continue - for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()}}): - try: - holo_user = HoloUser(entry["user"]) - await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore - await holo_user.label_reset(configGet("destination_group")) - col_sponsorships.find_one_and_delete({"user": holo_user.id}) +if configGet("enabled", "features", "sponsorships") is True: + if configGet("enabled", "scheduler", "sponsorships") is True: + @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "sponsorships")) + async def check_sponsors(): + for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()+timedelta(days=2)}}): try: tg_user = await app.get_users(entry["user"]) - logWrite(f"Notified user that sponsorship expired") + until_expiry = relativedelta(datetime.now(), entry["sponsorship"]["expires"]).days + await app.send_message( tg_user, locale("sponsorships_expires", "message").format(until_expiry) ) # type: ignore + logWrite(f"Notified user that sponsorship expires in {until_expiry} days") except Exception as exp: - logWrite(f"Could not find user {entry['user']} notify about sponsorship expired due to '{exp}'") - except Exception as exp: - logWrite(f"Could not reset label of user {entry['user']} due to '{exp}'") - continue - logWrite("Sponsorships check performed") + logWrite(f"Could not find user {entry['user']} notify about sponsorship expiry due to '{exp}'") + continue + for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()}}): + try: + holo_user = HoloUser(entry["user"]) + await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore + await holo_user.label_reset(configGet("destination_group")) + col_sponsorships.find_one_and_delete({"user": holo_user.id}) + try: + tg_user = await app.get_users(entry["user"]) + logWrite(f"Notified user that sponsorship expired") + except Exception as exp: + logWrite(f"Could not find user {entry['user']} notify about sponsorship expired due to '{exp}'") + except Exception as exp: + logWrite(f"Could not reset label of user {entry['user']} due to '{exp}'") + continue + logWrite("Sponsorships check performed") # Register all bot commands @scheduler.scheduled_job(trigger="date", run_date=datetime.now()+timedelta(seconds=3)) async def commands_register(): + commands = { + "users": [], + "admins": [], + "group_users": [], + "group_admins": [], + "locales": {} + } + valid_locales = [] files_locales = listdir(f'{configGet("locale", "locations")}') + for entry in files_locales: if entry.endswith(".json"): valid_locales.append(".".join(entry.split(".")[:-1])) + commands["locales"][".".join(entry.split(".")[:-1])] = { + "users": [], + "admins": [], + "group_users": [], + "group_admins": [] + } + + config_modules = configGet("features") + config_commands = configGet("commands") + + + for command in config_commands: + + enabled = False + + for module in config_commands[command]["modules"]: + if config_modules[module] == module: + enabled = True + + if enabled is False: + continue + + for permission in config_commands[command]["permissions"]: + commands[permission].append(BotCommand(command, locale("commands")[command])) + for lc in valid_locales: + commands["locales"][lc][permission].append(BotCommand(command, locale("commands", locale=lc)[command])) + # Registering user commands - commands_list = [] - for command in locale("commands"): - commands_list.append(BotCommand(command, locale("commands")[command])) - await app.set_bot_commands(commands_list) + await app.set_bot_commands(commands["users"]) logWrite("Registered user commands for default locale") # Registering user commands for each locale for lc in valid_locales: - commands_list = [] - for command in locale("commands", locale=lc): - commands_list.append(BotCommand(command, locale("commands",locale=lc)[command])) - await app.set_bot_commands(commands_list, language_code=lc) + await app.set_bot_commands(commands["locales"][lc]["users"], language_code=lc) logWrite(f"Registered user commands for locale {lc}") - # Registering admin commands - commands_admin_list = [] - for command in locale("commands"): - commands_admin_list.append(BotCommand(command, locale("commands")[command])) - - for command in locale("commands_admin"): - commands_admin_list.append(BotCommand(command, locale("commands_admin")[command])) - - for admin in configGet("admins"): + # Registering admin/owner commands + for admin in configGet("admins")+[configGet("owner")]: try: - await app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=admin)) - logWrite(f"Registered admin commands for admin {admin}") + await app.set_bot_commands(commands["admins"], scope=BotCommandScopeChat(chat_id=admin)) + if admin == configGet("owner"): + logWrite(f"Registered admin commands for owner {configGet('owner')}") + else: + logWrite(f"Registered admin commands for admin {admin}") except bad_request_400.PeerIdInvalid: pass - try: - await app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=configGet("owner"))) - logWrite(f"Registered admin commands for owner {configGet('owner')}") - except bad_request_400.PeerIdInvalid: - logWrite(f"Could not register commands for bot owner. Perhaps user has not started the bot yet.") - # Registering admin group commands - commands_group_admin_list = [] - for command in locale("commands_group_admin"): - commands_group_admin_list.append(BotCommand(command, locale("commands_group_admin")[command])) try: - await app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_group"))) + await app.set_bot_commands(commands["group_admins"], scope=BotCommandScopeChat(chat_id=configGet("admin_group"))) logWrite("Registered admin group commands for default locale") except bad_request_400.ChannelInvalid: logWrite(f"Could not register commands for admin group. Bot is likely not in the group.") # Registering destination group commands - commands_group_destination_list = [] - for command in locale("commands_group_destination"): - commands_group_destination_list.append(BotCommand(command, locale("commands_group_destination")[command])) try: - await app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_group"))) + await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("destination_group"))) logWrite("Registered destination group commands") except bad_request_400.ChannelInvalid: logWrite(f"Could not register commands for destination group. Bot is likely not in the group.") \ No newline at end of file From aad5c4f9f2757cfb10a76d4d14501a0c574acb05 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 21:46:16 +0100 Subject: [PATCH 08/27] Added support for "general" module --- config_example.json | 3 +++ modules/commands/message.py | 2 +- modules/commands/reboot.py | 2 +- modules/commands/rules.py | 3 ++- modules/custom_filters.py | 4 ++++ 5 files changed, 11 insertions(+), 3 deletions(-) diff --git a/config_example.json b/config_example.json index 2861396..3cca296 100644 --- a/config_example.json +++ b/config_example.json @@ -31,6 +31,9 @@ "location": "logs" }, "features": { + "general": { + "enabled": true + }, "applications": { "enabled": true }, diff --git a/modules/commands/message.py b/modules/commands/message.py index d7718aa..94af6d8 100644 --- a/modules/commands/message.py +++ b/modules/commands/message.py @@ -7,7 +7,7 @@ from modules.utils import logWrite, locale, should_quote from modules import custom_filters # Message command ============================================================================================================== -@app.on_message(~filters.scheduled & filters.command(["message"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.command(["message"], prefixes=["/"]) & custom_filters.admin) async def cmd_message(app: Client, msg: Message): try: diff --git a/modules/commands/reboot.py b/modules/commands/reboot.py index e832a15..8005a1a 100644 --- a/modules/commands/reboot.py +++ b/modules/commands/reboot.py @@ -11,7 +11,7 @@ from modules import custom_filters pid = getpid() # Shutdown command ============================================================================================================= -@app.on_message(~filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"]) & custom_filters.admin) +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["/"]) & custom_filters.admin) async def cmd_kill(app: Client, msg: Message): logWrite(f"Shutting down bot with pid {pid}") diff --git a/modules/commands/rules.py b/modules/commands/rules.py index 98b6c39..f81a701 100644 --- a/modules/commands/rules.py +++ b/modules/commands/rules.py @@ -4,6 +4,7 @@ from pyrogram import filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, User, Message from pyrogram.client import Client from modules.utils import locale +from modules import custom_filters from classes.holo_user import HoloUser class DefaultRulesMarkup(list): @@ -35,7 +36,7 @@ class DefaultRulesMarkup(list): # Rules command ============================================================================================================= -@app.on_message(~ filters.scheduled & filters.private & filters.command(["rules"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["rules"], prefixes=["/"])) async def cmd_rules(app: Client, msg: Message): await msg.reply_text(locale("rules_msg", locale=msg.from_user), disable_web_page_preview=True, reply_markup=DefaultRulesMarkup(msg.from_user).keyboard) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/custom_filters.py b/modules/custom_filters.py index 89f771d..dc54ef4 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -13,6 +13,9 @@ async def admin_func(_, __, msg: Message): async def allowed_func(_, __, msg: Message): return True if (col_applications.find_one({"user": msg.from_user.id}) is not None) else False +async def enabled_general_func(_, __, msg: Message): + return configGet("enabled", "features", "general") + async def enabled_applications_func(_, __, msg: Message): return configGet("enabled", "features", "applications") @@ -31,6 +34,7 @@ async def enabled_dinovoice_func(_, __, msg: Message): admin = filters.create(admin_func) allowed = filters.create(allowed_func) +enabled_general = filters.create(enabled_general_func) enabled_applications = filters.create(enabled_applications_func) enabled_sponsorships = filters.create(enabled_sponsorships_func) enabled_warnings = filters.create(enabled_warnings_func) From 1268c33830b5599fe4b880f41284adbb7606da8a Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 3 Jan 2023 21:54:01 +0100 Subject: [PATCH 09/27] Small fix --- modules/scheduled.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index b5ea0c2..0d1023e 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -111,7 +111,7 @@ async def commands_register(): valid_locales = [] files_locales = listdir(f'{configGet("locale", "locations")}') - + for entry in files_locales: if entry.endswith(".json"): valid_locales.append(".".join(entry.split(".")[:-1])) @@ -131,7 +131,7 @@ async def commands_register(): enabled = False for module in config_commands[command]["modules"]: - if config_modules[module] == module: + if config_modules[module]["enabled"] is True: enabled = True if enabled is False: From 8cb3ef283b256ec1a5fb7d6dbc20b803d0de3ed7 Mon Sep 17 00:00:00 2001 From: profitroll Date: Wed, 4 Jan 2023 13:15:08 +0100 Subject: [PATCH 10/27] Now using find_user() --- modules/commands/identify.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/commands/identify.py b/modules/commands/identify.py index daf7acf..6f83ed0 100644 --- a/modules/commands/identify.py +++ b/modules/commands/identify.py @@ -6,7 +6,7 @@ from pyrogram.client import Client from pyrogram.errors import bad_request_400 from pyrogram.enums.chat_action import ChatAction from classes.holo_user import HoloUser, UserNotFoundError, UserInvalidError -from modules.utils import jsonLoad, should_quote, logWrite, locale, download_tmp, create_tmp +from modules.utils import jsonLoad, should_quote, logWrite, locale, download_tmp, create_tmp, find_user from modules import custom_filters @app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("identify", prefixes=["/"]) & custom_filters.admin) @@ -20,8 +20,8 @@ async def command_identify(app: Client, msg: Message): try: holo_user = HoloUser(int(msg.command[1])) except ValueError: - holo_user = HoloUser(await app.get_users(msg.command[1])) - except (UserInvalidError, UserNotFoundError, bad_request_400.UsernameInvalid, bad_request_400.PeerIdInvalid, bad_request_400.UsernameNotOccupied): + holo_user = HoloUser(await find_user(app, msg.command[1])) + except (UserInvalidError, UserNotFoundError, bad_request_400.UsernameInvalid, bad_request_400.PeerIdInvalid, bad_request_400.UsernameNotOccupied, TypeError): await msg.reply_text(locale("identify_not_found", "message", locale=msg.from_user).format(msg.command[1])) return From 083281e784e5e84b588567d93794d85c40da798b Mon Sep 17 00:00:00 2001 From: profitroll Date: Wed, 4 Jan 2023 13:31:42 +0100 Subject: [PATCH 11/27] Fixed some paths --- modules/scheduled.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index 0d1023e..a012490 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -22,7 +22,7 @@ if configGet("enabled", "scheduler", "cache_members"): async for member in app.get_chat_members(configGet("destination_group")): list_of_users.append(member.user.id) makedirs("cache", exist_ok=True) - jsonSave(list_of_users, f"cache{sep}group_members") + jsonSave(list_of_users, path.join(configGet("cache", "locations"), "group_members")) if configGet("enabled", "scheduler", "cache_admins"): @scheduler.scheduled_job(trigger="interval", seconds=configGet("interval", "scheduler", "cache_admins")) @@ -31,7 +31,7 @@ if configGet("enabled", "scheduler", "cache_admins"): async for member in app.get_chat_members(configGet("admin_group")): list_of_users.append(member.user.id) makedirs("cache", exist_ok=True) - jsonSave(list_of_users, f"cache{sep}admins") + jsonSave(list_of_users, path.join(configGet("cache", "locations"), "admins")) # Cache the avatars of group members if configGet("enabled", "scheduler", "cache_avatars"): @@ -45,7 +45,7 @@ if configGet("enabled", "scheduler", "cache_avatars"): if user.photo != None: if not path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{user.photo.big_file_id}'): print(f'Pre-cached avatar {user.photo.big_file_id} of {user.id}', flush=True) - await app.download_media(user.photo.big_file_id, file_name=f'{configGet("cache", "locations")}{sep}avatars{sep}{user.photo.big_file_id}') + await app.download_media(user.photo.big_file_id, file_name=path.join(configGet("cache", "locations"), "avatars", user.photo.big_file_id)) logWrite("Avatars caching performed") From ccbc135ee42bca325df21e83c884ed2e26aabf0d Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 17:26:27 +0100 Subject: [PATCH 12/27] No need to save bot's ID anymore --- config_example.json | 1 - modules/handlers/everything.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/config_example.json b/config_example.json index 3cca296..2dc555a 100644 --- a/config_example.json +++ b/config_example.json @@ -2,7 +2,6 @@ "locale": "uk", "debug": false, "owner": 0, - "bot_id": 0, "age_allowed": 0, "api": "http://example.com", "inline_preview_count": 7, diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index 544b240..0297ad3 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -120,7 +120,7 @@ async def any_stage(app: Client, msg: Message): @app.on_message(~ filters.scheduled & filters.group) async def message_in_group(app: Client, msg: Message): if (msg.chat is not None) and (msg.via_bot is not None): - if (msg.via_bot.id == configGet("bot_id")) and (msg.chat.id == configGet("destination_group")): + if (msg.via_bot.id == (await app.get_me()).id) and (msg.chat.id == configGet("destination_group")): if configGet("remove_application_time") > 0: logWrite(f"User {msg.from_user.id} requested application in destination group, removing in {configGet('remove_application_time')} minutes") await asyncio.sleep(configGet("remove_application_time")*60) From d59a1671b3fd8940c5fdf2decf215fefc31a8c2b Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 19:14:02 +0100 Subject: [PATCH 13/27] Changed config keys --- README.md | 10 +++++++--- app.py | 2 +- classes/holo_user.py | 8 ++++---- config_example.json | 6 ++++-- modules/callbacks/reapply.py | 8 ++++---- modules/callbacks/sponsorship.py | 6 +++--- modules/callbacks/sub.py | 12 ++++++------ modules/callbacks/sus.py | 8 ++++---- modules/commands/application.py | 2 +- modules/commands/nearby.py | 2 +- modules/commands/reapply.py | 2 +- modules/commands/warn.py | 2 +- modules/commands/warnings.py | 2 +- modules/handlers/confirmation.py | 6 +++--- modules/handlers/everything.py | 2 +- modules/handlers/group_join.py | 6 +++--- modules/handlers/voice.py | 2 +- modules/inline.py | 2 +- modules/scheduled.py | 14 +++++++------- 19 files changed, 54 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 76278f6..ece51c1 100644 --- a/README.md +++ b/README.md @@ -32,15 +32,16 @@ You can see config file with all the comments below: "locale": "uk", "debug": false, "owner": 0, - "bot_id": 0, "age_allowed": 0, "api": "http://example.com", "inline_preview_count": 7, - "admin_group": 0, - "destination_group": 0, "remove_application_time": -1, "search_radius": 50, "admins": [], + "groups": { + "admin": 0, + "users": 0 + }, "bot": { "api_id": 0, "api_hash": "", @@ -61,6 +62,9 @@ You can see config file with all the comments below: "location": "logs" }, "features": { + "general": { + "enabled": true + }, "applications": { "enabled": true }, diff --git a/app.py b/app.py index 0c1e383..59f33a3 100644 --- a/app.py +++ b/app.py @@ -22,7 +22,7 @@ async def isAnAdmin(admin_id): # Check if user is in admin group try: - async for member in app.get_chat_members(configGet("admin_group")): + async for member in app.get_chat_members(configGet("admin", "groups")): if member.user.id == admin_id: return True except bad_request_400.ChannelInvalid: diff --git a/classes/holo_user.py b/classes/holo_user.py index 1757a31..0c719a9 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -284,9 +284,9 @@ class HoloUser(): raise LabelTooLongError(label) self.label = label try: - await app.promote_chat_member(configGet("destination_group"), self.id, privileges=ChatPrivileges(can_pin_messages=True, can_manage_video_chats=True)) + await app.promote_chat_member(configGet("admin", "users"), self.id, privileges=ChatPrivileges(can_pin_messages=True, can_manage_video_chats=True)) if not await isAnAdmin(self.id): - await app.set_administrator_title(configGet("destination_group"), self.id, label) + await app.set_administrator_title(configGet("admin", "users"), self.id, label) self.set("label", label) except bad_request_400.UserCreator: logWrite(f"Could not set {self.id}'s title to '{self.label}' because of bad_request_400.UserCreator") @@ -301,9 +301,9 @@ class HoloUser(): """ self.label = "" self.set("label", "") - await app.set_administrator_title(configGet("destination_group"), self.id, "") + await app.set_administrator_title(configGet("admin", "users"), self.id, "") if not await isAnAdmin(self.id): - await app.promote_chat_member(configGet("destination_group"), self.id, privileges=ChatPrivileges( + await app.promote_chat_member(configGet("admin", "users"), self.id, privileges=ChatPrivileges( can_manage_chat=False, can_pin_messages=False, can_manage_video_chats=False diff --git a/config_example.json b/config_example.json index 2dc555a..34751e0 100644 --- a/config_example.json +++ b/config_example.json @@ -5,11 +5,13 @@ "age_allowed": 0, "api": "http://example.com", "inline_preview_count": 7, - "admin_group": 0, - "destination_group": 0, "remove_application_time": -1, "search_radius": 50, "admins": [], + "groups": { + "admin": 0, + "users": 0 + }, "bot": { "api_id": 0, "api_hash": "", diff --git a/modules/callbacks/reapply.py b/modules/callbacks/reapply.py index b3c8141..7cc599f 100644 --- a/modules/callbacks/reapply.py +++ b/modules/callbacks/reapply.py @@ -16,7 +16,7 @@ async def callback_reapply_query_accept(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) logWrite(f"User {holo_user.id} got their reapplication approved by {clb.from_user.id}") await app.send_message(holo_user.id, locale("approved_joined", "message", locale=holo_user)) @@ -32,12 +32,12 @@ async def callback_reapply_query_accept(app: Client, clb: CallbackQuery): need_link = True - async for member in app.get_chat_members(configGet("destination_group")): + async for member in app.get_chat_members(configGet("admin", "users")): if member.user.id == holo_user.id: need_link = False if need_link: - link = await app.create_chat_invite_link(configGet("destination_group"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) + link = await app.create_chat_invite_link(configGet("admin", "users"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) await app.send_message(holo_user.id, locale("read_rules", "message", locale=holo_user)) @@ -62,7 +62,7 @@ async def callback_query_reapply_reject(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("rejected_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("rejected_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True) await app.send_message(holo_user.id, locale("rejected", "message", locale=holo_user)) logWrite(f"User {fullclb[2]} got their reapplication rejected by {clb.from_user.id}") diff --git a/modules/callbacks/sponsorship.py b/modules/callbacks/sponsorship.py index 910a5f6..37cc5bb 100644 --- a/modules/callbacks/sponsorship.py +++ b/modules/callbacks/sponsorship.py @@ -34,7 +34,7 @@ async def callback_query_sponsor_yes(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("sponsor_approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("sponsor_approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) await app.send_message(holo_user.id, locale("sponsor_approved", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got sponsorship approved by {clb.from_user.id}") @@ -67,7 +67,7 @@ async def callback_query_sponsor_yes(app: Client, clb: CallbackQuery): } ) - await holo_user.label_set(configGet("destination_group"), col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]["label"]) + await holo_user.label_set(configGet("admin", "users"), col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]["label"]) edited_markup = [[InlineKeyboardButton(text=str(locale("accepted", "button")), callback_data="nothing")]] @@ -80,7 +80,7 @@ async def callback_query_sponsor_no(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("sponsor_rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("sponsor_rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) await app.send_message(holo_user.id, locale("sponsor_rejected", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got sponsorship rejected by {clb.from_user.id}") diff --git a/modules/callbacks/sub.py b/modules/callbacks/sub.py index 9347798..b35b8fa 100644 --- a/modules/callbacks/sub.py +++ b/modules/callbacks/sub.py @@ -15,17 +15,17 @@ async def callback_query_accept(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) logWrite(f"User {holo_user.id} got approved by {clb.from_user.id}") need_link = True - async for member in app.get_chat_members(configGet("destination_group")): + async for member in app.get_chat_members(configGet("admin", "users")): if member.user.id == holo_user.id: need_link = False if need_link: - link = await app.create_chat_invite_link(configGet("destination_group"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) + link = await app.create_chat_invite_link(configGet("admin", "users"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) await app.send_message(holo_user.id, locale("read_rules", "message", locale=holo_user)) @@ -57,7 +57,7 @@ async def callback_query_reject(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) await app.send_message(holo_user.id, locale("rejected", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id}") @@ -74,7 +74,7 @@ async def callback_query_reject_aggressive(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("rejected_by_agr", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("rejected_by_agr", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) await app.send_message(holo_user.id, locale("rejected_aggressive", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id} due to being aggressive") @@ -91,7 +91,7 @@ async def callback_query_reject_russian(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("rejected_by_rus", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("rejected_by_rus", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) await app.send_message(holo_user.id, locale("rejected_russian", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id} due to being russian") diff --git a/modules/callbacks/sus.py b/modules/callbacks/sus.py index ae37ca1..b768448 100644 --- a/modules/callbacks/sus.py +++ b/modules/callbacks/sus.py @@ -13,7 +13,7 @@ async def callback_query_sus_allow(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("sus_allowed_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("sus_allowed_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) logWrite(f"User {holo_user.id} was allowed to join with another link by {clb.from_user.id}") edited_markup = [[InlineKeyboardButton(text=str(locale("sus_allowed", "button")), callback_data="nothing")]] @@ -21,7 +21,7 @@ async def callback_query_sus_allow(app: Client, clb: CallbackQuery): await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sus_allowed", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) - await app.restrict_chat_member(configGet("destination_group"), holo_user.id, permissions=ChatPermissions( + await app.restrict_chat_member(configGet("admin", "users"), holo_user.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, @@ -35,7 +35,7 @@ async def callback_query_sus_reject(app: Client, clb: CallbackQuery): fullclb = clb.data.split("_") holo_user = HoloUser(int(fullclb[2])) - await app.send_message(configGet("admin_group"), locale("sus_rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) + await app.send_message(configGet("admin", "groups"), locale("sus_rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) logWrite(f"User {holo_user.id} was rejected to join with another link by {clb.from_user.id}") edited_markup = [[InlineKeyboardButton(text=str(locale("sus_rejected", "button")), callback_data="nothing")]] @@ -43,7 +43,7 @@ async def callback_query_sus_reject(app: Client, clb: CallbackQuery): await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sus_rejected", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) - await app.ban_chat_member(configGet("destination_group"), holo_user.id) + await app.ban_chat_member(configGet("admin", "users"), holo_user.id) col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/application.py b/modules/commands/application.py index fc6556e..9e245f0 100644 --- a/modules/commands/application.py +++ b/modules/commands/application.py @@ -60,7 +60,7 @@ async def cmd_application(app: Client, msg: Message): # 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]): + # async for m in app.get_chat_members(configGet("admin", "users"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): # list_of_users.append(m) # user_id = list_of_users[0].user.id # try: diff --git a/modules/commands/nearby.py b/modules/commands/nearby.py index 5d2d5c3..f9c0275 100644 --- a/modules/commands/nearby.py +++ b/modules/commands/nearby.py @@ -11,7 +11,7 @@ from modules.database import col_applications, col_users from classes.errors.geo import PlaceNotFoundError # Nearby command =============================================================================================================== -@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & (filters.private | (filters.chat(configGet("admin_group")) | filters.chat(configGet("destination_group")))) & filters.command(["nearby"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & (filters.private | (filters.chat(configGet("admin", "groups")) | filters.chat(configGet("admin", "users")))) & filters.command(["nearby"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) async def cmd_nearby(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) diff --git a/modules/commands/reapply.py b/modules/commands/reapply.py index 7bd6d09..301113d 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -22,7 +22,7 @@ async def cmd_reapply(app: Client, msg: Message): left_chat = True - async for member in app.get_chat_members(configGet("destination_group")): + async for member in app.get_chat_members(configGet("admin", "users")): if member.user.id == msg.from_user.id: left_chat = False diff --git a/modules/commands/warn.py b/modules/commands/warn.py index 6399212..8f4a771 100644 --- a/modules/commands/warn.py +++ b/modules/commands/warn.py @@ -11,7 +11,7 @@ from modules import custom_filters @app.on_message(custom_filters.enabled_warnings & ~filters.scheduled & filters.command(["warn"], prefixes=["/"]) & custom_filters.admin) async def cmd_warn(app: Client, msg: Message): - if msg.chat.id == configGet("destination_group"): + if msg.chat.id == configGet("admin", "users"): if msg.reply_to_message_id != None: 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}) diff --git a/modules/commands/warnings.py b/modules/commands/warnings.py index 03fccfc..3323093 100644 --- a/modules/commands/warnings.py +++ b/modules/commands/warnings.py @@ -21,7 +21,7 @@ async def cmd_warnings(app: Client, msg: Message): 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]): + async for m in app.get_chat_members(configGet("admin", "users"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): list_of_users.append(m) if len(list_of_users) != 0: diff --git a/modules/handlers/confirmation.py b/modules/handlers/confirmation.py index b1c5fb7..76413d2 100644 --- a/modules/handlers/confirmation.py +++ b/modules/handlers/confirmation.py @@ -57,7 +57,7 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s i += 1 if tmp_application["reapply"]: - await app.send_message(chat_id=configGet("admin_group"), text=(locale("reapply_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( + await app.send_message(chat_id=configGet("admin", "groups"), text=(locale("reapply_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton(text=str(locale("reapply_yes", "button")), callback_data=f"reapply_yes_{holo_user.id}") @@ -69,7 +69,7 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s ) ) else: - await app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( + await app.send_message(chat_id=configGet("admin", "groups"), text=(locale("application_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(application_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton(text=str(locale("sub_yes", "button")), callback_data=f"sub_yes_{holo_user.id}") @@ -124,7 +124,7 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s else: sponsorship_content.append(f"{locale(f'question_{question}', 'message', 'sponsor_titles')} {tmp_sponsorship['sponsorship'][question]}") - await app.send_photo(chat_id=configGet("admin_group"), photo=f"tmp{sep}{filename}.jpg", caption=(locale("sponsor_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(sponsorship_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( + await app.send_photo(chat_id=configGet("admin", "groups"), photo=f"tmp{sep}{filename}.jpg", caption=(locale("sponsor_got", "message")).format(str(holo_user.id), msg.from_user.first_name, msg.from_user.username, "\n".join(sponsorship_content)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton(text=str(locale("sponsor_yes", "button")), callback_data=f"sponsor_yes_{holo_user.id}") diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index 0297ad3..fc834f4 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -120,7 +120,7 @@ async def any_stage(app: Client, msg: Message): @app.on_message(~ filters.scheduled & filters.group) async def message_in_group(app: Client, msg: Message): if (msg.chat is not None) and (msg.via_bot is not None): - if (msg.via_bot.id == (await app.get_me()).id) and (msg.chat.id == configGet("destination_group")): + if (msg.via_bot.id == (await app.get_me()).id) and (msg.chat.id == configGet("admin", "users")): if configGet("remove_application_time") > 0: logWrite(f"User {msg.from_user.id} requested application in destination group, removing in {configGet('remove_application_time')} minutes") await asyncio.sleep(configGet("remove_application_time")*60) diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index 82adfda..3ac1119 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -7,8 +7,8 @@ from classes.holo_user import HoloUser from modules import custom_filters # Filter users on join ========================================================================================================= -@app.on_chat_member_updated(custom_filters.enabled_invites_check, group=configGet("destination_group")) -#@app.on_message(filters.new_chat_members, group=configGet("destination_group")) +@app.on_chat_member_updated(custom_filters.enabled_invites_check, group=configGet("admin", "users")) +#@app.on_message(filters.new_chat_members, group=configGet("admin", "users")) async def filter_join(app: Client, member: ChatMemberUpdated): if member.invite_link != None: @@ -25,7 +25,7 @@ async def filter_join(app: Client, member: ChatMemberUpdated): logWrite(f"User {holo_user.id} joined destination group with stolen/unapproved link {holo_user.link}") - await app.send_message(configGet("admin_group"), locale("joined_false_link", "message").format(member.from_user.first_name, member.from_user.id), reply_markup=InlineKeyboardMarkup( + await app.send_message(configGet("admin", "groups"), locale("joined_false_link", "message").format(member.from_user.first_name, member.from_user.id), reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton(text=str(locale("sus_allow", "button")), callback_data=f"sus_allow_{member.from_user.id}") diff --git a/modules/handlers/voice.py b/modules/handlers/voice.py index 289fa03..f39dd22 100644 --- a/modules/handlers/voice.py +++ b/modules/handlers/voice.py @@ -7,7 +7,7 @@ from modules.logging import logWrite from modules.utils import configGet, locale from modules import custom_filters -@app.on_message(custom_filters.enabled_dinovoice & ~filters.scheduled & filters.voice & filters.chat(configGet("destination_group"))) +@app.on_message(custom_filters.enabled_dinovoice & ~filters.scheduled & filters.voice & filters.chat(configGet("admin", "users"))) async def voice_message(app: Client, msg: Message): logWrite(f"User {msg.from_user.id} sent voice message in destination group") await msg.reply_text(choice(locale("voice_message", "message"))) \ No newline at end of file diff --git a/modules/inline.py b/modules/inline.py index 0637c53..ac61ea9 100644 --- a/modules/inline.py +++ b/modules/inline.py @@ -51,7 +51,7 @@ async def inline_answer(client: Client, inline_query: InlineQuery): max_results = configGet("inline_preview_count") if inline_query.query != "" else 200 list_of_users = [] - async for m in app.get_chat_members(configGet("destination_group"), limit=max_results, filter=ChatMembersFilter.SEARCH, query=inline_query.query): + async for m in app.get_chat_members(configGet("admin", "users"), limit=max_results, filter=ChatMembersFilter.SEARCH, query=inline_query.query): list_of_users.append(m) results = [] diff --git a/modules/scheduled.py b/modules/scheduled.py index a012490..0bcccd6 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -19,7 +19,7 @@ if configGet("enabled", "scheduler", "cache_members"): @scheduler.scheduled_job(trigger="interval", seconds=configGet("interval", "scheduler", "cache_members")) async def cache_group_members(): list_of_users = [] - async for member in app.get_chat_members(configGet("destination_group")): + async for member in app.get_chat_members(configGet("admin", "users")): list_of_users.append(member.user.id) makedirs("cache", exist_ok=True) jsonSave(list_of_users, path.join(configGet("cache", "locations"), "group_members")) @@ -28,7 +28,7 @@ if configGet("enabled", "scheduler", "cache_admins"): @scheduler.scheduled_job(trigger="interval", seconds=configGet("interval", "scheduler", "cache_admins")) async def cache_admins(): list_of_users = [] - async for member in app.get_chat_members(configGet("admin_group")): + async for member in app.get_chat_members(configGet("admin", "groups")): list_of_users.append(member.user.id) makedirs("cache", exist_ok=True) jsonSave(list_of_users, path.join(configGet("cache", "locations"), "admins")) @@ -39,7 +39,7 @@ if configGet("enabled", "scheduler", "cache_avatars"): @scheduler.scheduled_job(trigger="interval", hours=configGet("interval", "scheduler", "cache_avatars")) async def cache_avatars(): list_of_users = [] - async for member in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=""): + async for member in app.get_chat_members(configGet("admin", "users"), filter=ChatMembersFilter.SEARCH, query=""): list_of_users.append(member.user) for user in list_of_users: if user.photo != None: @@ -58,7 +58,7 @@ if configGet("enabled", "features", "applications") is True: if entry["application"]["2"].strftime("%d.%m") == datetime.now().strftime("%d.%m"): try: tg_user = await app.get_users(entry["user"]) - await app.send_message( configGet("admin_group"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), entry["application"]["2"], '%d.%m.%Y').years)) ) # type: ignore + await app.send_message( configGet("admin", "groups"), locale("birthday", "message").format(str(tg_user.first_name), str(tg_user.username), str(relativedelta(datetime.now(), entry["application"]["2"], '%d.%m.%Y').years)) ) # type: ignore logWrite(f"Notified admins about {entry['user']}'s birthday") except Exception as exp: logWrite(f"Could not find user {entry['user']} to send a message about birthday due to '{exp}'") @@ -84,7 +84,7 @@ if configGet("enabled", "features", "sponsorships") is True: try: holo_user = HoloUser(entry["user"]) await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore - await holo_user.label_reset(configGet("destination_group")) + await holo_user.label_reset(configGet("admin", "users")) col_sponsorships.find_one_and_delete({"user": holo_user.id}) try: tg_user = await app.get_users(entry["user"]) @@ -165,14 +165,14 @@ async def commands_register(): # Registering admin group commands try: - await app.set_bot_commands(commands["group_admins"], scope=BotCommandScopeChat(chat_id=configGet("admin_group"))) + await app.set_bot_commands(commands["group_admins"], scope=BotCommandScopeChat(chat_id=configGet("admin", "groups"))) logWrite("Registered admin group commands for default locale") except bad_request_400.ChannelInvalid: logWrite(f"Could not register commands for admin group. Bot is likely not in the group.") # Registering destination group commands try: - await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("destination_group"))) + await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("admin", "users"))) logWrite("Registered destination group commands") except bad_request_400.ChannelInvalid: logWrite(f"Could not register commands for destination group. Bot is likely not in the group.") \ No newline at end of file From 3eef04794ac8a41a115a78ea78af709b1d34a3ef Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 19:58:54 +0100 Subject: [PATCH 14/27] Integration of spoilers [WIP] --- classes/holo_user.py | 12 +++++- config_example.json | 6 +++ holochecker.py | 3 ++ locale/uk.json | 33 +++++++++++++- modules/callbacks/sid.py | 10 +++++ modules/commands/cancel.py | 3 +- modules/commands/spoiler.py | 39 +++++++++++++++++ modules/commands/start.py | 18 +++++++- modules/custom_filters.py | 7 ++- modules/database.py | 3 +- modules/handlers/spoiler.py | 86 +++++++++++++++++++++++++++++++++++++ modules/inline.py | 39 +++++++++++++++-- 12 files changed, 247 insertions(+), 12 deletions(-) create mode 100644 modules/callbacks/sid.py create mode 100644 modules/commands/spoiler.py create mode 100644 modules/handlers/spoiler.py diff --git a/classes/holo_user.py b/classes/holo_user.py index 0c719a9..d0a4537 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -6,7 +6,7 @@ from pyrogram.types import User, ChatMember, ChatPrivileges, Chat, Message, Phot from pyrogram.errors import bad_request_400 from dateutil.relativedelta import relativedelta from classes.errors.geo import PlaceNotFoundError -from modules.database import col_tmp, col_users, col_applications, col_sponsorships, col_messages +from modules.database import col_tmp, col_users, col_applications, col_sponsorships, col_messages, col_spoilers from modules.logging import logWrite from modules.utils import configGet, create_tmp, download_tmp, find_location, locale, should_quote @@ -544,4 +544,12 @@ class HoloUser(): logWrite(f"User {self.id} completed stage {stage} of sponsorship") else: - return \ No newline at end of file + return + + def spoiler_state(self) -> bool: + """Check if user has any started but not finished spoilers + + ### Returns: + * `bool`: `True` if any not finished spoilers available and `False` if none. + """ + return False if col_spoilers.find_one({"user": self.id, "completed": False}) is None else True \ No newline at end of file diff --git a/config_example.json b/config_example.json index 34751e0..40f265c 100644 --- a/config_example.json +++ b/config_example.json @@ -87,6 +87,12 @@ "general" ] }, + "spoiler": { + "permissions": [ + "users", + "admins" + ] + }, "cancel": { "permissions": [ "users", diff --git a/holochecker.py b/holochecker.py index c2ad999..997357d 100644 --- a/holochecker.py +++ b/holochecker.py @@ -20,6 +20,7 @@ from modules.commands.nearby import * from modules.commands.reapply import * from modules.commands.reboot import * from modules.commands.rules import * +from modules.commands.spoiler import * from modules.commands.sponsorship import * from modules.commands.start import * from modules.commands.warn import * @@ -28,6 +29,7 @@ from modules.commands.warnings import * from modules.callbacks.nothing import * from modules.callbacks.reapply import * from modules.callbacks.rules import * +from modules.callbacks.sid import * from modules.callbacks.sponsorship import * from modules.callbacks.sub import * from modules.callbacks.sus import * @@ -35,6 +37,7 @@ from modules.callbacks.sus import * from modules.handlers.confirmation import * from modules.handlers.contact import * from modules.handlers.group_join import * +from modules.handlers.spoiler import * from modules.handlers.sponsorship import * from modules.handlers.voice import * from modules.handlers.welcome import * diff --git a/locale/uk.json b/locale/uk.json index c5674a8..2ebc1a0 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -100,6 +100,15 @@ "identify_invalid_syntax": "Неправильний синтаксис!\nТреба: `/identify ID/NAME/USERNAME`", "identify_not_found": "Не знайдено користувачів за запитом **{0}**", "identify_success": "Користувач `{0}`\n\nІм'я: {1}\nЮзернейм: {2}\nЄ в чаті: {3}\nЄ адміном: {4}\nРоль: {5}\nНаявна анкета: {6}\nНаявне спонсорство: {7}", + "spoiler_started": "Розпочато створення спойлера. Надішліть щось", + "spoiler_unfinished": "У вас ще є незавершений спойлер. Надішліть /cancel щоб зупинити його створення", + "spoiler_cancel": "Створення спойлера було припинено", + "spoiler_empty": "Спойлер без опису", + "spoiler_described": "Спойлер: {0}", + "spoiler_description_enter": "Добре, введіть бажаний опис спойлера", + "spoiler_using_description": "Встановлено опис спойлера: {0}", + "spoiler_send_description": "Майже впорались. Тепер треба надіслати коротенький опис спойлера, щоб люди розуміли що під ним варто очкувати. Надішли мінус (-) щоб пропустити цей крок.", + "spoiler_ready": "Успіх! Спойлер створено. Користуйтесь кнопкою нижче щоб надіслати його.", "yes": "Так", "no": "Ні", "voice_message": [ @@ -146,6 +155,17 @@ [ "Ні, повторно заповнити" ] + ], + "spoiler_description": [ + [ + "NSFW контент" + ], + [ + "Деанон холо-учасників" + ], + [ + "Інше (надішліть свій текст)" + ] ] }, "force_reply": { @@ -162,7 +182,9 @@ "sponsor1": "Ім'я дівчини", "sponsor2": "Дата до якої підписка", "sponsor3": "Фото-підтвердження", - "sponsor4": "Бажана роль" + "sponsor4": "Бажана роль", + "spoiler_content": "Вміст спойлера", + "spoiler_description": "Опис спойлера" }, "button": { "sub_yes": "✅ Прийняти", @@ -189,7 +211,9 @@ "applying_stop": "🛑 Перервати заповнення", "done": "✅ Готово", "sponsor_apply": "Заповнити форму", - "sponsor_started": "Форму розпочато" + "sponsor_started": "Форму розпочато", + "spoiler_send": "Надіслати", + "spoiler_view": "Переглянути" }, "callback": { "sub_accepted": "✅ Анкету {0} схвалено", @@ -222,6 +246,10 @@ "title": "", "description": "Переглянути анкету {0} (@{1})", "message_content": "{0} (@{1})\n\n**Дані анкети:**\n{2}" + }, + "spoiler": { + "title": "Відправити", + "description": "Надіслати цей спойлер до чату" } }, "rules_msg": "📢Правила можуть доповнюватись та змінюватись, залежно від потреби. У такому разі, порушення, які були вчинені до введення (змінення) правила, порушеннями вважатися не будуть. Про всі зміни в правилах, ви будете проінформовані за допомогою закріплених повідомлень. Але вони не будуть закріплені на постійній основі, тому, час від часу, перевіряйте актуальність правил у боті.\n\n🔔Якщо ви бачите, як хтось із учасників порушив правила, тегніть одного із адмінів, у відповідь на повідомлення, яке, на вашу думку, є порушенням. У дописі до тегу, вкажіть, по якому пункту ви побачили порушення. Або перешліть повідомлення до будь кого із адміністраторів у особисті повідомлення, та коротко опишіть ситуацію.\nСписок адміністраторів: @Chirkopol @Za_NerZula @Denialvapr\nЗ питань функціонування бота звертайтесь до @Profitroll2281337\n\n❗️Будь-який заборонений контент, може бути відправлений до чату за допомогою бота - https://t.me/spoilerobot з повним описом контенту, що міститься під спойлером. За неправильний або некоректний опис, може бути видане попередження.\n\n‼️Видалені або змінені повідомлення, все ще є повідомленнями від вашого імені, які могли побачити учасники чату, і які можуть бути відстежені через адмінську панель.\n\n🔨 За порушення - ви отримаєте попередження. За наявності 3-х попереджень - мут на добу. За повторні порушення, ви одразу отримаєте покарання, без додаткових попереджень.", @@ -248,6 +276,7 @@ "reapply": "Повторно заповнити анкету", "reboot": "Перезапустити бота", "rules": "Правила спільноти", + "spoiler": "Почати створювати спойлер", "sponsorship": "Отримати роль за спонсорство", "warn": "Попередити користувача", "warnings": "Переглянути попередження користувача" diff --git a/modules/callbacks/sid.py b/modules/callbacks/sid.py new file mode 100644 index 0000000..434690e --- /dev/null +++ b/modules/callbacks/sid.py @@ -0,0 +1,10 @@ +from app import app +from pyrogram.types import CallbackQuery +from pyrogram.client import Client +from pyrogram import filters + +# Callback rule ================================================================================================================ +@app.on_callback_query(filters.regex("sid_[\s\S]*")) +async def callback_query_rule(app: Client, clb: CallbackQuery): + await clb.answer(url=f'https://t.me/{(await app.get_me()).username}?start={clb.data.split("_")[1]}') +# ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/cancel.py b/modules/commands/cancel.py index 4880b2d..f0755af 100644 --- a/modules/commands/cancel.py +++ b/modules/commands/cancel.py @@ -3,11 +3,12 @@ from pyrogram import filters from pyrogram.types import Message from pyrogram.client import Client from modules.utils import should_quote, logWrite, locale -from modules.database import col_tmp +from modules.database import col_tmp, col_spoilers from modules import custom_filters @app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("cancel", prefixes=["/"])) async def command_cancel(app: Client, msg: Message): col_tmp.delete_many( {"user": msg.from_user.id} ) + col_spoilers.delete_many( {"user": msg.from_user.id, "completed": False} ) await msg.reply_text(locale("cancel", "message", locale=msg.from_user), quote=should_quote(msg)) logWrite(f"Cancelling all ongoing tmp operations for {msg.from_user.id}") \ No newline at end of file diff --git a/modules/commands/spoiler.py b/modules/commands/spoiler.py new file mode 100644 index 0000000..120ea40 --- /dev/null +++ b/modules/commands/spoiler.py @@ -0,0 +1,39 @@ +from app import app +from pyrogram import filters +from pyrogram.types import Message, ForceReply +from pyrogram.client import Client +from classes.holo_user import HoloUser, UserInvalidError, UserNotFoundError +from modules.utils import locale +from modules.database import col_spoilers +from modules import custom_filters + +# Spoiler command ============================================================================================================== +@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.command(["spoiler"], prefixes=["/"])) +async def cmd_spoiler(app: Client, msg: Message): + + try: + holo_user = HoloUser(msg.from_user) + except (UserInvalidError, UserNotFoundError): + return + + if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + + if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: + + col_spoilers.insert_one( + { + "user": msg.from_user.id, + "completed": False, + "description": None, + "photo": None, + "video": None, + "animation": None, + "text": None + } + ) + + await msg.reply_text(locale("spoiler_started", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_content", "force_reply", locale=msg.from_user))) + + else: + await msg.reply_text(locale("spoiler_unfinished", "message", locale=msg.from_user)) +# ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/start.py b/modules/commands/start.py index e51ac02..66cb464 100644 --- a/modules/commands/start.py +++ b/modules/commands/start.py @@ -3,8 +3,10 @@ from pyrogram import filters from pyrogram.types import ReplyKeyboardMarkup, Message from pyrogram.client import Client from modules.utils import locale, logWrite -from modules.database import col_users +from modules.database import col_users, col_spoilers from modules import custom_filters +from bson.objectid import ObjectId +from bson.errors import InvalidId # Start command ================================================================================================================ @app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"])) @@ -26,4 +28,18 @@ async def cmd_start(app: Client, msg: Message): logWrite(f"User {msg.from_user.id} started bot interaction") await msg.reply_text(locale("start", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("welcome", "keyboard", locale=msg.from_user), resize_keyboard=True)) + + if len(msg.command) > 1: + try: + spoiler = col_spoilers.find_one( {"_id": ObjectId(msg.command[1])} ) + if spoiler["photo"] is not None: + await msg.reply_photo(spoiler["photo"]) + if spoiler["video"] is not None: + await msg.reply_video(spoiler["video"]) + if spoiler["animation"] is not None: + await msg.reply_animation(spoiler["animation"]) + if spoiler["text"] is not None: + await msg.reply_text(spoiler["text"]) + except InvalidId: + await msg.reply_text(f"Got an invalid ID {msg.command[1]}") # ============================================================================================================================== \ No newline at end of file diff --git a/modules/custom_filters.py b/modules/custom_filters.py index dc54ef4..59baff2 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -1,8 +1,9 @@ """Custom message filters made to improve commands usage in context of Holo Users.""" +from os import path from app import isAnAdmin -from modules.utils import configGet +from modules.utils import configGet, jsonLoad from modules.database import col_applications from pyrogram import filters from pyrogram.types import Message @@ -10,6 +11,9 @@ from pyrogram.types import Message async def admin_func(_, __, msg: Message): return await isAnAdmin(msg.from_user.id) +async def member_func(_, __, msg: Message): + return True if (msg.from_user.id in jsonLoad(path.join(configGet("cache", "locations"), "group_members"))) else False + async def allowed_func(_, __, msg: Message): return True if (col_applications.find_one({"user": msg.from_user.id}) is not None) else False @@ -32,6 +36,7 @@ async def enabled_dinovoice_func(_, __, msg: Message): return configGet("enabled", "features", "dinovoice") admin = filters.create(admin_func) +member = filters.create(member_func) allowed = filters.create(allowed_func) enabled_general = filters.create(enabled_general_func) diff --git a/modules/database.py b/modules/database.py index f68db38..f518dc1 100644 --- a/modules/database.py +++ b/modules/database.py @@ -28,13 +28,14 @@ db = db_client.get_database(name=db_config["name"]) collections = db.list_collection_names() -for collection in ["tmp", "users", "context", "messages", "warnings", "applications", "sponsorships"]: +for collection in ["tmp", "users", "context", "spoilers", "messages", "warnings", "applications", "sponsorships"]: if not collection in collections: db.create_collection(collection) col_tmp = db.get_collection("tmp") col_users = db.get_collection("users") col_context = db.get_collection("context") +col_spoilers = db.get_collection("spoilers") col_messages = db.get_collection("messages") col_warnings = db.get_collection("warnings") col_applications = db.get_collection("applications") diff --git a/modules/handlers/spoiler.py b/modules/handlers/spoiler.py new file mode 100644 index 0000000..4e4c9e0 --- /dev/null +++ b/modules/handlers/spoiler.py @@ -0,0 +1,86 @@ +from app import app +from pyrogram import filters +from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, ForceReply, ReplyKeyboardMarkup, ReplyKeyboardRemove +from pyrogram.client import Client +from classes.holo_user import HoloUser, UserInvalidError, UserNotFoundError +from modules.utils import locale, all_locales +from modules.database import col_spoilers +from modules import custom_filters + +# Any other input ============================================================================================================== +@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.text) +async def handler_spoiler_text(app: Client, msg: Message): + + try: + holo_user = HoloUser(msg.from_user) + except (UserInvalidError, UserNotFoundError): + return + + if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + + spoiler = col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) + + if spoiler is None: + return + + if spoiler["photo"] is None and spoiler["video"] is None and spoiler["animation"] is None and spoiler["text"] is None: + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"text": msg.text}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + else: + for lc in all_locales("spoiler_description", "keyboard"): + if msg.text == lc[-1][0]: + await msg.reply_text(locale("spoiler_description_enter", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + return + if msg.text != "-": + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"description": msg.text, "completed": True}} ) + await msg.reply_text(locale("spoiler_using_description", "message", locale=msg.from_user).format(msg.text), reply_markup=ReplyKeyboardRemove()) + await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), quote=False, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_send", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}")]])) + +@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.photo) +async def handler_spoiler_photo(app: Client, msg: Message): + + try: + holo_user = HoloUser(msg.from_user) + except (UserInvalidError, UserNotFoundError): + return + + if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + + + if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: + return + + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"photo": msg.photo.file_id}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + +@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.video) +async def handler_spoiler_video(app: Client, msg: Message): + + try: + holo_user = HoloUser(msg.from_user) + except (UserInvalidError, UserNotFoundError): + return + + if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + + if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: + return + + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"video": msg.video.file_id}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + +@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.animation) +async def handler_spoiler_animation(app: Client, msg: Message): + + try: + holo_user = HoloUser(msg.from_user) + except (UserInvalidError, UserNotFoundError): + return + + if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + + if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: + return + + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"animation": msg.animation.file_id}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) \ No newline at end of file diff --git a/modules/inline.py b/modules/inline.py index ac61ea9..45e25aa 100644 --- a/modules/inline.py +++ b/modules/inline.py @@ -4,18 +4,51 @@ all inline queries that bot receives""" from datetime import datetime from os import path, sep from app import app, isAnAdmin -from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent, InlineQuery +from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent, InlineQuery, InlineKeyboardMarkup, InlineKeyboardButton 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 from classes.holo_user import HoloUser, UserInvalidError, UserNotFoundError from modules.utils import configGet, locale -from modules.database import col_applications +from modules.database import col_applications, col_spoilers +from bson.objectid import ObjectId +from bson.errors import InvalidId @app.on_inline_query() async def inline_answer(client: Client, inline_query: InlineQuery): + results = [] + + if inline_query.query.startswith("spoiler:"): + + try: + + spoil = col_spoilers.find_one( {"_id": ObjectId(inline_query.query.removeprefix("spoiler:"))} ) + + if spoil is not None: + + desc = locale("spoiler_empty", "message", locale=inline_query.from_user) if spoil["description"] is None else locale("spoiler_described", "message", locale=inline_query.from_user).format(spoil["description"]) + + results = [ + InlineQueryResultArticle( + title=locale("title", "inline", "spoiler", locale=inline_query.from_user), + description=locale("description", "inline", "spoiler", locale=inline_query.from_user), + input_message_content=InputTextMessageContent(desc, disable_web_page_preview=True), + reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_view", "button", locale=inline_query.from_user), callback_data=f'sid_{inline_query.query.removeprefix("spoiler:")}')]]) + ) + ] + + except InvalidId: + results = [] + + + await inline_query.answer( + results=results + ) + + return + if inline_query.chat_type in [ChatType.CHANNEL]: await inline_query.answer( results=[ @@ -54,8 +87,6 @@ async def inline_answer(client: Client, inline_query: InlineQuery): async for m in app.get_chat_members(configGet("admin", "users"), limit=max_results, filter=ChatMembersFilter.SEARCH, query=inline_query.query): list_of_users.append(m) - results = [] - for match in list_of_users: application = col_applications.find_one({"user": match.user.id}) From 3fd56e8b41c33df557557db1083e13eb9fa2e42e Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 19:59:09 +0100 Subject: [PATCH 15/27] Fixed a typo in config keys --- classes/holo_user.py | 8 ++++---- modules/callbacks/reapply.py | 4 ++-- modules/callbacks/sponsorship.py | 2 +- modules/callbacks/sub.py | 4 ++-- modules/callbacks/sus.py | 4 ++-- modules/commands/application.py | 2 +- modules/commands/nearby.py | 2 +- modules/commands/reapply.py | 2 +- modules/commands/warn.py | 2 +- modules/commands/warnings.py | 2 +- modules/handlers/everything.py | 2 +- modules/handlers/group_join.py | 4 ++-- modules/handlers/voice.py | 2 +- modules/inline.py | 2 +- modules/scheduled.py | 8 ++++---- 15 files changed, 25 insertions(+), 25 deletions(-) diff --git a/classes/holo_user.py b/classes/holo_user.py index d0a4537..d8f5ef8 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -284,9 +284,9 @@ class HoloUser(): raise LabelTooLongError(label) self.label = label try: - await app.promote_chat_member(configGet("admin", "users"), self.id, privileges=ChatPrivileges(can_pin_messages=True, can_manage_video_chats=True)) + await app.promote_chat_member(configGet("users", "groups"), self.id, privileges=ChatPrivileges(can_pin_messages=True, can_manage_video_chats=True)) if not await isAnAdmin(self.id): - await app.set_administrator_title(configGet("admin", "users"), self.id, label) + await app.set_administrator_title(configGet("users", "groups"), self.id, label) self.set("label", label) except bad_request_400.UserCreator: logWrite(f"Could not set {self.id}'s title to '{self.label}' because of bad_request_400.UserCreator") @@ -301,9 +301,9 @@ class HoloUser(): """ self.label = "" self.set("label", "") - await app.set_administrator_title(configGet("admin", "users"), self.id, "") + await app.set_administrator_title(configGet("users", "groups"), self.id, "") if not await isAnAdmin(self.id): - await app.promote_chat_member(configGet("admin", "users"), self.id, privileges=ChatPrivileges( + await app.promote_chat_member(configGet("users", "groups"), self.id, privileges=ChatPrivileges( can_manage_chat=False, can_pin_messages=False, can_manage_video_chats=False diff --git a/modules/callbacks/reapply.py b/modules/callbacks/reapply.py index 7cc599f..3f6a523 100644 --- a/modules/callbacks/reapply.py +++ b/modules/callbacks/reapply.py @@ -32,12 +32,12 @@ async def callback_reapply_query_accept(app: Client, clb: CallbackQuery): need_link = True - async for member in app.get_chat_members(configGet("admin", "users")): + async for member in app.get_chat_members(configGet("users", "groups")): if member.user.id == holo_user.id: need_link = False if need_link: - link = await app.create_chat_invite_link(configGet("admin", "users"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) + link = await app.create_chat_invite_link(configGet("users", "groups"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) await app.send_message(holo_user.id, locale("read_rules", "message", locale=holo_user)) diff --git a/modules/callbacks/sponsorship.py b/modules/callbacks/sponsorship.py index 37cc5bb..429aa2b 100644 --- a/modules/callbacks/sponsorship.py +++ b/modules/callbacks/sponsorship.py @@ -67,7 +67,7 @@ async def callback_query_sponsor_yes(app: Client, clb: CallbackQuery): } ) - await holo_user.label_set(configGet("admin", "users"), col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]["label"]) + await holo_user.label_set(configGet("users", "groups"), col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "sponsorship"}})["sponsorship"]["label"]) edited_markup = [[InlineKeyboardButton(text=str(locale("accepted", "button")), callback_data="nothing")]] diff --git a/modules/callbacks/sub.py b/modules/callbacks/sub.py index b35b8fa..eb76d06 100644 --- a/modules/callbacks/sub.py +++ b/modules/callbacks/sub.py @@ -20,12 +20,12 @@ async def callback_query_accept(app: Client, clb: CallbackQuery): need_link = True - async for member in app.get_chat_members(configGet("admin", "users")): + async for member in app.get_chat_members(configGet("users", "groups")): if member.user.id == holo_user.id: need_link = False if need_link: - link = await app.create_chat_invite_link(configGet("admin", "users"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) + link = await app.create_chat_invite_link(configGet("users", "groups"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) await app.send_message(holo_user.id, locale("read_rules", "message", locale=holo_user)) diff --git a/modules/callbacks/sus.py b/modules/callbacks/sus.py index b768448..a01da45 100644 --- a/modules/callbacks/sus.py +++ b/modules/callbacks/sus.py @@ -21,7 +21,7 @@ async def callback_query_sus_allow(app: Client, clb: CallbackQuery): await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sus_allowed", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) - await app.restrict_chat_member(configGet("admin", "users"), holo_user.id, permissions=ChatPermissions( + await app.restrict_chat_member(configGet("users", "groups"), holo_user.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, @@ -43,7 +43,7 @@ async def callback_query_sus_reject(app: Client, clb: CallbackQuery): await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sus_rejected", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) - await app.ban_chat_member(configGet("admin", "users"), holo_user.id) + await app.ban_chat_member(configGet("users", "groups"), holo_user.id) col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/application.py b/modules/commands/application.py index 9e245f0..46b0122 100644 --- a/modules/commands/application.py +++ b/modules/commands/application.py @@ -60,7 +60,7 @@ async def cmd_application(app: Client, msg: Message): # user_id = int(msg.command[1]) # else: # list_of_users = [] - # async for m in app.get_chat_members(configGet("admin", "users"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): + # async for m in app.get_chat_members(configGet("users", "groups"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): # list_of_users.append(m) # user_id = list_of_users[0].user.id # try: diff --git a/modules/commands/nearby.py b/modules/commands/nearby.py index f9c0275..6ef09de 100644 --- a/modules/commands/nearby.py +++ b/modules/commands/nearby.py @@ -11,7 +11,7 @@ from modules.database import col_applications, col_users from classes.errors.geo import PlaceNotFoundError # Nearby command =============================================================================================================== -@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & (filters.private | (filters.chat(configGet("admin", "groups")) | filters.chat(configGet("admin", "users")))) & filters.command(["nearby"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & (filters.private | (filters.chat(configGet("admin", "groups")) | filters.chat(configGet("users", "groups")))) & filters.command(["nearby"], prefixes=["/"]) & (custom_filters.allowed | custom_filters.admin)) async def cmd_nearby(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) diff --git a/modules/commands/reapply.py b/modules/commands/reapply.py index 301113d..35f7467 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -22,7 +22,7 @@ async def cmd_reapply(app: Client, msg: Message): left_chat = True - async for member in app.get_chat_members(configGet("admin", "users")): + async for member in app.get_chat_members(configGet("users", "groups")): if member.user.id == msg.from_user.id: left_chat = False diff --git a/modules/commands/warn.py b/modules/commands/warn.py index 8f4a771..3482eaf 100644 --- a/modules/commands/warn.py +++ b/modules/commands/warn.py @@ -11,7 +11,7 @@ from modules import custom_filters @app.on_message(custom_filters.enabled_warnings & ~filters.scheduled & filters.command(["warn"], prefixes=["/"]) & custom_filters.admin) async def cmd_warn(app: Client, msg: Message): - if msg.chat.id == configGet("admin", "users"): + if msg.chat.id == configGet("users", "groups"): if msg.reply_to_message_id != None: 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}) diff --git a/modules/commands/warnings.py b/modules/commands/warnings.py index 3323093..a25e734 100644 --- a/modules/commands/warnings.py +++ b/modules/commands/warnings.py @@ -21,7 +21,7 @@ async def cmd_warnings(app: Client, msg: Message): target_name = user_db["tg_name"] except: list_of_users = [] - async for m in app.get_chat_members(configGet("admin", "users"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): + async for m in app.get_chat_members(configGet("users", "groups"), filter=ChatMembersFilter.SEARCH, query=msg.command[1]): list_of_users.append(m) if len(list_of_users) != 0: diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index fc834f4..f2b2273 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -120,7 +120,7 @@ async def any_stage(app: Client, msg: Message): @app.on_message(~ filters.scheduled & filters.group) async def message_in_group(app: Client, msg: Message): if (msg.chat is not None) and (msg.via_bot is not None): - if (msg.via_bot.id == (await app.get_me()).id) and (msg.chat.id == configGet("admin", "users")): + if (msg.via_bot.id == (await app.get_me()).id) and (msg.chat.id == configGet("users", "groups")): if configGet("remove_application_time") > 0: logWrite(f"User {msg.from_user.id} requested application in destination group, removing in {configGet('remove_application_time')} minutes") await asyncio.sleep(configGet("remove_application_time")*60) diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index 3ac1119..2ee00a6 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -7,8 +7,8 @@ from classes.holo_user import HoloUser from modules import custom_filters # Filter users on join ========================================================================================================= -@app.on_chat_member_updated(custom_filters.enabled_invites_check, group=configGet("admin", "users")) -#@app.on_message(filters.new_chat_members, group=configGet("admin", "users")) +@app.on_chat_member_updated(custom_filters.enabled_invites_check, group=configGet("users", "groups")) +#@app.on_message(filters.new_chat_members, group=configGet("users", "groups")) async def filter_join(app: Client, member: ChatMemberUpdated): if member.invite_link != None: diff --git a/modules/handlers/voice.py b/modules/handlers/voice.py index f39dd22..abdb4ac 100644 --- a/modules/handlers/voice.py +++ b/modules/handlers/voice.py @@ -7,7 +7,7 @@ from modules.logging import logWrite from modules.utils import configGet, locale from modules import custom_filters -@app.on_message(custom_filters.enabled_dinovoice & ~filters.scheduled & filters.voice & filters.chat(configGet("admin", "users"))) +@app.on_message(custom_filters.enabled_dinovoice & ~filters.scheduled & filters.voice & filters.chat(configGet("users", "groups"))) async def voice_message(app: Client, msg: Message): logWrite(f"User {msg.from_user.id} sent voice message in destination group") await msg.reply_text(choice(locale("voice_message", "message"))) \ No newline at end of file diff --git a/modules/inline.py b/modules/inline.py index 45e25aa..2f30ac2 100644 --- a/modules/inline.py +++ b/modules/inline.py @@ -84,7 +84,7 @@ async def inline_answer(client: Client, inline_query: InlineQuery): max_results = configGet("inline_preview_count") if inline_query.query != "" else 200 list_of_users = [] - async for m in app.get_chat_members(configGet("admin", "users"), limit=max_results, filter=ChatMembersFilter.SEARCH, query=inline_query.query): + async for m in app.get_chat_members(configGet("users", "groups"), limit=max_results, filter=ChatMembersFilter.SEARCH, query=inline_query.query): list_of_users.append(m) for match in list_of_users: diff --git a/modules/scheduled.py b/modules/scheduled.py index 0bcccd6..b5f954f 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -19,7 +19,7 @@ if configGet("enabled", "scheduler", "cache_members"): @scheduler.scheduled_job(trigger="interval", seconds=configGet("interval", "scheduler", "cache_members")) async def cache_group_members(): list_of_users = [] - async for member in app.get_chat_members(configGet("admin", "users")): + async for member in app.get_chat_members(configGet("users", "groups")): list_of_users.append(member.user.id) makedirs("cache", exist_ok=True) jsonSave(list_of_users, path.join(configGet("cache", "locations"), "group_members")) @@ -39,7 +39,7 @@ if configGet("enabled", "scheduler", "cache_avatars"): @scheduler.scheduled_job(trigger="interval", hours=configGet("interval", "scheduler", "cache_avatars")) async def cache_avatars(): list_of_users = [] - async for member in app.get_chat_members(configGet("admin", "users"), filter=ChatMembersFilter.SEARCH, query=""): + async for member in app.get_chat_members(configGet("users", "groups"), filter=ChatMembersFilter.SEARCH, query=""): list_of_users.append(member.user) for user in list_of_users: if user.photo != None: @@ -84,7 +84,7 @@ if configGet("enabled", "features", "sponsorships") is True: try: holo_user = HoloUser(entry["user"]) await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore - await holo_user.label_reset(configGet("admin", "users")) + await holo_user.label_reset(configGet("users", "groups")) col_sponsorships.find_one_and_delete({"user": holo_user.id}) try: tg_user = await app.get_users(entry["user"]) @@ -172,7 +172,7 @@ async def commands_register(): # Registering destination group commands try: - await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("admin", "users"))) + await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("users", "groups"))) logWrite("Registered destination group commands") except bad_request_400.ChannelInvalid: logWrite(f"Could not register commands for destination group. Bot is likely not in the group.") \ No newline at end of file From 6b80b7d0fa124b9057d8cd3ffe16b70b9a1a9249 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 20:13:29 +0100 Subject: [PATCH 16/27] Improved handlers --- classes/holo_user.py | 3 ++ holochecker.py | 21 --------- modules/handlers/everything.py | 39 +++++++++++++-- modules/handlers/spoiler.py | 86 ---------------------------------- 4 files changed, 39 insertions(+), 110 deletions(-) delete mode 100644 modules/handlers/spoiler.py diff --git a/classes/holo_user.py b/classes/holo_user.py index d8f5ef8..7b19a5f 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -351,6 +351,9 @@ class HoloUser(): if self.sponsorship_state()[0] == "fill": return + if self.spoiler_state() is True: + return + # col_tmp.insert_one( # document=DefaultApplicationTemp(self.id).dict # ) diff --git a/holochecker.py b/holochecker.py index 997357d..92b504a 100644 --- a/holochecker.py +++ b/holochecker.py @@ -37,7 +37,6 @@ from modules.callbacks.sus import * from modules.handlers.confirmation import * from modules.handlers.contact import * from modules.handlers.group_join import * -from modules.handlers.spoiler import * from modules.handlers.sponsorship import * from modules.handlers.voice import * from modules.handlers.welcome import * @@ -53,26 +52,6 @@ if __name__ == "__main__": # I did compare performance, almost no difference and it's much more useful this way. Change my mind. app.start() - # if configGet("birthdays_notify"): - - # every().day.at(configGet("birthdays_time")).do(check_birthdays, app) - - # # Background tasks checker - # def background_task(): - # try: - # while True: - # try: - # run_pending() - # #print('Checked') - # time.sleep(1) - # except: - # pass - # except KeyboardInterrupt: - # print('\nShutting down') - # killProc(pid) - # t = Thread(target=background_task) - # t.start() - try: app.send_message(configGet("owner"), f"Starting up with pid `{pid}`") except bad_request_400.PeerIdInvalid: diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index f2b2273..6de82e8 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -1,11 +1,11 @@ from app import app, isAnAdmin import asyncio from pyrogram import filters -from pyrogram.types import Message +from pyrogram.types import Message, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply, InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.client import Client from classes.holo_user import HoloUser -from modules.utils import configGet, logWrite -from modules.database import col_messages +from modules.utils import configGet, logWrite, locale, all_locales +from modules.database import col_messages, col_spoilers async def message_involved(msg: Message) -> bool: message = col_messages.find_one({"destination.id": msg.reply_to_message.id, "destination.chat": msg.reply_to_message.chat.id}) @@ -58,6 +58,39 @@ async def any_stage(app: Client, msg: Message): if configGet("enabled", "features", "sponsorships") is True: await holo_user.sponsorship_next(msg.text, msg=msg) + + if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + + spoiler = col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) + + if spoiler is None: + return + + if msg.photo is not None: + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"photo": msg.photo.file_id}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + return + elif msg.video is not None: + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"video": msg.video.file_id}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + return + elif msg.animation is not None: + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"animation": msg.animation.file_id}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + return + + if spoiler["photo"] is None and spoiler["video"] is None and spoiler["animation"] is None and spoiler["text"] is None: + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"text": msg.text}} ) + await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + else: + for lc in all_locales("spoiler_description", "keyboard"): + if msg.text == lc[-1][0]: + await msg.reply_text(locale("spoiler_description_enter", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + return + if msg.text != "-": + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"description": msg.text, "completed": True}} ) + await msg.reply_text(locale("spoiler_using_description", "message", locale=msg.from_user).format(msg.text), reply_markup=ReplyKeyboardRemove()) + await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), quote=False, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_send", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}")]])) # user_stage = configGet("stage", file=str(msg.from_user.id)) diff --git a/modules/handlers/spoiler.py b/modules/handlers/spoiler.py deleted file mode 100644 index 4e4c9e0..0000000 --- a/modules/handlers/spoiler.py +++ /dev/null @@ -1,86 +0,0 @@ -from app import app -from pyrogram import filters -from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, ForceReply, ReplyKeyboardMarkup, ReplyKeyboardRemove -from pyrogram.client import Client -from classes.holo_user import HoloUser, UserInvalidError, UserNotFoundError -from modules.utils import locale, all_locales -from modules.database import col_spoilers -from modules import custom_filters - -# Any other input ============================================================================================================== -@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.text) -async def handler_spoiler_text(app: Client, msg: Message): - - try: - holo_user = HoloUser(msg.from_user) - except (UserInvalidError, UserNotFoundError): - return - - if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": - - spoiler = col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) - - if spoiler is None: - return - - if spoiler["photo"] is None and spoiler["video"] is None and spoiler["animation"] is None and spoiler["text"] is None: - col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"text": msg.text}} ) - await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) - else: - for lc in all_locales("spoiler_description", "keyboard"): - if msg.text == lc[-1][0]: - await msg.reply_text(locale("spoiler_description_enter", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) - return - if msg.text != "-": - col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"description": msg.text, "completed": True}} ) - await msg.reply_text(locale("spoiler_using_description", "message", locale=msg.from_user).format(msg.text), reply_markup=ReplyKeyboardRemove()) - await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), quote=False, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_send", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}")]])) - -@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.photo) -async def handler_spoiler_photo(app: Client, msg: Message): - - try: - holo_user = HoloUser(msg.from_user) - except (UserInvalidError, UserNotFoundError): - return - - if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": - - - if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: - return - - col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"photo": msg.photo.file_id}} ) - await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) - -@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.video) -async def handler_spoiler_video(app: Client, msg: Message): - - try: - holo_user = HoloUser(msg.from_user) - except (UserInvalidError, UserNotFoundError): - return - - if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": - - if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: - return - - col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"video": msg.video.file_id}} ) - await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) - -@app.on_message(custom_filters.member & ~filters.scheduled & filters.private & filters.animation) -async def handler_spoiler_animation(app: Client, msg: Message): - - try: - holo_user = HoloUser(msg.from_user) - except (UserInvalidError, UserNotFoundError): - return - - if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": - - if col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) is None: - return - - col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"animation": msg.animation.file_id}} ) - await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) \ No newline at end of file From 0214a29a2ed02b3ecf2bdd7dca3ce06300f407c6 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 21:55:50 +0100 Subject: [PATCH 17/27] Fixed handlers --- holochecker.py | 2 +- modules/handlers/everything.py | 17 +++++++++++++++-- modules/handlers/sponsorship.py | 5 +++-- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/holochecker.py b/holochecker.py index 92b504a..46abed3 100644 --- a/holochecker.py +++ b/holochecker.py @@ -37,9 +37,9 @@ from modules.callbacks.sus import * from modules.handlers.confirmation import * from modules.handlers.contact import * from modules.handlers.group_join import * -from modules.handlers.sponsorship import * from modules.handlers.voice import * from modules.handlers.welcome import * +from modules.handlers.sponsorship import * from modules.handlers.everything import * from modules.scheduled import * diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index 6de82e8..db22879 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -69,19 +69,25 @@ async def any_stage(app: Client, msg: Message): if msg.photo is not None: col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"photo": msg.photo.file_id}} ) await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + logWrite(f"Adding photo with id {msg.photo.file_id} to {msg.from_user.id}'s spoiler") return - elif msg.video is not None: + + if msg.video is not None: col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"video": msg.video.file_id}} ) await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + logWrite(f"Adding video with id {msg.video.file_id} to {msg.from_user.id}'s spoiler") return - elif msg.animation is not None: + + if msg.animation is not None: col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"animation": msg.animation.file_id}} ) await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + logWrite(f"Adding animation with id {msg.animation.file_id} to {msg.from_user.id}'s spoiler") return if spoiler["photo"] is None and spoiler["video"] is None and spoiler["animation"] is None and spoiler["text"] is None: col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"text": msg.text}} ) await msg.reply_text(locale("spoiler_send_description", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("spoiler_description", "keyboard"), resize_keyboard=True, one_time_keyboard=True, placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) + logWrite(f"Adding text '{msg.text}' to {msg.from_user.id}'s spoiler") else: for lc in all_locales("spoiler_description", "keyboard"): if msg.text == lc[-1][0]: @@ -89,6 +95,7 @@ async def any_stage(app: Client, msg: Message): return if msg.text != "-": col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"description": msg.text, "completed": True}} ) + logWrite(f"Adding description '{msg.text}' to {msg.from_user.id}'s spoiler") await msg.reply_text(locale("spoiler_using_description", "message", locale=msg.from_user).format(msg.text), reply_markup=ReplyKeyboardRemove()) await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), quote=False, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_send", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}")]])) @@ -154,6 +161,12 @@ async def any_stage(app: Client, msg: Message): async def message_in_group(app: Client, msg: Message): if (msg.chat is not None) and (msg.via_bot is not None): if (msg.via_bot.id == (await app.get_me()).id) and (msg.chat.id == configGet("users", "groups")): + if msg.text.startswith(locale("spoiler_described", "message").split()[0]) or msg.text.startswith(locale("spoiler_empty", "message").split()[0]): + try: + await msg.forward(configGet("users", "groups"), disable_notification=True) + except: + pass + return if configGet("remove_application_time") > 0: logWrite(f"User {msg.from_user.id} requested application in destination group, removing in {configGet('remove_application_time')} minutes") await asyncio.sleep(configGet("remove_application_time")*60) diff --git a/modules/handlers/sponsorship.py b/modules/handlers/sponsorship.py index 0c9c7d1..4021cf0 100644 --- a/modules/handlers/sponsorship.py +++ b/modules/handlers/sponsorship.py @@ -5,11 +5,12 @@ from pyrogram.client import Client from classes.holo_user import HoloUser from modules import custom_filters -@app.on_message(custom_filters.enabled_sponsorships & ~filters.scheduled & filters.photo & filters.private) +@app.on_message(custom_filters.enabled_sponsorships & custom_filters.filling_sponsorship & ~filters.scheduled & filters.private) async def sponsor_proof(app: Client, msg: Message): if msg.via_bot is None: holo_user = HoloUser(msg.from_user) - await holo_user.sponsorship_next(msg.text, msg=msg, photo=msg.photo) \ No newline at end of file + if msg.photo is not None: + await holo_user.sponsorship_next(msg.text, msg=msg, photo=msg.photo) \ No newline at end of file From 0739eeb87db2dbea4cb44d29c76fb30795717ffd Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 21:56:37 +0100 Subject: [PATCH 18/27] Updated config --- README.md | 15 ++++++++++++++- config_example.json | 9 ++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ece51c1..440da24 100644 --- a/README.md +++ b/README.md @@ -72,13 +72,16 @@ You can see config file with all the comments below: "enabled": true }, "warnings": { - "enabled": false + "enabled": true }, "invites_check": { "enabled": true }, "dinovoice": { "enabled": false + }, + "spoilers": { + "enabled": true } }, "scheduler": { @@ -117,12 +120,22 @@ You can see config file with all the comments below: "general" ] }, + "spoiler": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "spoilers" + ] + }, "cancel": { "permissions": [ "users", "admins" ], "modules": [ + "spoilers", "applications", "sponsorships" ] diff --git a/config_example.json b/config_example.json index 40f265c..5803272 100644 --- a/config_example.json +++ b/config_example.json @@ -42,13 +42,16 @@ "enabled": true }, "warnings": { - "enabled": false + "enabled": true }, "invites_check": { "enabled": true }, "dinovoice": { "enabled": false + }, + "spoilers": { + "enabled": true } }, "scheduler": { @@ -91,6 +94,9 @@ "permissions": [ "users", "admins" + ], + "modules": [ + "spoilers" ] }, "cancel": { @@ -99,6 +105,7 @@ "admins" ], "modules": [ + "spoilers", "applications", "sponsorships" ] From 4977b8f31a437bad6760da8ee533a8b4d0418117 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 21:56:54 +0100 Subject: [PATCH 19/27] Updated to-do list --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 440da24..d83d4fa 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,7 @@ After all of that you're good to go! Happy using :) * [ ] Stats and infographics * [ ] Check group members without completed application -* [ ] Replicate some functions of @spoilerobot +* [x] Replicate some functions of @spoilerobot * [x] Check sponsorship on Holo girls * [x] /nearby command * [x] Complete messenger between user and admins From 9431763e6b69bbb4c2450442299db9908a138ae0 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 21:57:11 +0100 Subject: [PATCH 20/27] Added filling_sponsorship filter --- modules/custom_filters.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/custom_filters.py b/modules/custom_filters.py index 59baff2..808965f 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -4,7 +4,7 @@ usage in context of Holo Users.""" from os import path from app import isAnAdmin from modules.utils import configGet, jsonLoad -from modules.database import col_applications +from modules.database import col_applications, col_tmp from pyrogram import filters from pyrogram.types import Message @@ -35,6 +35,9 @@ async def enabled_invites_check_func(_, __, msg: Message): async def enabled_dinovoice_func(_, __, msg: Message): return configGet("enabled", "features", "dinovoice") +async def filling_sponsorship_func(_, __, msg: Message): + return True if col_tmp.find_one({"user": msg.from_user.id, "type": "sponsorship"}) is not None else False + admin = filters.create(admin_func) member = filters.create(member_func) allowed = filters.create(allowed_func) @@ -44,4 +47,6 @@ enabled_applications = filters.create(enabled_applications_func) enabled_sponsorships = filters.create(enabled_sponsorships_func) enabled_warnings = filters.create(enabled_warnings_func) enabled_invites_check = filters.create(enabled_invites_check_func) -enabled_dinovoice = filters.create(enabled_dinovoice_func) \ No newline at end of file +enabled_dinovoice = filters.create(enabled_dinovoice_func) + +filling_sponsorship = filters.create(filling_sponsorship_func) \ No newline at end of file From b437092fe73aac7be2258b0da3c0f2284d031d85 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 21:58:20 +0100 Subject: [PATCH 21/27] Trying to find commands registration issue --- modules/scheduled.py | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index b5f954f..c564211 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -4,6 +4,7 @@ some scheduled tasks is the main idea of this module""" from os import listdir, makedirs, path, sep from apscheduler.schedulers.asyncio import AsyncIOScheduler from datetime import datetime, timedelta +from ujson import dumps from app import app from pyrogram.types import BotCommand, BotCommandScopeChat from pyrogram.errors import bad_request_400 @@ -109,6 +110,14 @@ async def commands_register(): "locales": {} } + commands_raw = { + "users": [], + "admins": [], + "group_users": [], + "group_admins": [], + "locales": {} + } + valid_locales = [] files_locales = listdir(f'{configGet("locale", "locations")}') @@ -121,6 +130,13 @@ async def commands_register(): "group_users": [], "group_admins": [] } + if configGet("debug") is True: + commands_raw["locales"][".".join(entry.split(".")[:-1])] = { + "users": [], + "admins": [], + "group_users": [], + "group_admins": [] + } config_modules = configGet("features") config_commands = configGet("commands") @@ -135,13 +151,26 @@ async def commands_register(): enabled = True if enabled is False: + if configGet("debug") is True: + logWrite(f"Not registering {command} at all") continue for permission in config_commands[command]["permissions"]: + commands[permission].append(BotCommand(command, locale("commands")[command])) + + if configGet("debug") is True: + commands_raw[permission].append({f"{command}": locale("commands")[command]}) + logWrite(f"Registering {command} for {permission}") + for lc in valid_locales: + commands["locales"][lc][permission].append(BotCommand(command, locale("commands", locale=lc)[command])) + if configGet("debug") is True: + commands_raw["locales"][lc][permission].append({f"{command}": locale("commands", locale=lc)[command]}) + logWrite(f"Registering {command} for {permission} [{lc}]") + # Registering user commands await app.set_bot_commands(commands["users"]) @@ -155,7 +184,7 @@ async def commands_register(): # Registering admin/owner commands for admin in configGet("admins")+[configGet("owner")]: try: - await app.set_bot_commands(commands["admins"], scope=BotCommandScopeChat(chat_id=admin)) + await app.set_bot_commands(commands["admins"]+commands["users"], scope=BotCommandScopeChat(chat_id=admin)) if admin == configGet("owner"): logWrite(f"Registered admin commands for owner {configGet('owner')}") else: @@ -175,4 +204,8 @@ async def commands_register(): await app.set_bot_commands(commands["group_users"], scope=BotCommandScopeChat(chat_id=configGet("users", "groups"))) logWrite("Registered destination group commands") except bad_request_400.ChannelInvalid: - logWrite(f"Could not register commands for destination group. Bot is likely not in the group.") \ No newline at end of file + logWrite(f"Could not register commands for destination group. Bot is likely not in the group.") + + + if configGet("debug") is True: + logWrite(f"Complete commands registration:\n{dumps(commands_raw, indent=4, ensure_ascii=False, encode_html_chars=False)}") \ No newline at end of file From 496bb7d4a663285f9a04bd5c31abbcd22c42cb3d Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 21:58:44 +0100 Subject: [PATCH 22/27] Improved logging --- modules/commands/spoiler.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/commands/spoiler.py b/modules/commands/spoiler.py index 120ea40..3239178 100644 --- a/modules/commands/spoiler.py +++ b/modules/commands/spoiler.py @@ -3,6 +3,7 @@ from pyrogram import filters from pyrogram.types import Message, ForceReply from pyrogram.client import Client from classes.holo_user import HoloUser, UserInvalidError, UserNotFoundError +from modules.logging import logWrite from modules.utils import locale from modules.database import col_spoilers from modules import custom_filters @@ -33,6 +34,7 @@ async def cmd_spoiler(app: Client, msg: Message): ) await msg.reply_text(locale("spoiler_started", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_content", "force_reply", locale=msg.from_user))) + logWrite(f"User {msg.from_user.id} started creating new spoiler") else: await msg.reply_text(locale("spoiler_unfinished", "message", locale=msg.from_user)) From bdb2338ab9149d796d3e15fdaf65f0c944bd0251 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 4 Jan 2023 22:31:58 +0100 Subject: [PATCH 23/27] Still debugging --- modules/scheduled.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index c564211..4ded913 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -182,9 +182,9 @@ async def commands_register(): logWrite(f"Registered user commands for locale {lc}") # Registering admin/owner commands - for admin in configGet("admins")+[configGet("owner")]: + for admin in configGet("admins").extend([configGet("owner")]): try: - await app.set_bot_commands(commands["admins"]+commands["users"], scope=BotCommandScopeChat(chat_id=admin)) + await app.set_bot_commands(commands["admins"].extend(commands["users"]), scope=BotCommandScopeChat(chat_id=admin)) if admin == configGet("owner"): logWrite(f"Registered admin commands for owner {configGet('owner')}") else: @@ -208,4 +208,5 @@ async def commands_register(): if configGet("debug") is True: + print(commands, flush=True) logWrite(f"Complete commands registration:\n{dumps(commands_raw, indent=4, ensure_ascii=False, encode_html_chars=False)}") \ No newline at end of file From c90495eb1c1884081ff21ae984f765011dc5c7ac Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 5 Jan 2023 10:49:22 +0100 Subject: [PATCH 24/27] Added spoiler's validation rule --- validation/spoilers.json | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 validation/spoilers.json diff --git a/validation/spoilers.json b/validation/spoilers.json new file mode 100644 index 0000000..1837cbb --- /dev/null +++ b/validation/spoilers.json @@ -0,0 +1,43 @@ +{ + "$jsonSchema": { + "required": [ + "user", + "completed", + "description", + "photo", + "video", + "animation", + "text" + ], + "properties": { + "user": { + "bsonType": ["int", "long"], + "description": "Telegram ID of user" + }, + "completed": { + "bsonType": "bool", + "description": "Whether spoiler is a completed one" + }, + "description": { + "bsonType": ["string", "null"], + "description": "Spoiler's description" + }, + "photo": { + "bsonType": ["string", "null"], + "description": "Spoilered photo" + }, + "video": { + "bsonType": ["string", "null"], + "description": "Spoilered video" + }, + "animation": { + "bsonType": ["string", "null"], + "description": "Spoilered animation/GIF" + }, + "text": { + "bsonType": ["string", "null"], + "description": "Spoilered text" + } + } + } +} \ No newline at end of file From 19fc9308e41e2eff6e7d2528d1e3976e9ad548d9 Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 5 Jan 2023 12:41:55 +0100 Subject: [PATCH 25/27] Added /resetcommands command --- config_example.json | 11 +++++- holochecker.py | 1 + locale/uk.json | 1 + modules/commands/resetcommands.py | 65 +++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 modules/commands/resetcommands.py diff --git a/config_example.json b/config_example.json index 5803272..5080175 100644 --- a/config_example.json +++ b/config_example.json @@ -149,8 +149,7 @@ }, "reboot": { "permissions": [ - "admins", - "group_admins" + "owner" ], "modules": [ "general" @@ -201,6 +200,14 @@ "modules": [ "applications" ] + }, + "resetcommands": { + "permissions": [ + "owner" + ], + "modules": [ + "general" + ] } } } \ No newline at end of file diff --git a/holochecker.py b/holochecker.py index 46abed3..63bf2fc 100644 --- a/holochecker.py +++ b/holochecker.py @@ -19,6 +19,7 @@ from modules.commands.message import * from modules.commands.nearby import * from modules.commands.reapply import * from modules.commands.reboot import * +from modules.commands.resetcommands import * from modules.commands.rules import * from modules.commands.spoiler import * from modules.commands.sponsorship import * diff --git a/locale/uk.json b/locale/uk.json index 2ebc1a0..ab8091d 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -275,6 +275,7 @@ "nearby": "Показати користувачів поблизу", "reapply": "Повторно заповнити анкету", "reboot": "Перезапустити бота", + "resetcommands": "Відреєструвати всі команди", "rules": "Правила спільноти", "spoiler": "Почати створювати спойлер", "sponsorship": "Отримати роль за спонсорство", diff --git a/modules/commands/resetcommands.py b/modules/commands/resetcommands.py new file mode 100644 index 0000000..9ed0657 --- /dev/null +++ b/modules/commands/resetcommands.py @@ -0,0 +1,65 @@ +from app import app +from os import getpid, listdir +from pyrogram import filters +from pyrogram.types import Message, BotCommandScopeDefault, BotCommandScopeChat +from pyrogram.errors import bad_request_400 +from pyrogram.client import Client +from modules.utils import logWrite, should_quote, configGet +from modules import custom_filters + +pid = getpid() + +# Shutdown command ============================================================================================================= +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["resetcommands"], prefixes=["/"]) & custom_filters.admin) +async def cmd_kill(app: Client, msg: Message): + + if msg.from_user.id == configGet("owner"): + + logWrite(f"Resetting all commands on owner's request") + + valid_locales = [] + files_locales = listdir(f'{configGet("locale", "locations")}') + + for entry in files_locales: + if entry.endswith(".json"): + valid_locales.append(".".join(entry.split(".")[:-1])) + + if configGet("debug") is True: + logWrite(f'Resetting commands in groups {configGet("admin", "groups")} and {configGet("users", "groups")}') + await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("admin", "groups"))) + await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("users", "groups"))) + + for admin in configGet("admins"): + try: + if configGet("debug") is True: + logWrite(f'Resetting commands for admin {admin}') + await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=admin)) + except bad_request_400.PeerIdInvalid: + pass + + try: + if configGet("debug") is True: + logWrite(f'Resetting commands for owner {configGet("owner")}') + for lc in valid_locales: + if configGet("debug") is True: + logWrite(f'Resetting commands for owner {configGet("owner")} [{lc}]') + await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner")), language_code=lc) + await app.delete_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner"))) + except bad_request_400.PeerIdInvalid: + pass + + for lc in valid_locales: + if configGet("debug") is True: + logWrite(f'Resetting commands for locale {lc}') + await app.delete_bot_commands(scope=BotCommandScopeDefault(), language_code=lc) + + if configGet("debug") is True: + logWrite(f'Resetting default commands') + await app.delete_bot_commands() + + await msg.reply_text("OK", quote=should_quote(msg)) + + if configGet("debug") is True: + logWrite(str(await app.get_bot_commands())) + logWrite(str(await app.get_bot_commands(scope=BotCommandScopeChat(chat_id=configGet("owner"))))) +# ============================================================================================================================== \ No newline at end of file From 2e8277d6d2d94bbd914a4de21a4f97ee15074aa1 Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 5 Jan 2023 12:42:15 +0100 Subject: [PATCH 26/27] Added "owner" as an additional command permission --- modules/scheduled.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index 4ded913..47116da 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -105,6 +105,7 @@ async def commands_register(): commands = { "users": [], "admins": [], + "owner": [], "group_users": [], "group_admins": [], "locales": {} @@ -113,6 +114,7 @@ async def commands_register(): commands_raw = { "users": [], "admins": [], + "owner": [], "group_users": [], "group_admins": [], "locales": {} @@ -127,6 +129,7 @@ async def commands_register(): commands["locales"][".".join(entry.split(".")[:-1])] = { "users": [], "admins": [], + "owner": [], "group_users": [], "group_admins": [] } @@ -134,6 +137,7 @@ async def commands_register(): commands_raw["locales"][".".join(entry.split(".")[:-1])] = { "users": [], "admins": [], + "owner": [], "group_users": [], "group_admins": [] } @@ -181,17 +185,23 @@ async def commands_register(): await app.set_bot_commands(commands["locales"][lc]["users"], language_code=lc) logWrite(f"Registered user commands for locale {lc}") - # Registering admin/owner commands - for admin in configGet("admins").extend([configGet("owner")]): + # Registering admin commands + for admin in configGet("admins"): try: - await app.set_bot_commands(commands["admins"].extend(commands["users"]), scope=BotCommandScopeChat(chat_id=admin)) - if admin == configGet("owner"): - logWrite(f"Registered admin commands for owner {configGet('owner')}") - else: - logWrite(f"Registered admin commands for admin {admin}") + await app.set_bot_commands(commands["admins"]+commands["users"], scope=BotCommandScopeChat(chat_id=admin)) + logWrite(f"Registered admin commands for admin {admin}") except bad_request_400.PeerIdInvalid: pass + # Registering owner commands + try: + await app.set_bot_commands(commands["admins"]+commands["owner"]+commands["users"], scope=BotCommandScopeChat(chat_id=configGet("owner"))) + for lc in valid_locales: + await app.set_bot_commands(commands["locales"][lc]["admins"]+commands["locales"][lc]["owner"]+commands["locales"][lc]["users"], scope=BotCommandScopeChat(chat_id=configGet("owner"))) + logWrite(f"Registered admin commands for owner {configGet('owner')}") + except bad_request_400.PeerIdInvalid: + pass + # Registering admin group commands try: await app.set_bot_commands(commands["group_admins"], scope=BotCommandScopeChat(chat_id=configGet("admin", "groups"))) From 646db667d9033938c4fda45c12c498c31c70a292 Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 5 Jan 2023 12:44:13 +0100 Subject: [PATCH 27/27] Updated config in README --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d83d4fa..2d5e066 100644 --- a/README.md +++ b/README.md @@ -179,8 +179,7 @@ You can see config file with all the comments below: }, "reboot": { "permissions": [ - "admins", - "group_admins" + "owner" ], "modules": [ "general" @@ -231,6 +230,14 @@ You can see config file with all the comments below: "modules": [ "applications" ] + }, + "resetcommands": { + "permissions": [ + "owner" + ], + "modules": [ + "general" + ] } } }