From 506c7c06c99877db27d9b515c1fae7d75401d315 Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 21 Oct 2022 14:00:03 +0200 Subject: [PATCH] Improved everything --- config_example.json | 2 + data/applications.json | 1 + locale/uk.json | 22 +++++- main.py | 169 +++++++++++++++++++++++++++++++++++------ 4 files changed, 168 insertions(+), 26 deletions(-) create mode 100644 data/applications.json diff --git a/config_example.json b/config_example.json index 87d515a..0e0259c 100644 --- a/config_example.json +++ b/config_example.json @@ -1,6 +1,8 @@ { "locale": "uk", "owner": 0, + "age_allowed": 0, + "admin_group": 0, "admins": [], "bot": { "api_id": 0, diff --git a/data/applications.json b/data/applications.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/data/applications.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/locale/uk.json b/locale/uk.json index 6ae2011..3b0a579 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -23,15 +23,29 @@ "question10": "Ну і нарешті, розкажи трохи про себе. Про хобі, чим тобі подобається займатись. Одним повідомленням, будь ласка.", "question2_underage": "Вибач, але треба досягти віку {0} років, щоб приєднатись до нас. Такі обмеження існують для того, щоб всім у спільноті було цікаво одне з одним.", "question2_invalid": "Будь ласка, введи ціле число.", - "question2_joke": "Тижпрограміст, ми так і поняли. Але будь ласка, введи реальне значення.", + "question2_joke": "Шутнік, ми так і поняли. Але будь ласка, введи реальне значення.", "confirm": "Супер, дякуємо!\n\nБудь ласка, перевір правильність даних:\n{0}\n\nВсе правильно?", + "application_sent": "Дякуємо! Ми надіслали твою анкетку на перевірку. Ти отримаєш повідомлення як тільки її перевірять та приймуть рішення. До тих пір від тебе більше нічого не потребується. Гарного дня! :)", + "application_got": "Отримано анкету від `{0}`\n\nІм'я тг: `{1}`, `{2}`\nUserID: `{3}`\n\n**Дані анкети:**\n{4}", "shutdown": "Вимкнення бота з підом `{0}`", "startup": "Запуск бота з підом `{0}`", "startup_downtime": "Запуск бота з підом `{0}` (лежав {1})", "sub_yes": "✅ Подання схвалено та прийнято", - "sub_no": "❌ Подання розглянуто та відхилено" + "sub_no": "❌ Подання розглянуто та відхилено", + "question_titles": { + "question1": "Ім'я/звертання:", + "question2": "Вік:", + "question3": "Проживаня:", + "question4": "Дізнався(лась) про холо:", + "question5": "Хололайв зацікавив:", + "question6": "Подобається контент:", + "question7": "Японські холодівчата:", + "question8": "Дивлюсь стріми:", + "question9": "Подобаються пісні:", + "question10": "Про себе:" + } }, - "keyboards": { + "keyboard": { "welcome": [ [ "Так, звісно" @@ -69,6 +83,8 @@ "button": { "sub_yes": "✅ Прийняти", "sub_no": "❌ Відхилити", + "sub_no_aggresive": "🤡 Відхилити (Токс)", + "sub_no_russian": "🇷🇺 Відхилити (Русак)", "accepted": "✅ Прийнято", "declined": "❌ Відхилено" }, diff --git a/main.py b/main.py index 4af3ba0..4e3bad1 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,3 @@ -import asyncio from time import time from os import getpid, listdir, remove from modules.utils import * @@ -9,11 +8,13 @@ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, BotComman from pyrogram import idle # type: ignore from pyrogram.errors.exceptions import bad_request_400 -pid = getpid() +pid = getpid() app = Client("holochecker", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot")) -@app.on_message(~ filters.scheduled & filters.command(["start"], prefixes=["/"])) + +# Start command ================================================================================================================ +@app.on_message(~ filters.scheduled & filters.private & filters.command(["start"], prefixes=["/"])) async def cmd_start(app, msg): try: @@ -28,17 +29,23 @@ async def cmd_start(app, msg): configSet("telegram_phone", str(msg.from_user.phone_number), file=str(msg.from_user.id)) configSet("telegram_locale", str(msg.from_user.language_code), file=str(msg.from_user.id)) - await msg.reply_text(locale("start", "message"), reply_markup=ReplyKeyboardMarkup(locale("welcome", "keyboards"), resize_keyboard=True)) + await msg.reply_text(locale("start", "message"), reply_markup=ReplyKeyboardMarkup(locale("welcome", "keyboard"), resize_keyboard=True)) +# ============================================================================================================================== -@app.on_message(~ filters.scheduled & filters.command(["kill", "die", "reboot"], prefixes=["", "/"])) + +# Shutdown command ============================================================================================================= +@app.on_message(~ filters.scheduled & filters.private & filters.command(["kill", "die", "reboot"], prefixes=["", "/"])) async def cmd_kill(app, msg): if (msg.from_user.id == configGet("owner")) or (msg.from_user.id in configGet("admins")): logWrite(f"Shutting down bot with pid {pid}") await msg.reply_text(f"Вимкнення бота з підом `{pid}`") killProc(pid) +# ============================================================================================================================== -@app.on_message(~ filters.scheduled & (filters.regex(locale("welcome", "keyboards")[0][0]) | filters.regex(locale("return", "keyboards")[0][0]))) + +# Welcome check ================================================================================================================ +@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("welcome", "keyboard")[0][0]) | filters.regex(locale("return", "keyboard")[0][0]))) async def welcome_pass(app, msg, once_again: bool = True): if not once_again: @@ -47,23 +54,67 @@ async def welcome_pass(app, msg, once_again: bool = True): await msg.reply_text(locale("question1", "message"), reply_markup=ForceReply(placeholder=locale("question1", "force_reply"))) configSet("stage", 1, file=str(msg.from_user.id)) -@app.on_message(~ filters.scheduled & (filters.regex(locale("welcome", "keyboards")[1][0]))) +@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("welcome", "keyboard")[1][0]))) async def welcome_reject(app, msg): - await msg.reply_text(locale("goodbye", "message"), reply_markup=ReplyKeyboardMarkup(locale("return", "keyboards"), resize_keyboard=True)) + await msg.reply_text(locale("goodbye", "message"), reply_markup=ReplyKeyboardMarkup(locale("return", "keyboard"), resize_keyboard=True)) +# ============================================================================================================================== -@app.on_message(~ filters.scheduled & (filters.regex(locale("confirm", "keyboards")[0][0]))) + +# Confirmation ================================================================================================================= +@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[0][0]))) async def confirm_yes(app, msg): user_stage = configGet("stage", file=str(msg.from_user.id)) if user_stage == 10: - await msg.reply_text("Alright! You did it!", reply_markup=ReplyKeyboardRemove()) - # send to admins + + await msg.reply_text(locale("application_sent", "message"), reply_markup=ReplyKeyboardRemove()) + + applications = jsonLoad(f"data{sep}applications.json") + + applications[str(msg.from_user.id)] = { + "approved": False, + "approved_by": None, + "approval_date": None, + "refused": False, + "refused_by": False, + "refusal_date": False, + "application_date": int(time()), + "application": configGet("application", file=str(msg.from_user.id)) + } + + jsonSave(applications, f"data{sep}applications.json") + + 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 app.send_message(chat_id=configGet("admin_group"), text=(locale("application_got", "message")).format(str(msg.from_user.id), msg.from_user.first_name, msg.from_user.last_name, msg.from_user.username, "\n".join(application_content)), reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(text=locale("sub_yes", "button"), callback_data=f"sub_yes_{msg.from_user.id}") + ], + [ + InlineKeyboardButton(text=locale("sub_no", "button"), callback_data=f"sub_no_{msg.from_user.id}") + ], + [ + InlineKeyboardButton(text=locale("sub_no_aggresive", "button"), callback_data=f"sub_no_aggresive_{msg.from_user.id}") + ], + [ + InlineKeyboardButton(text=locale("sub_no_russian", "button"), callback_data=f"sub_no_russian_{msg.from_user.id}") + ] + ] + ) + ) + configSet("sent", True, file=str(msg.from_user.id)) configSet("application_date", int(time()), file=str(msg.from_user.id)) -@app.on_message(~ filters.scheduled & (filters.regex(locale("confirm", "keyboards")[1][0]))) +@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[1][0]))) async def confirm_no(app, msg): user_stage = configGet("stage", file=str(msg.from_user.id)) @@ -75,8 +126,69 @@ async def confirm_no(app, msg): configSet("telegram_phone", str(msg.from_user.phone_number), file=str(msg.from_user.id)) configSet("telegram_locale", str(msg.from_user.language_code), file=str(msg.from_user.id)) await welcome_pass(app, msg, once_again=True) +# ============================================================================================================================== -@app.on_message(~ filters.scheduled) + +# Callbacks ==================================================================================================================== +@app.on_callback_query(filters.regex("sub_yes_[\s\S]*")) +async def callback_query_accept(app, clb): + + fullclb = clb.data.split("_") + user_locale = clb.from_user.language_code + + await app.send_message(configGet("admin_group"), f"Approved by {clb.from_user.id}") + await app.send_message(int(fullclb[2]), "You got approved") + + edited_markup = [[InlineKeyboardButton(text=locale("accepted", "button"), callback_data="nothing")]] + + await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) + await clb.answer(text=locale("sub_block", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) + +@app.on_callback_query(filters.regex("sub_no_[\s\S]*")) +async def callback_query_refuse(app, clb): + + fullclb = clb.data.split("_") + user_locale = clb.from_user.language_code + + await app.send_message(configGet("admin_group"), f"Refused by {clb.from_user.id}") + await app.send_message(int(fullclb[2]), "You got refused") + + edited_markup = [[InlineKeyboardButton(text=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_block", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) + +@app.on_callback_query(filters.regex("sub_no_aggresive_[\s\S]*")) +async def callback_query_refuse(app, clb): + + fullclb = clb.data.split("_") + user_locale = clb.from_user.language_code + + await app.send_message(configGet("admin_group"), f"Refused by {clb.from_user.id}") + await app.send_message(int(fullclb[2]), "You got refused") + + edited_markup = [[InlineKeyboardButton(text=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_block", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) + +@app.on_callback_query(filters.regex("sub_no_russian_[\s\S]*")) +async def callback_query_refuse(app, clb): + + fullclb = clb.data.split("_") + user_locale = clb.from_user.language_code + + await app.send_message(configGet("admin_group"), f"Refused by {clb.from_user.id}") + await app.send_message(int(fullclb[2]), "You got refused") + + edited_markup = [[InlineKeyboardButton(text=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_block", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) +# ============================================================================================================================== + +# Any other input ============================================================================================================== +@app.on_message(~ filters.scheduled & filters.private) async def any_stage(app, msg): user_stage = configGet("stage", file=str(msg.from_user.id)) @@ -88,8 +200,13 @@ async def any_stage(app, msg): elif user_stage == 2: try: configSet(str(user_stage), int(msg.text), "application", file=str(msg.from_user.id)) - await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=locale(f"question{user_stage+1}", "force_reply"))) - configSet("stage", user_stage+1, file=str(msg.from_user.id)) + if (int(msg.text) in [-1, 0, 128, 256, 512, 1024, 2048]) or (int(msg.text) >= 100): + await msg.reply_text(locale("question2_joke", "message"), reply_markup=ForceReply(placeholder=locale("question2", "force_reply"))) + elif int(msg.text) < configGet("age_allowed"): + await msg.reply_text(locale("question2_underage", "message"), reply_markup=ForceReply(placeholder=locale("question2", "force_reply"))) + else: + await msg.reply_text(locale(f"question{user_stage+1}", "message"), reply_markup=ForceReply(placeholder=locale(f"question{user_stage+1}", "force_reply"))) + configSet("stage", user_stage+1, file=str(msg.from_user.id)) except ValueError: await msg.reply_text(locale(f"question2_invalid", "message"), reply_markup=ForceReply(placeholder=locale(f"question{user_stage}", "force_reply"))) else: @@ -100,7 +217,12 @@ async def any_stage(app, msg): else: if not configGet("sent", file=str(msg.from_user.id)): if not configGet("confirmed", file=str(msg.from_user.id)): - await msg.reply_text(locale("confirm", "message"), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboards"), resize_keyboard=True)) + 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)) configSet(str(user_stage), str(msg.text), "application", file=str(msg.from_user.id)) #configSet("sent", True, file=str(msg.from_user.id)) #configSet("application_date", int(time()), file=str(msg.from_user.id)) @@ -108,6 +230,7 @@ async def any_stage(app, msg): await msg.reply_text("You are already done, wait!") else: await msg.reply_text("You are already done, wait!") +# ============================================================================================================================== if __name__ == "__main__": @@ -120,16 +243,16 @@ if __name__ == "__main__": app.send_message(configGet("owner"), f"Starting up with pid `{pid}`") # type: ignore - # Registering user commands for fallback locale - commands_list = [] - for command in configGet("commands"): - commands_list.append(BotCommand(command, configGet("commands")[command])) - app.set_bot_commands(commands_list) # type: ignore + # # Registering user commands + # commands_list = [] + # for command in configGet("commands"): + # commands_list.append(BotCommand(command, configGet("commands")[command])) + # app.set_bot_commands(commands_list) # type: ignore # Registering admin commands commands_admin_list = [] - for command in configGet("commands"): - commands_admin_list.append(BotCommand(command, configGet("commands")[command])) + # for command in configGet("commands"): + # commands_admin_list.append(BotCommand(command, configGet("commands")[command])) for command in configGet("commands_admin"): commands_admin_list.append(BotCommand(command, configGet("commands_admin")[command]))