From 42a4a2e58e744eed878e7148e0bd78b157438fe9 Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 12 Jan 2023 11:04:52 +0100 Subject: [PATCH 01/30] Internal and external spoilers are now separated --- config_example.json | 3 ++- holochecker.py | 2 +- locale/uk.json | 11 ++++++--- modules/callbacks/sid.py | 10 -------- modules/callbacks/spoiler.py | 31 +++++++++++++++++++++++++ modules/handlers/everything.py | 32 +++++++++++++++++++++++++- modules/inline.py | 42 ++++++++++++++++++---------------- 7 files changed, 95 insertions(+), 36 deletions(-) delete mode 100644 modules/callbacks/sid.py create mode 100644 modules/callbacks/spoiler.py diff --git a/config_example.json b/config_example.json index 5d06ffc..a562bc3 100644 --- a/config_example.json +++ b/config_example.json @@ -51,7 +51,8 @@ "enabled": false }, "spoilers": { - "enabled": true + "enabled": true, + "allow_external": true } }, "scheduler": { diff --git a/holochecker.py b/holochecker.py index da72662..c816c26 100644 --- a/holochecker.py +++ b/holochecker.py @@ -31,7 +31,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.spoiler import * from modules.callbacks.sponsorship import * from modules.callbacks.sub import * from modules.callbacks.sus import * diff --git a/locale/uk.json b/locale/uk.json index bf71dec..5be5fc5 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -109,7 +109,9 @@ "spoiler_unfinished": "У вас ще є незавершений спойлер. Надішліть /cancel щоб зупинити його створення", "spoiler_cancel": "Створення спойлера було припинено", "spoiler_empty": "Спойлер категорії \"{0}\" без опису", + "spoiler_empty_named": "Спойлер категорії \"{0}\" без опису від **{1}**", "spoiler_described": "Спойлер категорії \"{0}\": {1}", + "spoiler_described_named": "Спойлер категорії \"{0}\" від **{1}**: {2}", "spoiler_description_enter": "Добре, введіть бажаний опис спойлера", "spoiler_description_too_long": "Текст занадто довгий. Будь ласка, умісти опис у 1024 символи.", "spoiler_using_description": "Встановлено опис спойлера: {0}\n\nЗалишилось додати вміст самого спойлера. Бот приймає текстове повідомлення, фото, відео, файл а також гіф зображення (1 шт.)", @@ -226,8 +228,10 @@ "done": "✅ Готово", "sponsor_apply": "Заповнити форму", "sponsor_started": "Форму розпочато", - "spoiler_send": "Надіслати", - "spoiler_view": "Переглянути" + "spoiler_view": "Переглянути", + "spoiler_preview": "Попередній перегляд", + "spoiler_send_chat": "Надіслати в холо-чат", + "spoiler_send_other": "Надіслати в інший чат" }, "callback": { "sub_accepted": "✅ Анкету {0} схвалено", @@ -243,7 +247,8 @@ "reapply_stopped": "ℹ️ Перервано заповнення анкети", "sponsor_started": "ℹ️ Заповнення форми розпочато", "sponsor_accepted": "✅ Форму {0} схвалено", - "sponsor_rejected": "❌ Форму {0} відхилено" + "sponsor_rejected": "❌ Форму {0} відхилено", + "spoiler_sent": "✅ Повідомлення надіслано в холо-чат" }, "inline": { "forbidden": { diff --git a/modules/callbacks/sid.py b/modules/callbacks/sid.py deleted file mode 100644 index 434690e..0000000 --- a/modules/callbacks/sid.py +++ /dev/null @@ -1,10 +0,0 @@ -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/callbacks/spoiler.py b/modules/callbacks/spoiler.py new file mode 100644 index 0000000..8118a34 --- /dev/null +++ b/modules/callbacks/spoiler.py @@ -0,0 +1,31 @@ +from app import app +from pyrogram.types import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton +from pyrogram.client import Client +from pyrogram import filters +from modules.database import col_spoilers +from bson.objectid import ObjectId + +from modules.utils import configGet, locale + +# Callback sid ================================================================================================================= +@app.on_callback_query(filters.regex("sid_[\s\S]*")) +async def callback_query_sid(app: Client, clb: CallbackQuery): + await clb.answer(url=f'https://t.me/{(await app.get_me()).username}?start={clb.data.split("_")[1]}') +# ============================================================================================================================== + +# Callback shc ================================================================================================================= +@app.on_callback_query(filters.regex("shc_[\s\S]*")) +async def callback_query_shc(app: Client, clb: CallbackQuery): + + spoil = col_spoilers.find_one( {"_id": ObjectId(clb.data.split("_")[1])} ) + + if spoil["description"] == "": + desc = locale("spoiler_empty_named", "message", locale=clb.from_user).format(locale(spoil["category"], "message", "spoiler_categories"), clb.from_user.first_name) + else: + desc = locale("spoiler_described_named", "message", locale=clb.from_user).format(locale(spoil["category"], "message", "spoiler_categories"), clb.from_user.first_name, spoil["description"]) + + await app.send_message(configGet("users", "groups"), desc, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_view", "button", locale=clb.from_user), callback_data=f'sid_{clb.data.split("_")[1]}')]])) + await app.send_message(configGet("admin", "groups"), desc, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_view", "button", locale=clb.from_user), callback_data=f'sid_{clb.data.split("_")[1]}')]])) + + await clb.answer(locale("spoiler_sent", "callback", locale=clb.from_user), show_alert=True) +# ============================================================================================================================== \ No newline at end of file diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index eaf83cb..e899f19 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -146,7 +146,37 @@ async def any_stage(app: Client, msg: Message): ready = True if ready is True: - await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("spoiler_send", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}")]])) + if configGet("allow_external", "features", "spoilers") is True: + await msg.reply_text( + locale("spoiler_ready", "message", locale=msg.from_user), + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(locale("spoiler_preview", "button", locale=msg.from_user), callback_data=f"sid_{spoiler['_id'].__str__()}") + ], + [ + InlineKeyboardButton(locale("spoiler_send_chat", "button", locale=msg.from_user), callback_data=f"shc_{spoiler['_id'].__str__()}") + ], + [ + InlineKeyboardButton(locale("spoiler_send_other", "button", locale=msg.from_user), switch_inline_query=f"spoiler:{spoiler['_id'].__str__()}") + ] + ] + ) + ) + else: + await msg.reply_text( + locale("spoiler_ready", "message", locale=msg.from_user), + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(locale("spoiler_preview", "button", locale=msg.from_user), callback_data=f"sid_{spoiler['_id'].__str__()}") + ], + [ + InlineKeyboardButton(locale("spoiler_send_chat", "button", locale=msg.from_user), callback_data=f"shc_{spoiler['_id'].__str__()}") + ] + ] + ) + ) else: await msg.reply_text(locale("spoiler_incorrect_content", "message", locale=msg.from_user)) diff --git a/modules/inline.py b/modules/inline.py index ce25f7b..c8ba27a 100644 --- a/modules/inline.py +++ b/modules/inline.py @@ -22,34 +22,36 @@ async def inline_answer(client: Client, inline_query: InlineQuery): results = [] - if inline_query.query.startswith("spoiler:"): + if configGet("allow_external", "features", "spoilers") is True: - try: + if inline_query.query.startswith("spoiler:"): + + try: - spoil = col_spoilers.find_one( {"_id": ObjectId(inline_query.query.removeprefix("spoiler:"))} ) + spoil = col_spoilers.find_one( {"_id": ObjectId(inline_query.query.removeprefix("spoiler:"))} ) - if spoil is not None: + if spoil is not None: - desc = locale("spoiler_empty", "message", locale=inline_query.from_user).format(locale(spoil["category"], "message", "spoiler_categories")) if spoil["description"] == "" else locale("spoiler_described", "message", locale=inline_query.from_user).format(locale(spoil["category"], "message", "spoiler_categories"), spoil["description"]) + desc = locale("spoiler_empty", "message", locale=inline_query.from_user).format(locale(spoil["category"], "message", "spoiler_categories")) if spoil["description"] == "" else locale("spoiler_described", "message", locale=inline_query.from_user).format(locale(spoil["category"], "message", "spoiler_categories"), 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:")}')]]) - ) - ] + 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 = [] + except InvalidId: + results = [] - - await inline_query.answer( - results=results - ) + + await inline_query.answer( + results=results + ) - return + return if inline_query.chat_type in [ChatType.CHANNEL]: await inline_query.answer( From bd925418fdf37a5497ea56d6ef0b1772008a6fc9 Mon Sep 17 00:00:00 2001 From: profitroll Date: Thu, 12 Jan 2023 13:57:41 +0100 Subject: [PATCH 02/30] YouTube new videos on channels monitoring --- config_example.json | 5 +++++ locale/uk.json | 1 + modules/database.py | 3 ++- modules/scheduled.py | 34 ++++++++++++++++++++++++++++++++-- requirements.txt | 3 ++- 5 files changed, 42 insertions(+), 4 deletions(-) diff --git a/config_example.json b/config_example.json index a562bc3..c25b48d 100644 --- a/config_example.json +++ b/config_example.json @@ -75,6 +75,11 @@ "cache_admins": { "interval": 120, "enabled": true + }, + "channels_monitor": { + "interval": 5, + "enabled": true, + "channels": [] } }, "locations": { diff --git a/locale/uk.json b/locale/uk.json index 5be5fc5..c84a258 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -120,6 +120,7 @@ "spoiler_incorrect_content": "Бот не підтримує такий контент. Будь ласка, надішли текст, фото, відео, файл або анімацію (гіф).", "spoiler_incorrect_category": "Вказана категорія не є дійсною. Будь ласка, користуйся клавіатурою бота (кнопка біля 📎) для вибору категорії.", "spoiler_in_progress": "❌ **Дія неможлива**\nПерш ніж починати нову дію, треба завершити створення спойлера або перервати його командою /cancel.", + "youtube_video": "На каналі [{0}]({1}) нове відео!\n\n**[{2}]({3})**", "yes": "Так", "no": "Ні", "voice_message": [ diff --git a/modules/database.py b/modules/database.py index f518dc1..a7f3c67 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", "spoilers", "messages", "warnings", "applications", "sponsorships"]: +for collection in ["tmp", "users", "context", "youtube", "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_youtube = db.get_collection("youtube") col_spoilers = db.get_collection("spoilers") col_messages = db.get_collection("messages") col_warnings = db.get_collection("warnings") diff --git a/modules/scheduled.py b/modules/scheduled.py index f30f312..b972e31 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -1,7 +1,9 @@ """Automatically register commands and execute some scheduled tasks is the main idea of this module""" +from asyncio import sleep from os import listdir, makedirs, path, sep +from traceback import format_exc from apscheduler.schedulers.asyncio import AsyncIOScheduler from datetime import datetime, timedelta from ujson import dumps @@ -12,7 +14,9 @@ from pyrogram.enums.chat_members_filter import ChatMembersFilter from classes.holo_user import HoloUser from modules.utils import configGet, jsonSave, locale, logWrite from dateutil.relativedelta import relativedelta -from modules.database import col_applications, col_sponsorships +from modules.database import col_applications, col_sponsorships, col_youtube +from xmltodict import parse +from requests import get scheduler = AsyncIOScheduler() @@ -233,4 +237,30 @@ 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)}", debug=True) \ No newline at end of file + logWrite(f"Complete commands registration:\n{dumps(commands_raw, indent=4, ensure_ascii=False, encode_html_chars=False)}", debug=True) + + +if configGet("enabled", "scheduler", "channels_monitor"): + @scheduler.scheduled_job(trigger="interval", minutes=configGet("interval", "scheduler", "channels_monitor")) + async def channels_monitor(): + for channel in configGet("channels", "scheduler", "channels_monitor"): + if configGet("debug") is True: + logWrite(f'Processing videos of {channel["name"]} ({channel["id"]})', debug=True) + try: + req = get(f'https://www.youtube.com/feeds/videos.xml?channel_id={channel["id"]}') + parsed = parse(req.content) + if "feed" not in parsed: + continue + if "entry" not in parsed["feed"]: + continue + for entry in parsed["feed"]["entry"]: + if "yt:videoId" not in entry: + continue + if col_youtube.find_one( {"channel": channel["id"], "video": entry["yt:videoId"]} ) is None: + col_youtube.insert_one( {"channel": channel["id"], "video": entry["yt:videoId"], "date": datetime.fromisoformat(entry["published"])} ) + await app.send_message(configGet("users", "groups"), locale("youtube_video", "message").format(channel["name"], channel["link"], entry["title"], entry["link"]["@href"]), disable_web_page_preview=False) + await sleep(2) + except Exception as exp: + logWrite(f'Could not get last videos of {channel["name"]} ({channel["id"]}) due to {exp}: {format_exc()}') + if configGet("debug") is True: + logWrite("Admin group caching performed", debug=True) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 8e2a18e..d851783 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,4 +8,5 @@ tgcrypto==1.2.5 python_dateutil==2.8.2 starlette~=0.22.0 ujson~=5.7.0 -ftfy~=6.1.1 \ No newline at end of file +ftfy~=6.1.1 +xmltodict~=0.13.0 \ No newline at end of file From fd5e0b5b222a0e0278a6c74798c543d6d624bb45 Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 13 Jan 2023 10:43:27 +0100 Subject: [PATCH 03/30] Spoilers on custom filters --- modules/commands/spoiler.py | 2 +- modules/custom_filters.py | 4 ++++ modules/handlers/everything.py | 3 +++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/commands/spoiler.py b/modules/commands/spoiler.py index 48b203e..44f858b 100644 --- a/modules/commands/spoiler.py +++ b/modules/commands/spoiler.py @@ -10,7 +10,7 @@ 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=["/"])) +@app.on_message(custom_filters.enabled_spoilers & custom_filters.member & ~filters.scheduled & filters.private & filters.command(["spoiler"], prefixes=["/"])) async def cmd_spoiler(app: Client, msg: Message): try: diff --git a/modules/custom_filters.py b/modules/custom_filters.py index 4fa39fe..529a055 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -39,6 +39,9 @@ async def enabled_invites_check_func(_, __, msg: Message): async def enabled_dinovoice_func(_, __, msg: Message): return configGet("enabled", "features", "dinovoice") +async def enabled_spoilers_func(_, __, msg: Message): + return configGet("enabled", "features", "spoilers") + 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 @@ -52,5 +55,6 @@ 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) +enabled_spoilers = filters.create(enabled_spoilers_func) filling_sponsorship = filters.create(filling_sponsorship_func) \ No newline at end of file diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index e899f19..01366ff 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -66,6 +66,9 @@ async def any_stage(app: Client, msg: Message): if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": + if configGet("enabled", "features", "spoilers") is False: + return + spoiler = col_spoilers.find_one( {"user": msg.from_user.id, "completed": False} ) if spoiler is None: From 414bfefb21090b469154f3adea9137656e54b392 Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 13 Jan 2023 14:45:23 +0100 Subject: [PATCH 04/30] Fixed tmp download function --- modules/commands/identify.py | 2 +- modules/utils.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/commands/identify.py b/modules/commands/identify.py index ad76a0b..83a450b 100644 --- a/modules/commands/identify.py +++ b/modules/commands/identify.py @@ -51,7 +51,7 @@ async def cmd_identify(app: Client, msg: Message): if user.photo is not None: await app.send_chat_action(msg.chat.id, action=ChatAction.UPLOAD_PHOTO) await msg.reply_photo( - create_tmp(await download_tmp(app, user.photo.big_file_id), kind="image"), + create_tmp((await download_tmp(app, user.photo.big_file_id))[1], kind="image"), quote=should_quote(msg), caption=output ) diff --git a/modules/utils.py b/modules/utils.py index 880d087..cad4af5 100644 --- a/modules/utils.py +++ b/modules/utils.py @@ -1,4 +1,4 @@ -from typing import Any, Literal, Union +from typing import Any, Literal, Tuple, Union from uuid import uuid1 from requests import get from pyrogram.enums.chat_type import ChatType @@ -212,7 +212,7 @@ def create_tmp(bytedata: Union[bytes, bytearray], kind: Union[Literal["image", " file.write(bytedata) return path.join("tmp", filename) -async def download_tmp(app: Client, file_id: str) -> bytes: +async def download_tmp(app: Client, file_id: str) -> Tuple[str, bytes]: """Download file by its ID and return its bytes ### Args: @@ -220,14 +220,14 @@ async def download_tmp(app: Client, file_id: str) -> bytes: * file_id (`str`): File's unique id ### Returns: - * `bytes`: Bytes of downloaded file + * `Tuple[str, bytes]`: First is a filepath and the second is file's bytes """ filename = str(uuid1()) makedirs("tmp", exist_ok=True) await app.download_media(file_id, path.join("tmp", filename)) with open(path.join("tmp", filename), "rb") as f: bytedata = f.read() - return bytedata + return path.join("tmp", filename), bytedata try: from psutil import Process From 05e391647802797899fe1fae4ed7e28801f21ec8 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 16 Jan 2023 12:09:28 +0100 Subject: [PATCH 05/30] Fixed reply messages --- modules/handlers/everything.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index 01366ff..d79f7dc 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -22,7 +22,7 @@ async def message_context(msg: Message) -> tuple: return 0, 0 # Any other input ============================================================================================================== -@app.on_message(~ filters.scheduled & filters.private) +@app.on_message(~ filters.scheduled & (filters.private | filters.chat(configGet("admin", "groups")))) async def any_stage(app: Client, msg: Message): if msg.via_bot is None: @@ -52,6 +52,9 @@ async def any_stage(app: Client, msg: Message): return + if msg.chat.id == configGet("admin", "groups"): + return + if msg.text is not None: if configGet("enabled", "features", "applications") is True: From 8beb33b7c3dae4104e6a1aac96140ecce4aa2c4c Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 16 Jan 2023 12:09:53 +0100 Subject: [PATCH 06/30] Now ignoring bdays of users that left --- modules/scheduled.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index b972e31..519e700 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -12,7 +12,7 @@ from pyrogram.types import BotCommand, BotCommandScopeChat, BotCommandScopeChatA from pyrogram.errors import bad_request_400 from pyrogram.enums.chat_members_filter import ChatMembersFilter from classes.holo_user import HoloUser -from modules.utils import configGet, jsonSave, locale, logWrite +from modules.utils import configGet, jsonLoad, jsonSave, locale, logWrite from dateutil.relativedelta import relativedelta from modules.database import col_applications, col_sponsorships, col_youtube from xmltodict import parse @@ -66,6 +66,8 @@ if configGet("enabled", "features", "applications") is True: for entry in col_applications.find(): if entry["application"]["2"].strftime("%d.%m") == datetime.now().strftime("%d.%m"): try: + if entry["user"] not in jsonLoad(path.join(configGet("cache", "locations"), "group_members")): + continue tg_user = await app.get_users(entry["user"]) 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") @@ -82,6 +84,8 @@ if configGet("enabled", "features", "sponsorships") is True: async def check_sponsors(): for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()+timedelta(days=2)}}): try: + if entry["user"] not in jsonLoad(path.join(configGet("cache", "locations"), "group_members")): + continue tg_user = await app.get_users(entry["user"]) until_expiry = relativedelta(datetime.now(), entry["sponsorship"]["expires"]).days await app.send_message( tg_user.id, locale("sponsorships_expires", "message").format(until_expiry) ) # type: ignore @@ -92,9 +96,11 @@ if configGet("enabled", "features", "sponsorships") is True: for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()}}): try: holo_user = HoloUser(entry["user"]) + col_sponsorships.find_one_and_delete({"user": holo_user.id}) + if entry["user"] not in jsonLoad(path.join(configGet("cache", "locations"), "group_members")): + continue await app.send_message( entry["user"], locale("sponsorships_expired", "message") ) # type: ignore 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"]) logWrite(f"Notified user that sponsorship expired") From de552db4c8302c508bf85e25891a79deb4e9402e Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 16 Jan 2023 12:10:07 +0100 Subject: [PATCH 07/30] Reapply improved --- modules/callbacks/reapply.py | 21 +++++++++++++++++++-- modules/commands/reapply.py | 33 +++++++++++++++++++++++---------- modules/handlers/welcome.py | 5 ++++- 3 files changed, 46 insertions(+), 13 deletions(-) diff --git a/modules/callbacks/reapply.py b/modules/callbacks/reapply.py index ded851d..121a7d3 100644 --- a/modules/callbacks/reapply.py +++ b/modules/callbacks/reapply.py @@ -83,13 +83,30 @@ async def callback_query_reapply_reject(app: Client, clb: CallbackQuery): # Use old application when user reapplies after leaving the chat @app.on_callback_query(filters.regex("reapply_old_[\s\S]*")) async def callback_query_reapply_old(app: Client, clb: CallbackQuery): - fullclb = clb.data.split("_") - if HoloUser(clb.from_user).sponsorship_state()[0] == "fill": + fullclb = clb.data.split("_") + holo_user = HoloUser(clb.from_user) + + if holo_user.sponsorship_state()[0] == "fill": await clb.message.reply_text(locale("finish_sponsorship", "message"), quote=False) return message = await app.get_messages(clb.from_user.id, int(fullclb[2])) + + if col_tmp.find_one({"user": holo_user.id, "type": "application"}) is None and col_applications.find_one({"user": holo_user.id}) is not None: + col_tmp.insert_one( + { + "user": holo_user.id, + "type": "application", + "complete": True, + "sent": False, + "state": "fill", + "reapply": True, + "stage": 10, + "application": col_applications.find_one({"user": holo_user.id})["application"] + } + ) + await confirm_yes(app, message, kind="application") await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button", locale=clb.from_user), "nothing")]])) diff --git a/modules/commands/reapply.py b/modules/commands/reapply.py index 1912eb6..da3ee52 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -6,7 +6,7 @@ from classes.holo_user import HoloUser from modules.logging import logWrite from modules.utils import configGet, locale, should_quote from modules.handlers.welcome import welcome_pass -from modules.database import col_tmp +from modules.database import col_tmp, col_applications from modules import custom_filters # Reapply command ============================================================================================================== @@ -27,16 +27,20 @@ async def cmd_reapply(app: Client, msg: Message): if member.user.id == msg.from_user.id: left_chat = False - if not left_chat: - if holo_user.sponsorship_state()[0] == "fill": - await msg.reply_text(locale("finish_sponsorship", "message"), quote=should_quote(msg)) - return - holo_user.application_restart(reapply=True) - await welcome_pass(app, msg, once_again=True) - - else: + if left_chat is True: - if holo_user.application_state()[1] is True and holo_user.application_state()[0] != "fill": + if (holo_user.application_state()[1] is True and holo_user.application_state()[0] != "fill"): + + await msg.reply_text(locale("reapply_left_chat", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup([ + [ + InlineKeyboardButton(locale("reapply_old_one", "button", locale=holo_user), f"reapply_old_{msg.id}") + ], + [ + InlineKeyboardButton(locale("reapply_new_one", "button", locale=holo_user), f"reapply_new_{msg.id}") + ] + ])) + + elif col_tmp.find_one({"user": holo_user.id, "type": "application"}) is None and col_applications.find_one({"user": holo_user.id}) is not None: await msg.reply_text(locale("reapply_left_chat", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup([ [ @@ -52,6 +56,15 @@ async def cmd_reapply(app: Client, msg: Message): holo_user.application_restart(reapply=True) await welcome_pass(app, msg, once_again=True) + else: + + if holo_user.sponsorship_state()[0] == "fill": + await msg.reply_text(locale("finish_sponsorship", "message"), quote=should_quote(msg)) + return + + holo_user.application_restart(reapply=True) + await welcome_pass(app, msg, once_again=True) + else: await msg.reply_text(locale("reapply_in_progress", "message", locale=holo_user).format(locale("confirm", "keyboard", locale=holo_user)[1][0]), reply_markup=InlineKeyboardMarkup([ diff --git a/modules/handlers/welcome.py b/modules/handlers/welcome.py index 9194174..2450178 100644 --- a/modules/handlers/welcome.py +++ b/modules/handlers/welcome.py @@ -30,7 +30,10 @@ async def welcome_pass(app: Client, msg: Message, once_again: bool = False) -> N if once_again is False: holo_user.application_restart() - logWrite(f"User {msg.from_user.id} confirmed starting the application") + if once_again is True: + logWrite(f"User {msg.from_user.id} confirmed starting the application") + else: + logWrite(f"User {msg.from_user.id} confirmed starting the application once again") await msg.reply_text(locale("question1", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("question1", "force_reply", locale=msg.from_user))) welcome_2 = [] From 51b943b57670919a6528bcca2b57e35c2584eacf Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 16 Jan 2023 12:10:40 +0100 Subject: [PATCH 08/30] Added format notice in 2nd question of application --- locale/uk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locale/uk.json b/locale/uk.json index c84a258..d3bf951 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -4,7 +4,7 @@ "goodbye": "Добре, дякуємо за чесність! Вибачте, але за таких умов ми не будемо тебе додавати до спільноти. Якщо передумаєш та захочеш приєднатись - просто натисни на кнопку.", "privacy_notice": "Раді це чути!\n\nДля продовження треба буде заповнити невеличку анкетку. Будь ласка, віднесись до цього серйозно. Ми відповідально ставимось до персональних даних, тому ця анкета не буде передана третім особам, а буде використана лише для проходження до спільноти.", "question1": "Як до тебе можна звертатись?", - "question2": "Коли в тебе день народження?", + "question2": "Коли в тебе день народження?\n\nБудь ласка, у форматі ДД.ММ.РРРР", "question3": "З якого ти міста або де проживаєш зараз?\n\n⚠️ Будь ласка, не вказуйте точних адрес! \"Київ\" або \"Київська Область\" є достатньою конкретизацією.\n\nПриклади:\n• Київ\n• Одеська область\n• Макіївка (Луганська область)", "question4": "Коли вперше довелось дізнатись про Хололайв?", "question5": "Чим тебе зацікавив Хололайв?", From 4019f2f376b692ab05e01214bee707a159447e33 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:03:04 +0100 Subject: [PATCH 09/30] This fix resolves #10 --- locale/uk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locale/uk.json b/locale/uk.json index d3bf951..1221ec1 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -272,7 +272,7 @@ "description": "Надіслати цей спойлер до чату" } }, - "rules_msg": "📢Правила можуть доповнюватись та змінюватись, залежно від потреби. У такому разі, порушення, які були вчинені до введення (змінення) правила, порушеннями вважатися не будуть. Про всі зміни в правилах, ви будете проінформовані за допомогою закріплених повідомлень. Але вони не будуть закріплені на постійній основі, тому, час від часу, перевіряйте актуальність правил у боті.\n\n🔔Якщо ви бачите, як хтось із учасників порушив правила, тегніть одного із адмінів, у відповідь на повідомлення, яке, на вашу думку, є порушенням. У дописі до тегу, вкажіть, по якому пункту ви побачили порушення. Або перешліть повідомлення до будь кого із адміністраторів у особисті повідомлення, та коротко опишіть ситуацію.\nСписок адміністраторів: @Chirkopol @Za_NerZula @Denialvapr\nЗ питань функціонування бота звертайтесь до @Profitroll2281337\n\n❗️Будь-який заборонений контент, може бути відправлений допомогою команди /spoiler у бота - з повним описом контенту, що міститься під спойлером. За неправильний або некоректний опис, може бути видане попередження.\n\n‼️Видалені або змінені повідомлення, все ще є повідомленнями від вашого імені, які могли побачити учасники чату, і які можуть бути відстежені через адмінську панель.\n\n🔨 За порушення - ви отримаєте попередження. За наявності 3-х попереджень - мут на добу. За повторні порушення, ви одразу отримаєте покарання, без додаткових попереджень.", + "rules_msg": "📢Правила можуть доповнюватись та змінюватись, залежно від потреби. У такому разі, порушення, які були вчинені до введення (змінення) правила, порушеннями вважатися не будуть. Про всі зміни в правилах, ви будете проінформовані за допомогою закріплених повідомлень. Але вони не будуть закріплені на постійній основі, тому, час від часу, перевіряйте актуальність правил у боті.\n\n🔔Якщо ви бачите, як хтось із учасників порушив правила, тегніть одного із адмінів, у відповідь на повідомлення, яке, на вашу думку, є порушенням. У дописі до тегу, вкажіть, по якому пункту ви побачили порушення. Або перешліть повідомлення до будь кого із адміністраторів у особисті повідомлення, та коротко опишіть ситуацію.\nСписок адміністраторів: @Chirkopol @Za_NerZula @Denialvapr\nЗ питань функціонування бота звертайтесь до @Profitroll2281337\n\n❗️Будь-який заборонений контент, може бути відправлений за допомогою команди /spoiler у бота - з повним описом контенту, що міститься під спойлером. За неправильний або некоректний опис, може бути видане попередження.\n\n‼️Видалені або змінені повідомлення, все ще є повідомленнями від вашого імені, які могли побачити учасники чату, і які можуть бути відстежені через адмінську панель.\n\n🔨 За порушення - ви отримаєте попередження. За наявності 3-х попереджень - мут на добу. За повторні порушення, ви одразу отримаєте покарання, без додаткових попереджень.", "rules": [ "1️⃣) \"HoloKyiv Chat\" та \"HoloUA (Hololive Ukraine) Chat\" створені виключно для українців (13+). В них можуть знаходитись тільки люди які: \n- Народились в Україні, та проживають, на данний момент, у ній.\n- Народились за межами України, але проживають у ній.\n- Народились в Україні але, на даний момент, не проживають у ній.\n\"HoloUA (Hololive Ukraine) Chat\" відкритий для усіх українців. Щоб потрапити до нього, заповніть, будь ласка, анкету, та дочекайтесь, поки її схвалять адміни.\nУ \"HoloKyiv Chat\" можна потрапити тільки особисто, якщо ви проживаєте у Київі, або є близьким другом одного із учасників чату. Із приводу додавання до чату пишіть @Chirkopol у приватні повідомлення.\n🔨 Якщо у процесі спілкування виявиться, що ви не українець, вас буде видалено із чату, до моменту, поки ви їм не станете. Без образ. Ми створюємо виключно українське ком'юніті.", "2️⃣) Заборонено поширення NSFW-контенту з прямим або частково прихованим порнографічним змістом. На контенті \"еротичного характеру\" повинні бути закриті \"сумнівні\" ділянки тіл. \nЗаборонено поширення шок-контенту з великою наявністю крові та/або фізичних пошкоджень.", From e3fd4b35766ce8d16cfc18702f35e971252493f2 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:10:06 +0100 Subject: [PATCH 10/30] This commit closes #21 --- modules/scheduled.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index 519e700..2d17eaa 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -87,9 +87,9 @@ if configGet("enabled", "features", "sponsorships") is True: if entry["user"] not in jsonLoad(path.join(configGet("cache", "locations"), "group_members")): continue tg_user = await app.get_users(entry["user"]) - until_expiry = relativedelta(datetime.now(), entry["sponsorship"]["expires"]).days + until_expiry = abs(relativedelta(datetime.now(), entry["sponsorship"]["expires"]).days)+1 await app.send_message( tg_user.id, locale("sponsorships_expires", "message").format(until_expiry) ) # type: ignore - logWrite(f"Notified user that sponsorship expires in {until_expiry} days") + logWrite(f"Notified user {entry['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 @@ -103,7 +103,7 @@ if configGet("enabled", "features", "sponsorships") is True: await holo_user.label_reset(configGet("users", "groups")) try: tg_user = await app.get_users(entry["user"]) - logWrite(f"Notified user that sponsorship expired") + logWrite(f"Notified user {entry['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: From adc8c83102261f51e581a3a7784abeb547e8954a Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:15:26 +0100 Subject: [PATCH 11/30] Closes #13 --- locale/en.disabled | 3 --- locale/uk.json | 3 --- modules/callbacks/sub.py | 17 ----------------- modules/handlers/confirmation.py | 3 --- 4 files changed, 26 deletions(-) diff --git a/locale/en.disabled b/locale/en.disabled index a93f3b5..3f4a79d 100644 --- a/locale/en.disabled +++ b/locale/en.disabled @@ -31,7 +31,6 @@ "approved_joined": "Congratulations! Your application has been reviewed and confirmed as correct. Thank you for your time and have a nice day!", "read_rules": "Please read these rules before clicking the button and joining the chat.", "rejected.": "Oh dear! Your application has been reviewed but not confirmed as eligible to join the community. Better luck next time!\n\nYou can try to reapply with the /reapply command.", - "rejected_aggressive": "Oh dear! Your application has been reviewed, but not confirmed as eligible to join the community.", "rejected_russian": "Russian warship, go fuck yourself!", "approved_by": "✅ **Application approved**\nAdmin **{0}** has reviewed and approved application `{1}`.", "rejected_by": "❌ **Form rejected**\nAdmin **{0}** has reviewed and rejected form `{1}`.", @@ -122,7 +121,6 @@ "button": { "sub_yes": "✅ Accept", "sub_no": "❌ Reject", - "sub_aggressive": "🤡 Reject (Toxic)", "sub_russian": "🇷🇺 Reject (Russian)", "accepted": "✅ Accepted", "declined": "❌ Rejected", @@ -145,7 +143,6 @@ "callback": { "sub_accepted": "✅ Application {0} has been approved", "sub_rejected": "❌ Application {0} rejected", - "sub_aggressive": "🤡 Application {0} rejected", "sub_russian": "🇷🇺 Application {0} rejected", "sus_allowed": "✅ Access {0} allowed", "sus_rejected": "❌ Access {0} denied", diff --git a/locale/uk.json b/locale/uk.json index 1221ec1..eea358a 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -48,7 +48,6 @@ "approved_joined": "Вітаємо! Твою анкету переглянули та підтвердили її правильність. Дякуємо за витрачений на заповнення час та гарного дня!", "read_rules": "Будь ласка, прочитай ці правила перш ніж натискати на кнопку та приєднуватись до чату.", "rejected": "Ой лишенько! Твою анкету переглянули, однак не підтвердили право на вступ до спільноти. Better luck next time!\n\nТи можеш спробувати повторно заповнити анкету командою /reapply", - "rejected_aggressive": "Ой лишенько! Твою анкету переглянули, однак не підтвердили право на вступ до спільноти.", "rejected_russian": "русский военньій корабль, иди нахуй!", "approved_by": "✅ **Анкету схвалено**\nАдмін **{0}** переглянув та схвалив анкету `{1}`.", "rejected_by": "❌ **Анкету відхилено**\nАдмін **{0}** переглянув та відхилив анкету `{1}`.", @@ -206,7 +205,6 @@ "button": { "sub_yes": "✅ Прийняти", "sub_no": "❌ Відхилити", - "sub_aggressive": "🤡 Відхилити (Токс)", "sub_russian": "🇷🇺 Відхилити (Русак)", "sponsor_yes": "✅ Прийняти", "sponsor_no": "❌ Відхилити", @@ -237,7 +235,6 @@ "callback": { "sub_accepted": "✅ Анкету {0} схвалено", "sub_rejected": "❌ Анкету {0} відхилено", - "sub_aggressive": "🤡 Анкету {0} відхилено", "sub_russian": "🇷🇺 Анкету {0} відхилено", "sus_allowed": "✅ Доступ {0} дозволено", "sus_rejected": "❌ Доступ {0} заборонено", diff --git a/modules/callbacks/sub.py b/modules/callbacks/sub.py index eb76d06..f806f50 100644 --- a/modules/callbacks/sub.py +++ b/modules/callbacks/sub.py @@ -68,23 +68,6 @@ async def callback_query_reject(app: Client, clb: CallbackQuery): await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sub_rejected", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) -@app.on_callback_query(filters.regex("sub_aggressive_[\s\S]*")) -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", "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") - - col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) - - edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]] - - await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) - await clb.answer(text=locale("sub_aggressive", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) - @app.on_callback_query(filters.regex("sub_russian_[\s\S]*")) async def callback_query_reject_russian(app: Client, clb: CallbackQuery): diff --git a/modules/handlers/confirmation.py b/modules/handlers/confirmation.py index 364a276..9dc8a79 100644 --- a/modules/handlers/confirmation.py +++ b/modules/handlers/confirmation.py @@ -83,9 +83,6 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s [ 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}") ] From f4c1bf9587f3d4b5a8cde8c6cc9419946e56d0ba Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:17:00 +0100 Subject: [PATCH 12/30] This commit closes #15 --- locale/uk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locale/uk.json b/locale/uk.json index eea358a..1b73899 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -9,7 +9,7 @@ "question4": "Коли вперше довелось дізнатись про Хололайв?", "question5": "Чим тебе зацікавив Хололайв?", "question6": "Контент якої дівчини тобі подобається найбільше?", - "question7": "Назви контент хоча б п'яти японських холодівчат, які тобі подобаються найбільше.", + "question7": "Назви контент хоча б п'яти **ЯПОНСЬКИХ** холодівчат, які тобі подобаються найбільше.", "question8": "Чи дивишся ти стріми дівчат Хололайву?", "question9": "Чиї пісні з Хололайву тобі подобаються найбільше?", "question10": "Ну і нарешті, розкажи трохи про себе. Про хобі, чим тобі подобається займатись. Одним повідомленням, будь ласка.", From a59a42ffd9f25d4bf1dd2000c8df76bf38b0982b Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:17:39 +0100 Subject: [PATCH 13/30] Is also connected #15 --- locale/en.disabled | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locale/en.disabled b/locale/en.disabled index 3f4a79d..cf7c410 100644 --- a/locale/en.disabled +++ b/locale/en.disabled @@ -9,7 +9,7 @@ "question4": "When did you first learn about Hololive?", "question5": "What made you interested in Hololive?", "question6": "Which girl's content do you like the most?", - "question7": "Name the content of at least five Japanese girls you like the most.", + "question7": "Name the content of at least five **JAPANESE** girls you like the most.", "question8": "Do you watch streams of Hololive girls?", "question9": "Whose songs from Hololive do you like the most?", "question10": "And finally, tell us a little about yourself. About hobbies, what you like to do. In one message, please.", From 834157030c980b84b5408fb4b9cda8584c6a632f Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:20:56 +0100 Subject: [PATCH 14/30] This commit closes #19 --- locale/uk.json | 1 + modules/commands/cancel.py | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/locale/uk.json b/locale/uk.json index 1b73899..9bd138e 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -101,6 +101,7 @@ "nearby_result": "Результати пошуку:\n\n{0}", "nearby_empty": "Здається, нікого поблизу немає.", "cancel": "Всі поточні операції скасовано.", + "cancel_reapply": "Всі поточні операції скасовано.\nЩоб знову заповнити анкету користуйся /reapply", "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}", diff --git a/modules/commands/cancel.py b/modules/commands/cancel.py index 4c86903..8721dc8 100644 --- a/modules/commands/cancel.py +++ b/modules/commands/cancel.py @@ -3,7 +3,7 @@ from pyrogram import filters from pyrogram.types import Message, ReplyKeyboardRemove from pyrogram.client import Client from modules.utils import should_quote, logWrite, locale -from modules.database import col_tmp, col_spoilers +from modules.database import col_tmp, col_spoilers, col_applications from modules import custom_filters # Cancel command =============================================================================================================== @@ -11,6 +11,9 @@ from modules import custom_filters async def command_cancel(app: Client, msg: Message): col_tmp.delete_many( {"user": msg.from_user.id, "sent": False} ) 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), reply_markup=ReplyKeyboardRemove()) + if col_applications.find_one( {"user": msg.from_user.id} ) is None: + await msg.reply_text(locale("cancel_reapply", "message", locale=msg.from_user), quote=should_quote(msg), reply_markup=ReplyKeyboardRemove()) + else: + await msg.reply_text(locale("cancel", "message", locale=msg.from_user), quote=should_quote(msg), reply_markup=ReplyKeyboardRemove()) logWrite(f"Cancelling all ongoing tmp operations for {msg.from_user.id}") # ============================================================================================================================== \ No newline at end of file From 7feaa7af564ba25ad1d9f29563a0dde62242dbf6 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:25:01 +0100 Subject: [PATCH 15/30] This commit closes #14 --- classes/holo_user.py | 2 +- config_example.json | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/classes/holo_user.py b/classes/holo_user.py index d06acca..e3ced82 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -330,7 +330,7 @@ class HoloUser(): await msg.reply_text(locale(f"question2_invalid", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"question{stage}", "force_reply", locale=self.locale)))) return - if datetime.now() <= input_dt: + if (datetime.now() <= input_dt) or ((datetime.now() - input_dt).days) > ((datetime.now() - datetime.now().replace(year=datetime.now().year - configGet("age_maximum"))).days): logWrite(f"User {msg.from_user.id} failed stage {stage} due to joking") await msg.reply_text(locale("question2_joke", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply", locale=self.locale)))) return diff --git a/config_example.json b/config_example.json index c25b48d..d7ddf44 100644 --- a/config_example.json +++ b/config_example.json @@ -3,6 +3,7 @@ "debug": false, "owner": 0, "age_allowed": 0, + "age_maximum": 70, "api": "http://example.com", "inline_preview_count": 7, "remove_application_time": -1, From 431b2d048fb5d92e7c6b5436bb30d1e0d9580c46 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:29:58 +0100 Subject: [PATCH 16/30] This commit closes #11 --- locale/uk.json | 1 + modules/commands/spoiler.py | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/locale/uk.json b/locale/uk.json index 9bd138e..537a816 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -121,6 +121,7 @@ "spoiler_incorrect_category": "Вказана категорія не є дійсною. Будь ласка, користуйся клавіатурою бота (кнопка біля 📎) для вибору категорії.", "spoiler_in_progress": "❌ **Дія неможлива**\nПерш ніж починати нову дію, треба завершити створення спойлера або перервати його командою /cancel.", "youtube_video": "На каналі [{0}]({1}) нове відео!\n\n**[{2}]({3})**", + "not_member": "❌ **Дія неможлива**\nУ тебе немає заповненої та схваленої анкети. Заповни таку за допомогою /reapply та спробуй ще раз після її підтвердження.", "yes": "Так", "no": "Ні", "voice_message": [ diff --git a/modules/commands/spoiler.py b/modules/commands/spoiler.py index 44f858b..e674aa7 100644 --- a/modules/commands/spoiler.py +++ b/modules/commands/spoiler.py @@ -10,7 +10,7 @@ from modules.database import col_spoilers from modules import custom_filters # Spoiler command ============================================================================================================== -@app.on_message(custom_filters.enabled_spoilers & custom_filters.member & ~filters.scheduled & filters.private & filters.command(["spoiler"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_spoilers & ~filters.scheduled & filters.private & filters.command(["spoiler"], prefixes=["/"])) async def cmd_spoiler(app: Client, msg: Message): try: @@ -18,6 +18,11 @@ async def cmd_spoiler(app: Client, msg: Message): except (UserInvalidError, UserNotFoundError): return + if holo_user.application_state()[0] != "approved": + + await msg.reply_text(locale("not_member", "message", locale=msg.from_user)) + 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: From f14e80856cd2f24f7b6fe0d1935deb1bfca14b3e Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 11:57:32 +0100 Subject: [PATCH 17/30] This commit closes --- locale/uk.json | 1 + modules/handlers/group_join.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/locale/uk.json b/locale/uk.json index 537a816..671fc7d 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -91,6 +91,7 @@ "no_user_application": "Не знайдено користувачів за запитом **{0}**", "user_invalid": "Надісланий користувач не має завершеної анкети.", "joined_false_link": "Користувач **{0}** (`{1}`) приєднався до групи не за своїм посиланням", + "joined_application": "{0} (@{1})\n\n**Дані анкети:**\n{2}", "sponsorships_expires": "⚠️ **Нагадування**\nНадана платна підписка припинить діяти **за {0} д**. Будь ласка, оновіть дані про неї командою /sponsorship інакше роль буде втрачено!", "sponsorships_expired": "⚠️ **Нагадування**\nТермін дії вказаної підписки сплив. Для повторного отримання ролі користуйся командою /sponsorship.", "label_too_long": "Довжина назви ролі не повинна перевищувати 16 символів", diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index 2ee00a6..7c26549 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -1,10 +1,13 @@ +from datetime import datetime from app import app, isAnAdmin from pyrogram.types import ChatPermissions, InlineKeyboardMarkup, InlineKeyboardButton, ChatMemberUpdated 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 +from modules.logging import logWrite +from modules.database import col_applications +from classes.holo_user import HoloUser +from dateutil.relativedelta import relativedelta # Filter users on join ========================================================================================================= @app.on_chat_member_updated(custom_filters.enabled_invites_check, group=configGet("users", "groups")) @@ -16,7 +19,28 @@ async def filter_join(app: Client, member: ChatMemberUpdated): holo_user = HoloUser(member.from_user) if (holo_user.link is not None) and (holo_user.link == member.invite_link.invite_link): + logWrite(f"User {holo_user.id} joined destination group with correct link {holo_user.link}") + + application = col_applications.find_one({"user": holo_user.id}) + application_content = [] + i = 1 + + for question in application['application']: + + if i == 2: + age = relativedelta(datetime.now(), application['application']['2']) + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") + elif i == 3: + if application['application']['3']['countryCode'] == "UA": + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}") + + i += 1 + await app.send_message(configGet("users", "groups"), locale("joined_application", "messages").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) return if await isAnAdmin(member.invite_link.creator.id): From 1ce47b0aaf9bf2750b5627cc0afd490a51628e19 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 12:01:35 +0100 Subject: [PATCH 18/30] Polished solution for #18 --- modules/handlers/group_join.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index 7c26549..9f2328c 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -40,11 +40,39 @@ async def filter_join(app: Client, member: ChatMemberUpdated): application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}") i += 1 + await app.send_message(configGet("users", "groups"), locale("joined_application", "messages").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) + return if await isAnAdmin(member.invite_link.creator.id): logWrite(f"User {holo_user.id} joined destination group with link {holo_user.link} of an admin {member.invite_link.creator.id}") + + application = col_applications.find_one({"user": holo_user.id}) + + if application is None: + return + + application_content = [] + i = 1 + + for question in application['application']: + + if i == 2: + age = relativedelta(datetime.now(), application['application']['2']) + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") + elif i == 3: + if application['application']['3']['countryCode'] == "UA": + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + else: + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}") + + i += 1 + + await app.send_message(configGet("users", "groups"), locale("joined_application", "messages").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) + return logWrite(f"User {holo_user.id} joined destination group with stolen/unapproved link {holo_user.link}") From 7be7d5ac7b79c0f00c4c3a32ff1f350431276424 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 12:01:58 +0100 Subject: [PATCH 19/30] One hecking line added --- modules/handlers/group_join.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index 9f2328c..453ccde 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -46,10 +46,11 @@ async def filter_join(app: Client, member: ChatMemberUpdated): return if await isAnAdmin(member.invite_link.creator.id): + logWrite(f"User {holo_user.id} joined destination group with link {holo_user.link} of an admin {member.invite_link.creator.id}") application = col_applications.find_one({"user": holo_user.id}) - + if application is None: return From eeff6d40ce3fbc7f2fa580e3aa33abdf71f8b6c3 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 14:39:38 +0100 Subject: [PATCH 20/30] /issue command --- config_example.json | 10 ++++++++++ holochecker.py | 1 + locale/uk.json | 5 ++++- modules/commands/issue.py | 21 +++++++++++++++++++++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 modules/commands/issue.py diff --git a/config_example.json b/config_example.json index d7ddf44..6ed09ec 100644 --- a/config_example.json +++ b/config_example.json @@ -5,6 +5,7 @@ "age_allowed": 0, "age_maximum": 70, "api": "http://example.com", + "issues": "https://github.com/example/test/issues/new", "inline_preview_count": 7, "remove_application_time": -1, "search_radius": 50, @@ -189,6 +190,15 @@ "sponsorships" ] }, + "issue": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "general" + ] + }, "application": { "permissions": [ "admins", diff --git a/holochecker.py b/holochecker.py index c816c26..be4de80 100644 --- a/holochecker.py +++ b/holochecker.py @@ -15,6 +15,7 @@ from modules.commands.application import * from modules.commands.applications import * from modules.commands.cancel import * from modules.commands.identify import * +from modules.commands.issue import * from modules.commands.label import * from modules.commands.message import * from modules.commands.nearby import * diff --git a/locale/uk.json b/locale/uk.json index 671fc7d..35e7e39 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -123,6 +123,7 @@ "spoiler_in_progress": "❌ **Дія неможлива**\nПерш ніж починати нову дію, треба завершити створення спойлера або перервати його командою /cancel.", "youtube_video": "На каналі [{0}]({1}) нове відео!\n\n**[{2}]({3})**", "not_member": "❌ **Дія неможлива**\nУ тебе немає заповненої та схваленої анкети. Заповни таку за допомогою /reapply та спробуй ще раз після її підтвердження.", + "issue": "**Допоможіть боту**\nЗнайшли баг або помилку? Маєте файну ідею для нової функції? Повідомте нас, створивши нову задачу на гіті.\n\nЗа можливості, опишіть свій запит максимально детально. Якщо є змога, також додайте скріншоти або додаткову відому інформацію.", "yes": "Так", "no": "Ні", "voice_message": [ @@ -233,7 +234,8 @@ "spoiler_view": "Переглянути", "spoiler_preview": "Попередній перегляд", "spoiler_send_chat": "Надіслати в холо-чат", - "spoiler_send_other": "Надіслати в інший чат" + "spoiler_send_other": "Надіслати в інший чат", + "issue": "🪄 Створити задачу" }, "callback": { "sub_accepted": "✅ Анкету {0} схвалено", @@ -290,6 +292,7 @@ "applications": "Отримати всі анкети як JSON", "cancel": "Відмінити актуальну дію", "identify": "Дізнатись дані про користувача за айді", + "issue": "Задачі для покращення бота", "label": "Встановити нікнейм користувачу", "message": "Надіслати користувачу повідомлення", "nearby": "Показати користувачів поблизу", diff --git a/modules/commands/issue.py b/modules/commands/issue.py new file mode 100644 index 0000000..f300455 --- /dev/null +++ b/modules/commands/issue.py @@ -0,0 +1,21 @@ +from typing import Union +from app import app +from pyrogram import filters +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, User, Message +from pyrogram.client import Client +from modules.utils import configGet, locale +from modules import custom_filters +from classes.holo_user import HoloUser + + +# Issue command ================================================================================================================ +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["issue"], prefixes=["/"])) +async def cmd_issue(app: Client, msg: Message): + await msg.reply_text(locale("issue", "message", locale=msg.from_user), disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(locale("issue", "button", locale=msg.from_user), url=configGet("issues")) + ] + ] + )) +# ============================================================================================================================== \ No newline at end of file From a3c27ab4bd6a29fd5c5ed9b298e8f1626e314823 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 14:48:29 +0100 Subject: [PATCH 21/30] Updated default config --- README.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2d5e066..4db0f86 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,9 @@ You can see config file with all the comments below: "debug": false, "owner": 0, "age_allowed": 0, + "age_maximum": 70, "api": "http://example.com", + "issues": "https://github.com/example/test/issues/new", "inline_preview_count": 7, "remove_application_time": -1, "search_radius": 50, @@ -81,7 +83,8 @@ You can see config file with all the comments below: "enabled": false }, "spoilers": { - "enabled": true + "enabled": true, + "allow_external": true } }, "scheduler": { @@ -104,6 +107,11 @@ You can see config file with all the comments below: "cache_admins": { "interval": 120, "enabled": true + }, + "channels_monitor": { + "interval": 5, + "enabled": true, + "channels": [] } }, "locations": { @@ -144,7 +152,6 @@ You can see config file with all the comments below: "permissions": [ "users", "admins", - "group_users", "group_admins" ], "modules": [ @@ -153,7 +160,7 @@ You can see config file with all the comments below: }, "warn": { "permissions": [ - "group_users" + "group_users_admins" ], "modules": [ "warnings" @@ -213,6 +220,15 @@ You can see config file with all the comments below: "sponsorships" ] }, + "issue": { + "permissions": [ + "users", + "admins" + ], + "modules": [ + "general" + ] + }, "application": { "permissions": [ "admins", From b10a62c63e4ac755916bae8e2611c27b27c022da Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 14:50:39 +0100 Subject: [PATCH 22/30] Updated requirements --- requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index d851783..01ea0a5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,8 +2,8 @@ APScheduler==3.9.1.post1 fastapi~=0.88.0 psutil==5.9.4 pymongo==4.3.3 -Pyrogram~=2.0.96 -requests==2.28.1 +Pyrogram~=2.0.97 +requests==2.28.2 tgcrypto==1.2.5 python_dateutil==2.8.2 starlette~=0.22.0 From 66a1ea17ab8255d5637d0f9350bd071dda1a2264 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 23 Jan 2023 15:12:29 +0100 Subject: [PATCH 23/30] This commit is closing #20 --- modules/commands/reapply.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/commands/reapply.py b/modules/commands/reapply.py index da3ee52..c2722fc 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -29,7 +29,7 @@ async def cmd_reapply(app: Client, msg: Message): if left_chat is True: - if (holo_user.application_state()[1] is True and holo_user.application_state()[0] != "fill"): + if (holo_user.application_state()[1] is True and holo_user.application_state()[0] not in ["fill", "rejected"]): await msg.reply_text(locale("reapply_left_chat", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup([ [ From c56385a18120ad91d434e341ebe8d4818c45f652 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Mon, 23 Jan 2023 18:25:03 +0100 Subject: [PATCH 24/30] Fixed spoiler flow --- modules/commands/spoiler.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/commands/spoiler.py b/modules/commands/spoiler.py index e674aa7..8b0f150 100644 --- a/modules/commands/spoiler.py +++ b/modules/commands/spoiler.py @@ -6,7 +6,7 @@ from classes.errors.holo_user import UserNotFoundError, UserInvalidError from classes.holo_user import HoloUser from modules.logging import logWrite from modules.utils import locale -from modules.database import col_spoilers +from modules.database import col_spoilers, col_applications from modules import custom_filters # Spoiler command ============================================================================================================== @@ -18,18 +18,18 @@ async def cmd_spoiler(app: Client, msg: Message): except (UserInvalidError, UserNotFoundError): return - if holo_user.application_state()[0] != "approved": + if col_applications.find_one( {"user": holo_user.id} ) is None: await msg.reply_text(locale("not_member", "message", locale=msg.from_user)) 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: + if col_spoilers.find_one( {"user": holo_user.id, "completed": False} ) is None: col_spoilers.insert_one( { - "user": msg.from_user.id, + "user": holo_user.id, "completed": False, "category": None, "description": None, From fd19b4cb0b82271afcf0fede5ed6cdb1d8f37f69 Mon Sep 17 00:00:00 2001 From: profitroll Date: Wed, 25 Jan 2023 14:05:00 +0100 Subject: [PATCH 25/30] Seems like added a grayout for sponsors --- modules/scheduled.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/scheduled.py b/modules/scheduled.py index 2d17eaa..c3f5706 100644 --- a/modules/scheduled.py +++ b/modules/scheduled.py @@ -93,7 +93,7 @@ if configGet("enabled", "features", "sponsorships") is True: 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()}}): + for entry in col_sponsorships.find({"sponsorship.expires": {"$lt": datetime.now()-timedelta(days=1)}}): try: holo_user = HoloUser(entry["user"]) col_sponsorships.find_one_and_delete({"user": holo_user.id}) From eaec6f2fe8eb886ba8011c5e0c40bc369ee4dc7f Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 30 Jan 2023 10:39:14 +0100 Subject: [PATCH 26/30] Fixed join messages not being sent --- modules/handlers/group_join.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/handlers/group_join.py b/modules/handlers/group_join.py index 453ccde..5786b4b 100644 --- a/modules/handlers/group_join.py +++ b/modules/handlers/group_join.py @@ -41,7 +41,7 @@ async def filter_join(app: Client, member: ChatMemberUpdated): i += 1 - await app.send_message(configGet("users", "groups"), locale("joined_application", "messages").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) + await app.send_message(configGet("users", "groups"), locale("joined_application", "message").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) return @@ -72,7 +72,7 @@ async def filter_join(app: Client, member: ChatMemberUpdated): i += 1 - await app.send_message(configGet("users", "groups"), locale("joined_application", "messages").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) + await app.send_message(configGet("users", "groups"), locale("joined_application", "message").format(member.from_user.first_name, member.from_user.username, "\n".join(application_content))) return From f98fb0b6dc5a8ad1d7dcfce9f874d7c0f500a724 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 30 Jan 2023 10:54:43 +0100 Subject: [PATCH 27/30] Probably fix for static emojis from #25 --- classes/holo_user.py | 4 ++-- modules/commands/message.py | 6 +++--- modules/handlers/everything.py | 27 +++++++++++++++------------ 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/classes/holo_user.py b/classes/holo_user.py index e3ced82..9def05e 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -319,7 +319,7 @@ class HoloUser(): if progress["state"] == "fill" and progress["sent"] is False: if msg.text is not None: - msg.text = fix_text(msg.text) + msg.text = fix_text(str(msg.text)) if stage == 2: @@ -445,7 +445,7 @@ class HoloUser(): stage = progress["stage"] if msg.text is not None: - msg.text = fix_text(msg.text) + msg.text = fix_text(str(msg.text)) elif msg.caption is not None: msg.caption = fix_text(msg.caption) diff --git a/modules/commands/message.py b/modules/commands/message.py index 50c6b0a..b2f582a 100644 --- a/modules/commands/message.py +++ b/modules/commands/message.py @@ -18,10 +18,10 @@ async def cmd_message(app: Client, msg: Message): except (ValueError, UserInvalidError): destination = HoloUser(await find_user(app, query=msg.command[1])) - if ((msg.text is not None) and (len(msg.text.split()) > 2)): - await destination.message(context=msg, text=" ".join(msg.text.split()[2:]), caption=msg.caption, photo=msg.photo, video=msg.video, file=msg.document, voice=msg.voice, animation=msg.animation, adm_context=True) + if ((msg.text is not None) and (len(str(msg.text).split()) > 2)): + await destination.message(context=msg, text=" ".join(str(msg.text).split()[2:]), caption=msg.caption, photo=msg.photo, video=msg.video, file=msg.document, voice=msg.voice, animation=msg.animation, adm_context=True) elif ((msg.caption is not None) and (len(msg.caption.split()) > 2)): - await destination.message(context=msg, text=msg.text, caption=" ".join(msg.caption.split()[2:]), photo=msg.photo, video=msg.video, file=msg.document, voice=msg.voice, animation=msg.animation, adm_context=True) + await destination.message(context=msg, text=str(msg.text), caption=" ".join(msg.caption.split()[2:]), photo=msg.photo, video=msg.video, file=msg.document, voice=msg.voice, animation=msg.animation, adm_context=True) else: await destination.message(context=msg, text=None, caption=None, photo=msg.photo, video=msg.video, file=msg.document, voice=msg.voice, animation=msg.animation, adm_context=True) diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index d79f7dc..2464fe9 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -36,10 +36,13 @@ async def any_stage(app: Client, msg: Message): destination_user = HoloUser(context_message.from_user) + if destination_user is None: + return + await destination_user.message( origin=context_message, context=msg, - text=msg.text, + text=str(msg.text), caption=msg.caption, photo=msg.photo, video=msg.video, @@ -58,14 +61,14 @@ async def any_stage(app: Client, msg: Message): if msg.text is not None: if configGet("enabled", "features", "applications") is True: - await holo_user.application_next(msg.text, msg=msg) + await holo_user.application_next(str(msg.text), msg=msg) if configGet("enabled", "features", "sponsorships") is True: - await holo_user.sponsorship_next(msg.text, msg) + await holo_user.sponsorship_next(str(msg.text), msg) if msg.photo is not None: - await holo_user.sponsorship_next(msg.text, msg=msg, photo=msg.photo) + await holo_user.sponsorship_next(str(msg.text), msg=msg, photo=msg.photo) if holo_user.application_state()[0] != "fill" and holo_user.sponsorship_state()[0] != "fill": @@ -84,7 +87,7 @@ async def any_stage(app: Client, msg: Message): # Find category in all locales for lc in all_locales("spoiler_categories", "message"): for key in lc: - if lc[key] == msg.text: + if lc[key] == str(msg.text): found = True category = key @@ -104,16 +107,16 @@ async def any_stage(app: Client, msg: Message): # return - if msg.text != "-": - msg.text = fix_text(msg.text) - if len(msg.text) > 1024: + if str(msg.text) != "-": + msg.text = fix_text(str(msg.text)) + if len(str(msg.text)) > 1024: await msg.reply_text(locale("spoiler_description_too_long", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("spoiler_description", "force_reply", locale=msg.from_user))) return col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"description": msg.text}} ) else: col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"description": ""}} ) - logWrite(f"Adding description '{msg.text}' to {msg.from_user.id}'s spoiler") + logWrite(f"Adding description '{str(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=ForceReply(placeholder=locale("spoiler_content", "force_reply", locale=msg.from_user))) return @@ -147,8 +150,8 @@ async def any_stage(app: Client, msg: Message): if spoiler["photo"] is None and spoiler["video"] is None and spoiler["audio"] is None and spoiler["animation"] is None and spoiler["document"] is None and spoiler["text"] is None: if msg.text is not None: - col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"text": msg.text, "completed": True}} ) - logWrite(f"Adding text '{msg.text}' to {msg.from_user.id}'s spoiler") + col_spoilers.find_one_and_update( {"user": msg.from_user.id, "completed": False}, {"$set": {"text": str(msg.text), "completed": True}} ) + logWrite(f"Adding text '{str(msg.text)}' to {msg.from_user.id}'s spoiler") ready = True if ready is True: @@ -191,7 +194,7 @@ 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]): + if str(msg.text).startswith(locale("spoiler_described", "message").split()[0]) or str(msg.text).startswith(locale("spoiler_empty", "message").split()[0]): logWrite(f"User {msg.from_user.id} sent spoiler to user's group") try: logWrite("Forwarding spoiler to admin's group") From 360bdf2c728e7b078402aa0883d26cf12c2ba30a Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 30 Jan 2023 10:58:47 +0100 Subject: [PATCH 28/30] This commit closes #24 --- locale/uk.json | 3 ++- modules/handlers/everything.py | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/locale/uk.json b/locale/uk.json index 35e7e39..f7997c5 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -117,7 +117,8 @@ "spoiler_description_too_long": "Текст занадто довгий. Будь ласка, умісти опис у 1024 символи.", "spoiler_using_description": "Встановлено опис спойлера: {0}\n\nЗалишилось додати вміст самого спойлера. Бот приймає текстове повідомлення, фото, відео, файл а також гіф зображення (1 шт.)", "spoiler_send_description": "Тепер треба надіслати коротенький опис спойлера, щоб люди розуміли що під ним варто очкувати. Надішли мінус (-) щоб пропустити цей крок.", - "spoiler_ready": "Успіх! Спойлер створено. Користуйтесь кнопкою нижче щоб надіслати його.", + "spoiler_ready": "Успіх! Спойлер створено", + "spoiler_send": "Користуйтесь кнопкою нижче щоб надіслати його.", "spoiler_incorrect_content": "Бот не підтримує такий контент. Будь ласка, надішли текст, фото, відео, файл або анімацію (гіф).", "spoiler_incorrect_category": "Вказана категорія не є дійсною. Будь ласка, користуйся клавіатурою бота (кнопка біля 📎) для вибору категорії.", "spoiler_in_progress": "❌ **Дія неможлива**\nПерш ніж починати нову дію, треба завершити створення спойлера або перервати його командою /cancel.", diff --git a/modules/handlers/everything.py b/modules/handlers/everything.py index 2464fe9..b8e1547 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -3,7 +3,7 @@ from app import app, isAnAdmin import asyncio from ftfy import fix_text from pyrogram import filters -from pyrogram.types import Message, ForceReply, InlineKeyboardMarkup, InlineKeyboardButton +from pyrogram.types import Message, ForceReply, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove from pyrogram.client import Client from classes.holo_user import HoloUser from modules.utils import configGet, logWrite, locale, all_locales @@ -155,9 +155,10 @@ async def any_stage(app: Client, msg: Message): ready = True if ready is True: + await msg.reply_text(locale("spoiler_ready", "message", locale=msg.from_user), reply_markup=ReplyKeyboardRemove()) if configGet("allow_external", "features", "spoilers") is True: await msg.reply_text( - locale("spoiler_ready", "message", locale=msg.from_user), + locale("spoiler_send", "message", locale=msg.from_user), reply_markup=InlineKeyboardMarkup( [ [ @@ -174,7 +175,7 @@ async def any_stage(app: Client, msg: Message): ) else: await msg.reply_text( - locale("spoiler_ready", "message", locale=msg.from_user), + locale("spoiler_send", "message", locale=msg.from_user), reply_markup=InlineKeyboardMarkup( [ [ From 82a878aa6d54992ed48cbca12b358c4674092556 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 30 Jan 2023 11:01:52 +0100 Subject: [PATCH 29/30] WIP: #17 --- modules/custom_filters.py | 10 +++++++++- modules/database.py | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/modules/custom_filters.py b/modules/custom_filters.py index 529a055..bc217cc 100644 --- a/modules/custom_filters.py +++ b/modules/custom_filters.py @@ -4,10 +4,11 @@ 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, col_tmp +from modules.database import col_applications, col_tmp, col_bans from pyrogram import filters from pyrogram.types import Message + async def admin_func(_, __, msg: Message): return await isAnAdmin(msg.from_user.id) @@ -21,6 +22,11 @@ async def allowed_func(_, __, msg: Message): output = False return output + +async def banned_func(_, __, msg: Message): + return True if col_bans.find_one( {"user": msg.from_user.id} ) is not None else False + + async def enabled_general_func(_, __, msg: Message): return configGet("enabled", "features", "general") @@ -49,6 +55,8 @@ admin = filters.create(admin_func) member = filters.create(member_func) allowed = filters.create(allowed_func) +banned = filters.create(banned_func) + enabled_general = filters.create(enabled_general_func) enabled_applications = filters.create(enabled_applications_func) enabled_sponsorships = filters.create(enabled_sponsorships_func) diff --git a/modules/database.py b/modules/database.py index a7f3c67..94775e8 100644 --- a/modules/database.py +++ b/modules/database.py @@ -28,11 +28,12 @@ db = db_client.get_database(name=db_config["name"]) collections = db.list_collection_names() -for collection in ["tmp", "users", "context", "youtube", "spoilers", "messages", "warnings", "applications", "sponsorships"]: +for collection in ["tmp", "bans", "users", "context", "youtube", "spoilers", "messages", "warnings", "applications", "sponsorships"]: if not collection in collections: db.create_collection(collection) col_tmp = db.get_collection("tmp") +col_bans = db.get_collection("bans") col_users = db.get_collection("users") col_context = db.get_collection("context") col_youtube = db.get_collection("youtube") From 23b2925ffaf0ed6bbd3f53248076f438f72eabe6 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 30 Jan 2023 11:28:23 +0100 Subject: [PATCH 30/30] This commit closes #17 --- holochecker.py | 1 + locale/uk.json | 6 +++++- modules/callbacks/ban.py | 27 +++++++++++++++++++++++++++ modules/callbacks/reapply.py | 2 +- modules/callbacks/sub.py | 2 +- modules/commands/cancel.py | 2 +- modules/commands/issue.py | 2 +- modules/commands/nearby.py | 2 +- modules/commands/reapply.py | 2 +- modules/commands/rules.py | 2 +- modules/commands/spoiler.py | 2 +- modules/commands/sponsorship.py | 2 +- modules/commands/start.py | 2 +- modules/handlers/confirmation.py | 4 ++-- modules/handlers/contact.py | 2 +- modules/handlers/everything.py | 3 ++- modules/handlers/welcome.py | 4 ++-- 17 files changed, 50 insertions(+), 17 deletions(-) create mode 100644 modules/callbacks/ban.py diff --git a/holochecker.py b/holochecker.py index be4de80..50d434d 100644 --- a/holochecker.py +++ b/holochecker.py @@ -29,6 +29,7 @@ from modules.commands.start import * from modules.commands.warn import * from modules.commands.warnings import * +from modules.callbacks.ban import * from modules.callbacks.nothing import * from modules.callbacks.reapply import * from modules.callbacks.rules import * diff --git a/locale/uk.json b/locale/uk.json index f7997c5..440becb 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -125,6 +125,7 @@ "youtube_video": "На каналі [{0}]({1}) нове відео!\n\n**[{2}]({3})**", "not_member": "❌ **Дія неможлива**\nУ тебе немає заповненої та схваленої анкети. Заповни таку за допомогою /reapply та спробуй ще раз після її підтвердження.", "issue": "**Допоможіть боту**\nЗнайшли баг або помилку? Маєте файну ідею для нової функції? Повідомте нас, створивши нову задачу на гіті.\n\nЗа можливості, опишіть свій запит максимально детально. Якщо є змога, також додайте скріншоти або додаткову відому інформацію.", + "you_are_banned": "⚠️ **Вас було заблоковано**\nТепер не можна відправити анкету або користуватись командами бота.", "yes": "Так", "no": "Ні", "voice_message": [ @@ -236,7 +237,9 @@ "spoiler_preview": "Попередній перегляд", "spoiler_send_chat": "Надіслати в холо-чат", "spoiler_send_other": "Надіслати в інший чат", - "issue": "🪄 Створити задачу" + "issue": "🪄 Створити задачу", + "ban": "💀 Заблокувати", + "banned": "☠️ Заблоковано" }, "callback": { "sub_accepted": "✅ Анкету {0} схвалено", @@ -244,6 +247,7 @@ "sub_russian": "🇷🇺 Анкету {0} відхилено", "sus_allowed": "✅ Доступ {0} дозволено", "sus_rejected": "❌ Доступ {0} заборонено", + "sub_banned": "☠️ Користувача заблоковано", "nothing": "🔔 Дія вже виконана", "rules_page": "ℹ️ Показано правило {0}", "rules_home": "ℹ️ Показано головну правил", diff --git a/modules/callbacks/ban.py b/modules/callbacks/ban.py new file mode 100644 index 0000000..b34ad76 --- /dev/null +++ b/modules/callbacks/ban.py @@ -0,0 +1,27 @@ +from app import app, isAnAdmin +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery +from pyrogram import filters +from pyrogram.client import Client +from modules.utils import locale +from modules.database import col_bans +from modules.logging import logWrite + +@app.on_callback_query(filters.regex("ban_[\s\S]*")) +async def callback_query_reject(app: Client, clb: CallbackQuery): + + fullclb = clb.data.split("_") + + if not await isAnAdmin(int(fullclb[1])): + col_bans.insert_one( {"user": int(fullclb[1])} ) + + edited_markup = [[InlineKeyboardButton(text=str(locale("banned", "button")), callback_data="nothing")]] + + await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) + await clb.answer(text=locale("sub_banned", "callback", locale=clb.from_user)) + + logWrite(f"User {fullclb[1]} has been banned by {clb.from_user.id}") + + try: + await app.send_message(int(fullclb[1]), locale("you_are_banned", "message")) + except Exception as exp: + logWrite(f"Could send ban message to {fullclb[1]} due to {exp}") \ No newline at end of file diff --git a/modules/callbacks/reapply.py b/modules/callbacks/reapply.py index 121a7d3..13671f2 100644 --- a/modules/callbacks/reapply.py +++ b/modules/callbacks/reapply.py @@ -75,7 +75,7 @@ async def callback_query_reapply_reject(app: Client, clb: CallbackQuery): col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) - edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]] + edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")], [InlineKeyboardButton(text=str(locale("ban", "button")), callback_data=f"ban_{fullclb[2]}")]] await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sub_rejected", "callback", locale=clb.from_user).format(fullclb[2]), show_alert=True) diff --git a/modules/callbacks/sub.py b/modules/callbacks/sub.py index f806f50..e9ba485 100644 --- a/modules/callbacks/sub.py +++ b/modules/callbacks/sub.py @@ -63,7 +63,7 @@ async def callback_query_reject(app: Client, clb: CallbackQuery): col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) - edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")]] + edited_markup = [[InlineKeyboardButton(text=str(locale("declined", "button")), callback_data="nothing")], [InlineKeyboardButton(text=str(locale("ban", "button")), callback_data=f"ban_{fullclb[2]}")]] await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) await clb.answer(text=locale("sub_rejected", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) diff --git a/modules/commands/cancel.py b/modules/commands/cancel.py index 8721dc8..d46fa6f 100644 --- a/modules/commands/cancel.py +++ b/modules/commands/cancel.py @@ -7,7 +7,7 @@ from modules.database import col_tmp, col_spoilers, col_applications from modules import custom_filters # Cancel command =============================================================================================================== -@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("cancel", prefixes=["/"])) +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.command("cancel", prefixes=["/"]) & ~custom_filters.banned) async def command_cancel(app: Client, msg: Message): col_tmp.delete_many( {"user": msg.from_user.id, "sent": False} ) col_spoilers.delete_many( {"user": msg.from_user.id, "completed": False} ) diff --git a/modules/commands/issue.py b/modules/commands/issue.py index f300455..b6dd9bb 100644 --- a/modules/commands/issue.py +++ b/modules/commands/issue.py @@ -9,7 +9,7 @@ from classes.holo_user import HoloUser # Issue command ================================================================================================================ -@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["issue"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["issue"], prefixes=["/"]) & ~custom_filters.banned) async def cmd_issue(app: Client, msg: Message): await msg.reply_text(locale("issue", "message", locale=msg.from_user), disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [ diff --git a/modules/commands/nearby.py b/modules/commands/nearby.py index f0a80a4..993322b 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("users", "groups")))) & 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) & ~custom_filters.banned) 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 c2722fc..70e5105 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -10,7 +10,7 @@ from modules.database import col_tmp, col_applications from modules import custom_filters # Reapply command ============================================================================================================== -@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(["reapply"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(["reapply"], prefixes=["/"]) & ~custom_filters.banned) async def cmd_reapply(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) diff --git a/modules/commands/rules.py b/modules/commands/rules.py index f81a701..3ddc3b5 100644 --- a/modules/commands/rules.py +++ b/modules/commands/rules.py @@ -36,7 +36,7 @@ class DefaultRulesMarkup(list): # Rules command ============================================================================================================= -@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & filters.command(["rules"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_general & ~filters.scheduled & filters.private & ~custom_filters.banned & 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/commands/spoiler.py b/modules/commands/spoiler.py index 8b0f150..b28429c 100644 --- a/modules/commands/spoiler.py +++ b/modules/commands/spoiler.py @@ -10,7 +10,7 @@ from modules.database import col_spoilers, col_applications from modules import custom_filters # Spoiler command ============================================================================================================== -@app.on_message(custom_filters.enabled_spoilers & ~filters.scheduled & filters.private & filters.command(["spoiler"], prefixes=["/"])) +@app.on_message(custom_filters.enabled_spoilers & ~filters.scheduled & filters.private & ~custom_filters.banned & filters.command(["spoiler"], prefixes=["/"])) async def cmd_spoiler(app: Client, msg: Message): try: diff --git a/modules/commands/sponsorship.py b/modules/commands/sponsorship.py index 4896b2a..46cc05a 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(custom_filters.enabled_sponsorships & ~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.banned & (custom_filters.allowed | custom_filters.admin)) async def cmd_sponsorship(app: Client, msg: Message): holo_user = HoloUser(msg.from_user) if holo_user.application_state()[0] == "fill": diff --git a/modules/commands/start.py b/modules/commands/start.py index 85b8e0c..0452507 100644 --- a/modules/commands/start.py +++ b/modules/commands/start.py @@ -9,7 +9,7 @@ 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=["/"])) +@app.on_message(custom_filters.enabled_applications & ~filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"]) & ~custom_filters.banned) async def cmd_start(app: Client, msg: Message): user = col_users.find_one({"user": msg.from_user.id}) diff --git a/modules/handlers/confirmation.py b/modules/handlers/confirmation.py index 9dc8a79..51e82da 100644 --- a/modules/handlers/confirmation.py +++ b/modules/handlers/confirmation.py @@ -16,7 +16,7 @@ from modules import custom_filters confirmation_1 = [] for pattern in all_locales("confirm", "keyboard"): confirmation_1.append(pattern[0][0]) -@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.private & filters.command(confirmation_1, prefixes=[""])) +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.private & filters.command(confirmation_1, prefixes=[""]) & ~custom_filters.banned) async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "sponsorship", "unknown"] = "unknown"): holo_user = HoloUser(msg.from_user) @@ -145,7 +145,7 @@ async def confirm_yes(app: Client, msg: Message, kind: Literal["application", "s confirmation_2 = [] for pattern in all_locales("confirm", "keyboard"): confirmation_2.append(pattern[1][0]) -@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.private & filters.command(confirmation_2, prefixes=[""])) +@app.on_message((custom_filters.enabled_applications | custom_filters.enabled_sponsorships) & ~filters.scheduled & filters.private & filters.command(confirmation_2, prefixes=[""]) & ~custom_filters.banned) async def confirm_no(app: Client, msg: Message, kind: Literal["application", "sponsorship", "unknown"] = "unknown"): holo_user = HoloUser(msg.from_user) diff --git a/modules/handlers/contact.py b/modules/handlers/contact.py index 83f3122..1a75fef 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(custom_filters.enabled_applications & ~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) & ~custom_filters.banned) 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 b8e1547..9cc5f0c 100644 --- a/modules/handlers/everything.py +++ b/modules/handlers/everything.py @@ -8,6 +8,7 @@ from pyrogram.client import Client from classes.holo_user import HoloUser from modules.utils import configGet, logWrite, locale, all_locales from modules.database import col_messages, col_spoilers +from modules import custom_filters 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}) @@ -22,7 +23,7 @@ async def message_context(msg: Message) -> tuple: return 0, 0 # Any other input ============================================================================================================== -@app.on_message(~ filters.scheduled & (filters.private | filters.chat(configGet("admin", "groups")))) +@app.on_message(~ filters.scheduled & (filters.private | filters.chat(configGet("admin", "groups"))) & ~custom_filters.banned) async def any_stage(app: Client, msg: Message): if msg.via_bot is None: diff --git a/modules/handlers/welcome.py b/modules/handlers/welcome.py index 2450178..5b139d2 100644 --- a/modules/handlers/welcome.py +++ b/modules/handlers/welcome.py @@ -12,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(custom_filters.enabled_applications & ~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=[""]) & ~custom_filters.banned) async def welcome_pass(app: Client, msg: Message, once_again: bool = False) -> None: """Set user's stage to 1 and start a fresh application @@ -39,7 +39,7 @@ async def welcome_pass(app: Client, msg: Message, once_again: bool = False) -> N welcome_2 = [] for pattern in all_locales("welcome", "keyboard"): welcome_2.append(pattern[1][0]) -@app.on_message(custom_filters.enabled_applications & ~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=[""]) & ~custom_filters.banned) async def welcome_reject(app: Client, msg: Message): logWrite(f"User {msg.from_user.id} rejected to start the application")