From cfc8167663b7a5c45d9806291334cf80aa366663 Mon Sep 17 00:00:00 2001 From: profitroll Date: Wed, 26 Oct 2022 14:54:55 +0200 Subject: [PATCH] Inline implemented --- README.md | 2 +- app.py | 12 ++++ locale/uk.json | 17 ++++++ main.py | 114 ++++++++++++++++++-------------------- modules/inline.py | 136 ++++++++++++++++++++++++++++++++++++++++++++++ modules/utils.py | 22 ++++---- 6 files changed, 230 insertions(+), 73 deletions(-) create mode 100644 app.py create mode 100644 modules/inline.py diff --git a/README.md b/README.md index 1a05ef3..605dedc 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ After all of that you're good to go! Happy using :) ## To-Do * [x] Check if link belongs to admin -* [ ] Inline query user's application +* [x] Inline query user's application * [x] Get applications .json * [ ] Get application by id and user_id * [x] Age as a DD.MM.YYYY diff --git a/app.py b/app.py new file mode 100644 index 0000000..bd365a3 --- /dev/null +++ b/app.py @@ -0,0 +1,12 @@ +from modules.utils import configGet +from pyrogram.client import Client + +app = Client("holochecker", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot")) + +async def isAnAdmin(admin_id): + if admin_id == configGet("owner") or admin_id in configGet("admins"): + return True + async for member in app.get_chat_members(configGet("admin_group")): + if member.user.id == admin_id: + return True + return False \ No newline at end of file diff --git a/locale/uk.json b/locale/uk.json index d275f95..9e62a8f 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -124,5 +124,22 @@ "sus_allowed": "✅ Доступ {0} дозволено", "sus_refused": "❌ Доступ {0} заборонено", "nothing": "🔔 Дія вже виконана" + }, + "inline": { + "forbidden": { + "title": "Дія недоступна", + "description": "Ти не маєш дозволу переглядати це", + "message_content": "Немає дозволу на перегляд." + }, + "not_pm": { + "title": "Дія недоступна", + "description": "Ця команда доступна тільки в приватних повідомленнях в чаті з самим ботом", + "message_content": "Дія доступна тільки в ПП." + }, + "user": { + "title": "", + "description": "Переглянути анкету {0} (@{1})", + "message_content": "{0} (@{1})\n\n**Дані анкети:**\n{2}" + } } } \ No newline at end of file diff --git a/main.py b/main.py index faf39cc..78eef65 100644 --- a/main.py +++ b/main.py @@ -5,9 +5,10 @@ from time import time from os import getpid, path from modules.birthdays import check_birthdays from modules.utils import * +from modules.inline import * from schedule import run_pending, every +from app import app -from pyrogram.client import Client from pyrogram import filters from pyrogram.enums.parse_mode import ParseMode from pyrogram.enums.chat_action import ChatAction @@ -17,7 +18,6 @@ from pyrogram.errors.exceptions import bad_request_400 pid = getpid() -app = Client("holochecker", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot")) for entry in [f"{configGet('data', 'locations')}{sep}applications.json"]: @@ -28,16 +28,6 @@ for entry in [f"{configGet('data', 'locations')}{sep}applications.json"]: except: pass - -async def isAnAdmin(admin_id): - if admin_id == configGet("owner") or admin_id in configGet("admins"): - return True - async for member in app.get_chat_members(configGet("admin_group")): - if member.user.id == admin_id: - return True - return False - - # Start command ================================================================================================================ @app.on_message(~ filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"])) async def cmd_start(app, msg): @@ -472,63 +462,65 @@ async def get_contact(app, msg): @app.on_message(~ filters.scheduled & filters.private) async def any_stage(app, msg): - user_stage = configGet("stage", file=str(msg.from_user.id)) - - if user_stage == 1: - await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply")))) - logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application") - configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) - configSet("stage", user_stage+1, file=str(msg.from_user.id)) + if msg.via_bot == None: - elif user_stage == 2: - - try: - - configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) - - input_dt = datetime.strptime(msg.text, "%d.%m.%Y") - - if datetime.now() <= input_dt: - logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to joking") - await msg.reply_text(locale("question2_joke", "message"), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply")))) - - elif ((datetime.now() - input_dt).days) < ((datetime.now() - datetime.now().replace(year=datetime.now().year - configGet("age_allowed"))).days): - logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to being underage") - await msg.reply_text(locale("question2_underage", "message").format(str(configGet("age_allowed"))), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply")))) # type: ignore - - else: - logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application") - await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply")))) - configSet("stage", user_stage+1, file=str(msg.from_user.id)) - - except ValueError: - logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to sending invalid date format") - await msg.reply_text(locale(f"question2_invalid", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage}", "force_reply")))) - - else: - if user_stage <= 9: - logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application") + user_stage = configGet("stage", file=str(msg.from_user.id)) + + if user_stage == 1: await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply")))) + logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application") configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) configSet("stage", user_stage+1, file=str(msg.from_user.id)) + + elif user_stage == 2: + + try: + + configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) + + input_dt = datetime.strptime(msg.text, "%d.%m.%Y") + + if datetime.now() <= input_dt: + logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to joking") + await msg.reply_text(locale("question2_joke", "message"), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply")))) + + elif ((datetime.now() - input_dt).days) < ((datetime.now() - datetime.now().replace(year=datetime.now().year - configGet("age_allowed"))).days): + logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to being underage") + await msg.reply_text(locale("question2_underage", "message").format(str(configGet("age_allowed"))), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply")))) # type: ignore + + else: + logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application") + await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply")))) + configSet("stage", user_stage+1, file=str(msg.from_user.id)) + + except ValueError: + logWrite(f"User {msg.from_user.id} failed stage {user_stage} due to sending invalid date format") + await msg.reply_text(locale(f"question2_invalid", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage}", "force_reply")))) + else: - if not configGet("sent", file=str(msg.from_user.id)): - if not configGet("confirmed", file=str(msg.from_user.id)): - configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) - application_content = [] - i = 1 - for question in configGet("application", file=str(msg.from_user.id)): - application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(msg.from_user.id))[question]}") - i += 1 - await msg.reply_text(locale("confirm", "message").format("\n".join(application_content)), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard"), resize_keyboard=True)) # type: ignore - #configSet("sent", True, file=str(msg.from_user.id)) - #configSet("application_date", int(time()), file=str(msg.from_user.id)) + if user_stage <= 9: + logWrite(f"User {msg.from_user.id} completed stage {user_stage} of application") + await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{user_stage+1}", "force_reply")))) + configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) + configSet("stage", user_stage+1, file=str(msg.from_user.id)) + else: + if not configGet("sent", file=str(msg.from_user.id)): + if not configGet("confirmed", file=str(msg.from_user.id)): + configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) + application_content = [] + i = 1 + for question in configGet("application", file=str(msg.from_user.id)): + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(msg.from_user.id))[question]}") + i += 1 + await msg.reply_text(locale("confirm", "message").format("\n".join(application_content)), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard"), resize_keyboard=True)) # type: ignore + #configSet("sent", True, file=str(msg.from_user.id)) + #configSet("application_date", int(time()), file=str(msg.from_user.id)) + else: + if not configGet("approved", file=str(msg.from_user.id)) and not configGet("refused", file=str(msg.from_user.id)): + await msg.reply_text(locale("already_sent", "message")) else: if not configGet("approved", file=str(msg.from_user.id)) and not configGet("refused", file=str(msg.from_user.id)): await msg.reply_text(locale("already_sent", "message")) - else: - if not configGet("approved", file=str(msg.from_user.id)) and not configGet("refused", file=str(msg.from_user.id)): - await msg.reply_text(locale("already_sent", "message")) # ============================================================================================================================== diff --git a/modules/inline.py b/modules/inline.py new file mode 100644 index 0000000..0676dd8 --- /dev/null +++ b/modules/inline.py @@ -0,0 +1,136 @@ +from datetime import datetime +from os import path, sep +from pyrogram.types import InlineQueryResultArticle, InputTextMessageContent +from pyrogram.enums.chat_type import ChatType +from pyrogram.enums.chat_members_filter import ChatMembersFilter +from dateutil.relativedelta import relativedelta + +from app import app, isAnAdmin +from modules.utils import configGet, jsonLoad, locale + +@app.on_inline_query() +async def inline_answer(client, inline_query): + + if inline_query.chat_type not in [ChatType.BOT, ChatType.PRIVATE]: + await inline_query.answer( + results=[ + InlineQueryResultArticle( + title=locale("title", "inline", "not_pm"), + input_message_content=InputTextMessageContent( + locale("message_content", "inline", "not_pm") + ), + description=locale("description", "inline", "not_pm") + ) + ] + ) + return + + if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{inline_query.from_user.id}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{inline_query.from_user.id}.json")["approved"]) or (await isAnAdmin(inline_query.from_user.id)): + + list_of_users = [] + async for m in app.get_chat_members(configGet("admin_group"), filter=ChatMembersFilter.SEARCH, query=inline_query.query): + list_of_users.append(m) + + #list_of_names = [] + + #list_filtered = [v for v in (list_of_users) if inline_query.query in v] + + results = [] + + for match in list_of_users: + # if match.user.photo != None: + # results.append( + # InlineQueryResultArticle( + # title=str(match.user.first_name), + # input_message_content=InputTextMessageContent( + # f"More about @{match.user.username}" + # ), + # description=f"More info about {match.user.username}", + # thumb_url=f'https://api.telegram.org/bot{configGet("bot_token", "bot")}/{match.user.photo.big_file_id}', + # thumb_height=640, + # thumb_width=640 + # ) + # ) + # else: + + try: + user_data = jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{match.user.id}.json") + application_content = [] + i = 1 + for question in configGet("application", file=str(match.user.id)): + if i == 2: + age = relativedelta(datetime.now(), datetime.strptime(configGet('application', file=str(match.user.id))['2'], '%d.%m.%Y')) + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(match.user.id))['2']} ({age.years} р.)") + else: + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {configGet('application', file=str(match.user.id))[question]}") + i += 1 + results.append( + InlineQueryResultArticle( + title=str(match.user.first_name), + input_message_content=InputTextMessageContent( + locale("message_content", "inline", "user").format(match.user.first_name, match.user.username, "\n".join(application_content)) + ), + description=locale("description", "inline", "user").format(match.user.first_name, match.user.username) + ) + ) + except FileNotFoundError: + pass + except TypeError: + pass + + await inline_query.answer( + results=results, + cache_time=10 + ) + + # await inline_query.answer( + # results=[ + # InlineQueryResultArticle( + # title="Installation", + # input_message_content=InputTextMessageContent( + # "Here's how to install **Pyrogram**" + # ), + # url="https://docs.pyrogram.org/intro/install", + # description="How to install Pyrogram", + # reply_markup=InlineKeyboardMarkup( + # [ + # [InlineKeyboardButton( + # "Open website", + # url="https://docs.pyrogram.org/intro/install" + # )] + # ] + # ) + # ), + # InlineQueryResultArticle( + # title="Usage", + # input_message_content=InputTextMessageContent( + # "Here's how to use **Pyrogram**" + # ), + # url="https://docs.pyrogram.org/start/invoking", + # description="How to use Pyrogram", + # reply_markup=InlineKeyboardMarkup( + # [ + # [InlineKeyboardButton( + # "Open website", + # url="https://docs.pyrogram.org/start/invoking" + # )] + # ] + # ) + # ) + # ], + # cache_time=1 + # ) + + else: + await inline_query.answer( + results=[ + InlineQueryResultArticle( + title=locale("title", "inline", "forbidden"), + input_message_content=InputTextMessageContent( + locale("message_content", "inline", "forbidden") + ), + description=locale("description", "inline", "forbidden") + ) + ] + ) + return \ No newline at end of file diff --git a/modules/utils.py b/modules/utils.py index 6cf6744..54d7893 100644 --- a/modules/utils.py +++ b/modules/utils.py @@ -44,15 +44,15 @@ def configSet(key: str, value, *args: str, file: str = "config"): """ if file == "config": filepath = "" + if this_dict["debug"]: + try: + this_dict = jsonLoad("config_debug.json") + file = "config_debug" + except FileNotFoundError: + print("Debug mode is set but config_debug.json is not there! Falling back to config.json", flush=True) else: filepath = f"data{sep}users{sep}" this_dict = jsonLoad(f"{filepath}{file}.json") - if this_dict["debug"]: - try: - this_dict = jsonLoad("config_debug.json") - file = "config_debug" - except FileNotFoundError: - print("Debug mode is set but config_debug.json is not there! Falling back to config.json", flush=True) string = "this_dict" for arg in args: string += f'["{arg}"]' @@ -79,11 +79,11 @@ def configGet(key: str, *args: str, file: str = "config"): except FileNotFoundError: print("Config file not found! Copy config_example.json to config.json, configure it and rerun the bot!", flush=True) exit() - if this_dict["debug"]: - try: - this_dict = jsonLoad("config_debug.json") - except FileNotFoundError: - print("Debug mode is set but config_debug.json is not there! Falling back to config.json", flush=True) + if this_dict["debug"]: + try: + this_dict = jsonLoad("config_debug.json") + except FileNotFoundError: + print("Debug mode is set but config_debug.json is not there! Falling back to config.json", flush=True) else: this_dict = jsonLoad(f"data{sep}users{sep}{file}.json") this_key = this_dict