From a769ea9ef5a80f3be6e2ba8530a132b4a50d93fa Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Sat, 17 Dec 2022 00:58:33 +0100 Subject: [PATCH] Added language_code context --- classes/holo_user.py | 34 +++++++++---------- modules/callbacks/nothing.py | 2 +- modules/callbacks/reapply.py | 27 ++++++++------- modules/callbacks/rules.py | 26 +++++++------- modules/callbacks/sub.py | 26 +++++++------- modules/callbacks/sus.py | 4 +-- modules/commands/application.py | 18 +++++----- modules/commands/message.py | 4 +-- modules/commands/reapply.py | 16 ++++----- modules/commands/reboot.py | 4 +-- modules/commands/rules.py | 58 ++++++++++++++++++-------------- modules/commands/start.py | 2 +- modules/commands/warnings.py | 11 +++--- modules/commands_register.py | 35 +++++++++++++------ modules/handlers/confirmation.py | 12 +++++-- modules/handlers/contact.py | 16 ++++----- modules/handlers/welcome.py | 18 +++++++--- modules/inline.py | 36 ++++++++++---------- modules/utils.py | 42 ++++++++++++++++++++--- 19 files changed, 230 insertions(+), 161 deletions(-) diff --git a/classes/holo_user.py b/classes/holo_user.py index 3de2b1b..474d1ec 100644 --- a/classes/holo_user.py +++ b/classes/holo_user.py @@ -100,13 +100,13 @@ class HoloUser(): self.locale = holo_user["tg_locale"] self.username = holo_user["tg_username"] - if isinstance(user, User) and (self.name != user.first_name): + if isinstance(user, User) and ((self.name != user.first_name) and (user.first_name is None)): self.set("tg_name", user.first_name) if isinstance(user, User) and (self.phone != user.phone_number): self.set("tg_phone", user.phone_number) - if isinstance(user, User) and ((self.locale != user.language_code) and (user.language_code != None)): + if isinstance(user, User) and ((self.locale != user.language_code) and (user.language_code is not None)): self.set("tg_locale", user.language_code) if isinstance(user, User) and (self.username != user.username): @@ -328,39 +328,39 @@ class HoloUser(): input_dt = datetime.strptime(query, "%d.%m.%Y") except ValueError: logWrite(f"User {msg.from_user.id} failed stage {stage} due to sending invalid date format") - await msg.reply_text(locale(f"question2_invalid", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{stage}", "force_reply")))) + 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: logWrite(f"User {msg.from_user.id} failed stage {stage} due to joking") - await msg.reply_text(locale("question2_joke", "message"), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply")))) + await msg.reply_text(locale("question2_joke", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply", locale=self.locale)))) return 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 {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")))) + await msg.reply_text(locale("question2_underage", "message", locale=self.locale).format(str(configGet("age_allowed"))), reply_markup=ForceReply(placeholder=str(locale("question2", "force_reply", locale=self.locale)))) return else: print(f'Look: {((datetime.now() - input_dt).days)} > {(datetime.now() - datetime.now().replace(year=datetime.now().year - configGet("age_allowed"))).days}') progress["application"][str(stage)] = input_dt col_tmp.update_one({"user": {"$eq": self.id}, "type": {"$eq": "application"}}, {"$set": {"application": progress["application"], "stage": progress["stage"]+1}}) - await msg.reply_text(locale(f"question{stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{stage+1}", "force_reply")))) + await msg.reply_text(locale(f"question{stage+1}", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"question{stage+1}", "force_reply", locale=self.locale)))) elif stage == 3: try: result = (get(f"http://api.geonames.org/searchJSON?q={query}&maxRows=1&countryBias=UA&lang=uk&orderby=relevance&featureClass=P&featureClass=A&username={configGet('username', 'geocoding')}")).json() progress["application"][str(stage)] = result["geonames"][0] col_tmp.update_one({"user": {"$eq": self.id}, "type": {"$eq": "application"}}, {"$set": {"application": progress["application"], "stage": progress["stage"]+1}}) - await msg.reply_text(locale(f"question3_found", "message").format(result["geonames"][0]["name"], result["geonames"][0]["adminName1"])) - await msg.reply_text(locale(f"question{stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{stage+1}", "force_reply")))) + await msg.reply_text(locale(f"question3_found", "message", locale=self.locale).format(result["geonames"][0]["name"], result["geonames"][0]["adminName1"])) + await msg.reply_text(locale(f"question{stage+1}", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"question{stage+1}", "force_reply", locale=self.locale)))) except (ValueError, KeyError, IndexError): - await msg.reply_text(locale(f"question3_invalid", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{stage}", "force_reply")))) + await msg.reply_text(locale(f"question3_invalid", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"question{stage}", "force_reply", locale=self.locale)))) return except Exception as exp: - await msg.reply_text(locale("question3_error", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{stage}", "force_reply")))) + await msg.reply_text(locale("question3_error", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"question{stage}", "force_reply", locale=self.locale)))) try: - await app.send_message(configGet("owner"), locale("question3_traceback", "message").format(query, exp, print_exc())) + await app.send_message(configGet("owner"), locale("question3_traceback", "message", locale=self.locale).format(query, exp, print_exc())) except bad_request_400.PeerIdInvalid: logWrite(f"Could not notify admin about failure when sending message! Admin has never interacted with bot!") return @@ -373,20 +373,20 @@ class HoloUser(): for question in progress["application"]: if i == 2: age = relativedelta(datetime.now(), progress['application']['2']) - application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {progress['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles', locale=self.locale)} {progress['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") elif i == 3: if progress['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {progress['application']['3']['name']} ({progress['application']['3']['adminName1']})") + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles', locale=self.locale)} {progress['application']['3']['name']} ({progress['application']['3']['adminName1']})") else: - application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {progress['application']['3']['name']} ({progress['application']['3']['adminName1']}, {progress['application']['3']['countryName']})") + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles', locale=self.locale)} {progress['application']['3']['name']} ({progress['application']['3']['adminName1']}, {progress['application']['3']['countryName']})") else: - application_content.append(f"{locale('question'+str(i), 'message', 'question_titles')} {progress['application'][question]}") + application_content.append(f"{locale('question'+str(i), 'message', 'question_titles', locale=self.locale)} {progress['application'][question]}") i += 1 - await msg.reply_text(locale("confirm", "message").format("\n".join(application_content)), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard"), resize_keyboard=True)) + await msg.reply_text(locale("confirm", "message", locale=self.locale).format("\n".join(application_content)), reply_markup=ReplyKeyboardMarkup(locale("confirm", "keyboard", locale=self.locale), resize_keyboard=True)) else: progress["application"][str(stage)] = query col_tmp.update_one({"user": {"$eq": self.id}, "type": {"$eq": "application"}}, {"$set": {"application": progress["application"], "stage": progress["stage"]+1}}) - await msg.reply_text(locale(f"question{stage+1}", "message"), reply_markup=ForceReply(placeholder=str(locale(f"question{stage+1}", "force_reply")))) + await msg.reply_text(locale(f"question{stage+1}", "message", locale=self.locale), reply_markup=ForceReply(placeholder=str(locale(f"question{stage+1}", "force_reply", locale=self.locale)))) logWrite(f"User {self.id} completed stage {stage} of application") \ No newline at end of file diff --git a/modules/callbacks/nothing.py b/modules/callbacks/nothing.py index f33eed0..8f4a719 100644 --- a/modules/callbacks/nothing.py +++ b/modules/callbacks/nothing.py @@ -5,5 +5,5 @@ from modules.utils import locale # Callback empty =============================================================================================================== @app.on_callback_query(filters.regex("nothing")) async def callback_query_nothing(app, clb): - await clb.answer(text=locale("nothing", "callback")) + await clb.answer(text=locale("nothing", "callback", locale=clb.from_user)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/callbacks/reapply.py b/modules/callbacks/reapply.py index 74c2fe8..635a1c0 100644 --- a/modules/callbacks/reapply.py +++ b/modules/callbacks/reapply.py @@ -18,7 +18,7 @@ async def callback_reapply_query_accept(app, clb): await app.send_message(configGet("admin_group"), locale("approved_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) logWrite(f"User {holo_user.id} got their reapplication approved by {clb.from_user.id}") - await app.send_message(holo_user.id, locale("approved_joined", "message")) + await app.send_message(holo_user.id, locale("approved_joined", "message", locale=holo_user)) col_applications.delete_one({"user": {"$eq": holo_user.id}}) col_applications.insert_one({"user": holo_user.id, "date": datetime.now(), "admin": clb.from_user.id, "application": col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}})["application"]}) @@ -27,7 +27,7 @@ async def callback_reapply_query_accept(app, clb): edited_markup = [[InlineKeyboardButton(text=str(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_accepted", "callback").format(holo_user.id), show_alert=True) + await clb.answer(text=locale("sub_accepted", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) need_link = True @@ -38,14 +38,14 @@ async def callback_reapply_query_accept(app, clb): if need_link: link = await app.create_chat_invite_link(configGet("destination_group"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) - await app.send_message(holo_user.id, locale("read_rules", "message")) + await app.send_message(holo_user.id, locale("read_rules", "message", locale=holo_user)) - for rule_msg in locale("rules"): + for rule_msg in locale("rules", locale=holo_user): await app.send_message(holo_user.id, rule_msg) await app.send_message(holo_user.id, locale("approved", "message"), reply_markup=InlineKeyboardMarkup( [[ - InlineKeyboardButton(str(locale("join", "button")), url=link.invite_link) + InlineKeyboardButton(str(locale("join", "button", locale=holo_user)), url=link.invite_link) ]] )) @@ -53,7 +53,7 @@ async def callback_reapply_query_accept(app, clb): logWrite(f"User {holo_user.id} got an invite link {link.invite_link}") else: - await app.send_message(holo_user.id, locale("approved_joined", "message")) + await app.send_message(holo_user.id, locale("approved_joined", "message", locale=holo_user)) @app.on_callback_query(filters.regex("reapply_no_[\s\S]*")) async def callback_query_reapply_reject(app, clb): @@ -62,7 +62,7 @@ async def callback_query_reapply_reject(app, clb): holo_user = HoloUser(int(fullclb[2])) await app.send_message(configGet("admin_group"), locale("rejected_by", "message").format(clb.from_user.first_name, fullclb[2]), disable_notification=True) - await app.send_message(holo_user.id, locale("rejected", "message")) + await app.send_message(holo_user.id, locale("rejected", "message", locale=holo_user)) logWrite(f"User {fullclb[2]} got their reapplication rejected by {clb.from_user.id}") col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) @@ -70,7 +70,7 @@ async def callback_query_reapply_reject(app, clb): 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_rejected", "callback").format(fullclb[2]), show_alert=True) + await clb.answer(text=locale("sub_rejected", "callback", locale=clb.from_user).format(fullclb[2]), show_alert=True) # Use old application when user reapplies after leaving the chat @app.on_callback_query(filters.regex("reapply_old_[\s\S]*")) @@ -78,7 +78,7 @@ async def callback_query_reapply_old(app, clb): fullclb = clb.data.split("_") message = await app.get_messages(clb.from_user.id, int(fullclb[2])) await confirm_yes(app, message) - await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button"), "nothing")]])) + await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button", locale=clb.from_user), "nothing")]])) # Start a new application when user reapplies after leaving the chat @app.on_callback_query(filters.regex("reapply_new_[\s\S]*")) @@ -86,11 +86,12 @@ async def callback_query_reapply_new(app, clb): fullclb = clb.data.split("_") - await clb.answer(locale("reapply_stopped", "callback")) + await clb.answer(locale("reapply_stopped", "callback", locale=clb.from_user)) message = await app.get_messages(clb.from_user.id, int(fullclb[2])) + col_tmp.update_one({"user": clb.from_user.id}, {"$set": {"state": "fill", "completed": False, "stage": 1}}) await welcome_pass(app, message, once_again=True) logWrite(f"User {clb.from_user.id} restarted the application after leaving the chat earlier") - await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button"), "nothing")]])) + await clb.message.edit(clb.message.text, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(locale("done", "button", locale=clb.from_user), "nothing")]])) # Abort application fill in progress and restart it @app.on_callback_query(filters.regex("reapply_stop_[\s\S]*")) @@ -100,9 +101,9 @@ async def callback_query_reapply_stop(app, clb): holo_user = HoloUser(clb.from_user) holo_user.application_restart() - await clb.answer(locale("reapply_stopped", "callback")) + await clb.answer(locale("reapply_stopped", "callback", locale=holo_user)) message = await app.get_messages(clb.from_user.id, int(fullclb[2])) await welcome_pass(app, message, once_again=True) logWrite(f"User {clb.from_user.id} restarted the application due to typo in it") - await clb.message.edit(locale("reapply_restarted", "message"), reply_markup=ReplyKeyboardRemove()) + await clb.message.edit(locale("reapply_restarted", "message", locale=holo_user), reply_markup=ReplyKeyboardRemove()) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/callbacks/rules.py b/modules/callbacks/rules.py index ca91296..0a5a0ba 100644 --- a/modules/callbacks/rules.py +++ b/modules/callbacks/rules.py @@ -3,7 +3,7 @@ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.errors import bad_request_400 from pyrogram import filters from modules.utils import locale, logWrite -from modules.commands.rules import default_rules_markup +from modules.commands.rules import DefaultRulesMarkup # Callback rule ================================================================================================================ @app.on_callback_query(filters.regex("rule_[\s\S]*")) @@ -17,24 +17,24 @@ async def callback_query_rule(app, clb): if rule_num == len(locale("rules")): lower_buttons = [ - InlineKeyboardButton(locale("rules_prev", "button"), callback_data=f"rule_{rule_num-1}") + InlineKeyboardButton(locale("rules_prev", "button", locale=clb.from_user), callback_data=f"rule_{rule_num-1}") ] elif rule_num == 1: lower_buttons = [ - InlineKeyboardButton(locale("rules_next", "button"), callback_data=f"rule_{rule_num+1}") + InlineKeyboardButton(locale("rules_next", "button", locale=clb.from_user), callback_data=f"rule_{rule_num+1}") ] else: lower_buttons = [ - InlineKeyboardButton(locale("rules_prev", "button"), callback_data=f"rule_{rule_num-1}"), - InlineKeyboardButton(locale("rules_next", "button"), callback_data=f"rule_{rule_num+1}") + InlineKeyboardButton(locale("rules_prev", "button", locale=clb.from_user), callback_data=f"rule_{rule_num-1}"), + InlineKeyboardButton(locale("rules_next", "button", locale=clb.from_user), callback_data=f"rule_{rule_num+1}") ] try: - await clb.message.edit(text=locale("rules")[rule_num-1], disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( + await clb.message.edit(text=locale("rules", locale=clb.from_user)[rule_num-1], disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [ [ - InlineKeyboardButton(locale("rules_home", "button"), callback_data="rules_home"), - InlineKeyboardButton(locale("rules_additional", "button"), callback_data="rules_additional") + InlineKeyboardButton(locale("rules_home", "button", locale=clb.from_user), callback_data="rules_home"), + InlineKeyboardButton(locale("rules_additional", "button", locale=clb.from_user), callback_data="rules_additional") ], lower_buttons ] @@ -43,7 +43,7 @@ async def callback_query_rule(app, clb): except bad_request_400.MessageNotModified: pass - await clb.answer(text=locale("rules_page", "callback").format(fullclb[1])) + await clb.answer(text=locale("rules_page", "callback", locale=clb.from_user).format(fullclb[1])) @app.on_callback_query(filters.regex("rules_home")) async def callback_query_rules_home(app, clb): @@ -51,11 +51,11 @@ async def callback_query_rules_home(app, clb): logWrite(f"User {clb.from_user.id} requested to check out homepage rules") try: - await clb.message.edit(text=locale("rules_msg"), disable_web_page_preview=True, reply_markup=default_rules_markup) + await clb.message.edit(text=locale("rules_msg", locale=clb.from_user), disable_web_page_preview=True, reply_markup=DefaultRulesMarkup(clb.from_user).keyboard) except bad_request_400.MessageNotModified: pass - await clb.answer(text=locale("rules_home", "callback")) + await clb.answer(text=locale("rules_home", "callback", locale=clb.from_user)) @app.on_callback_query(filters.regex("rules_additional")) async def callback_query_rules_additional(app, clb): @@ -63,9 +63,9 @@ async def callback_query_rules_additional(app, clb): logWrite(f"User {clb.from_user.id} requested to check out additional rules") try: - await clb.message.edit(text=locale("rules_additional"), disable_web_page_preview=True, reply_markup=default_rules_markup) + await clb.message.edit(text=locale("rules_additional", locale=clb.from_user), disable_web_page_preview=True, reply_markup=DefaultRulesMarkup(clb.from_user).keyboard) except bad_request_400.MessageNotModified: pass - await clb.answer(text=locale("rules_additional", "callback")) + await clb.answer(text=locale("rules_additional", "callback", locale=clb.from_user)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/callbacks/sub.py b/modules/callbacks/sub.py index de9163a..5eebb09 100644 --- a/modules/callbacks/sub.py +++ b/modules/callbacks/sub.py @@ -5,7 +5,7 @@ from pyrogram import filters from classes.holo_user import HoloUser from modules.utils import configGet, locale, logWrite from modules.database import col_tmp, col_applications -from modules.commands.rules import default_rules_markup +from modules.commands.rules import DefaultRulesMarkup # Callbacks application ======================================================================================================== @app.on_callback_query(filters.regex("sub_yes_[\s\S]*")) @@ -26,13 +26,13 @@ async def callback_query_accept(app, clb): if need_link: link = await app.create_chat_invite_link(configGet("destination_group"), name=f"Invite for {holo_user.id}", member_limit=1) #, expire_date=datetime.now()+timedelta(days=1)) - await app.send_message(holo_user.id, locale("read_rules", "message")) + await app.send_message(holo_user.id, locale("read_rules", "message", locale=holo_user)) - await app.send_message(holo_user.id, locale("rules_msg"), disable_web_page_preview=True, reply_markup=default_rules_markup) + await app.send_message(holo_user.id, locale("rules_msg", locale=holo_user), disable_web_page_preview=True, reply_markup=DefaultRulesMarkup(holo_user).keyboard) - await app.send_message(holo_user.id, locale("approved", "message"), reply_markup=InlineKeyboardMarkup( + await app.send_message(holo_user.id, locale("approved", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup( [[ - InlineKeyboardButton(str(locale("join", "button")), url=link.invite_link) + InlineKeyboardButton(str(locale("join", "button", locale=holo_user)), url=link.invite_link) ]] )) @@ -40,7 +40,7 @@ async def callback_query_accept(app, clb): logWrite(f"User {holo_user.id} got an invite link {link.invite_link}") else: - await app.send_message(holo_user.id, locale("approved_joined", "message")) + await app.send_message(holo_user.id, locale("approved_joined", "message", locale=holo_user)) col_applications.insert_one({"user": holo_user.id, "date": datetime.now(), "admin": clb.from_user.id, "application": col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}})["application"]}) col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "approved", "sent": False}}) @@ -48,7 +48,7 @@ async def callback_query_accept(app, clb): edited_markup = [[InlineKeyboardButton(text=str(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_accepted", "callback").format(holo_user.id), show_alert=True) + await clb.answer(text=locale("sub_accepted", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) @app.on_callback_query(filters.regex("sub_no_[\s\S]*")) async def callback_query_reject(app, clb): @@ -57,7 +57,7 @@ async def callback_query_reject(app, clb): holo_user = HoloUser(int(fullclb[2])) await app.send_message(configGet("admin_group"), locale("rejected_by", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) - await app.send_message(holo_user.id, locale("rejected", "message")) + await app.send_message(holo_user.id, locale("rejected", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id}") col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) @@ -65,7 +65,7 @@ async def callback_query_reject(app, clb): 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_rejected", "callback").format(holo_user.id), show_alert=True) + 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, clb): @@ -74,7 +74,7 @@ async def callback_query_reject_aggressive(app, clb): holo_user = HoloUser(int(fullclb[2])) await app.send_message(configGet("admin_group"), locale("rejected_by_agr", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) - await app.send_message(holo_user.id, locale("rejected_aggressive", "message")) + 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}}) @@ -82,7 +82,7 @@ async def callback_query_reject_aggressive(app, clb): 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").format(holo_user.id), show_alert=True) + 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, clb): @@ -91,7 +91,7 @@ async def callback_query_reject_russian(app, clb): holo_user = HoloUser(int(fullclb[2])) await app.send_message(configGet("admin_group"), locale("rejected_by_rus", "message").format(clb.from_user.first_name, holo_user.id), disable_notification=True) - await app.send_message(holo_user.id, locale("rejected_russian", "message")) + await app.send_message(holo_user.id, locale("rejected_russian", "message", locale=holo_user)) logWrite(f"User {holo_user.id} got rejected by {clb.from_user.id} due to being russian") col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "rejected", "sent": False}}) @@ -99,5 +99,5 @@ async def callback_query_reject_russian(app, clb): 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_russian", "callback").format(holo_user.id), show_alert=True) + await clb.answer(text=locale("sub_russian", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/callbacks/sus.py b/modules/callbacks/sus.py index 2f49542..50c6d52 100644 --- a/modules/callbacks/sus.py +++ b/modules/callbacks/sus.py @@ -18,7 +18,7 @@ async def callback_query_sus_allow(app, clb): edited_markup = [[InlineKeyboardButton(text=str(locale("sus_allowed", "button")), callback_data="nothing")]] await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) - await clb.answer(text=locale("sus_allowed", "callback").format(holo_user.id), show_alert=True) + await clb.answer(text=locale("sus_allowed", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) await app.restrict_chat_member(configGet("destination_group"), holo_user.id, permissions=ChatPermissions( can_send_messages=True, @@ -40,7 +40,7 @@ async def callback_query_sus_reject(app, clb): edited_markup = [[InlineKeyboardButton(text=str(locale("sus_rejected", "button")), callback_data="nothing")]] await clb.message.edit(text=clb.message.text, reply_markup=InlineKeyboardMarkup(edited_markup)) - await clb.answer(text=locale("sus_rejected", "callback").format(holo_user.id), show_alert=True) + await clb.answer(text=locale("sus_rejected", "callback", locale=clb.from_user).format(holo_user.id), show_alert=True) await app.ban_chat_member(configGet("destination_group"), holo_user.id) diff --git a/modules/commands/application.py b/modules/commands/application.py index ad3d24f..62d1e28 100644 --- a/modules/commands/application.py +++ b/modules/commands/application.py @@ -22,14 +22,14 @@ async def cmd_application(app, msg): try: holo_user = HoloUser((await app.get_users(msg.command[1])).id) except (bad_request_400.UsernameInvalid, bad_request_400.PeerIdInvalid): - await msg.reply_text(locale("no_user_application", "message").format(msg.command[1]), quote=should_quote(msg)) + await msg.reply_text(locale("no_user_application", "message", locale=msg.from_user).format(msg.command[1]), quote=should_quote(msg)) return application = col_applications.find_one({"user": holo_user.id}) if application is None: logWrite(f"User {msg.from_user.id} requested application of {holo_user.id} but user does not exists") - await msg.reply_text(locale("user_invalid", "message"), quote=should_quote(msg)) + await msg.reply_text(locale("user_invalid", "message", locale=msg.from_user), quote=should_quote(msg)) return application_content = [] @@ -39,21 +39,21 @@ async def cmd_application(app, msg): 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} р.)") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") elif i == 3: if application['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']}") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=msg.from_user)} {application['application'][question]}") i += 1 - application_status = locale("application_status_accepted", "message").format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) + application_status = locale("application_status_accepted", "message", locale=msg.from_user).format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) logWrite(f"User {msg.from_user.id} requested application of {holo_user.id}") - await msg.reply_text(locale("contact", "message").format(holo_user.id, "\n".join(application_content), application_status), parse_mode=ParseMode.MARKDOWN, quote=should_quote(msg)) + await msg.reply_text(locale("contact", "message", locale=msg.from_user).format(holo_user.id, "\n".join(application_content), application_status), parse_mode=ParseMode.MARKDOWN, quote=should_quote(msg)) # if (path.exists(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json") and jsonLoad(f"{configGet('data', 'locations')}{sep}users{sep}{msg.command[1]}.json")["approved"]): # user_id = int(msg.command[1]) @@ -92,5 +92,5 @@ async def cmd_application(app, msg): # await msg.reply_text(locale("contact", "message").format(str(user_id), "\n".join(application_content), application_status), quote=should_quote(msg)) except IndexError: - await msg.reply_text(locale("application_invalid_syntax", "message"), quote=should_quote(msg)) + await msg.reply_text(locale("application_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/message.py b/modules/commands/message.py index fa6dd8a..74ceeb4 100644 --- a/modules/commands/message.py +++ b/modules/commands/message.py @@ -24,9 +24,9 @@ async def cmd_message(app, msg): await destination.message(context=msg, text=None, caption=None, photo=msg.photo, video=msg.video, file=msg.document, adm_context=True) except IndexError: - await msg.reply_text(locale("message_invalid_syntax", "message"), quote=should_quote(msg)) + await msg.reply_text(locale("message_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) logWrite(f"Admin {msg.from_user.id} tried to send message but 'IndexError'") except ValueError: - await msg.reply_text(locale("message_invalid_syntax", "message"), quote=should_quote(msg)) + await msg.reply_text(locale("message_invalid_syntax", "message", locale=msg.from_user), quote=should_quote(msg)) logWrite(f"Admin {msg.from_user.id} tried to send message but 'ValueError'") # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/reapply.py b/modules/commands/reapply.py index bb81eca..0936bf8 100644 --- a/modules/commands/reapply.py +++ b/modules/commands/reapply.py @@ -22,27 +22,27 @@ async def cmd_reapply(app, msg): holo_user.application_restart() await welcome_pass(app, msg, once_again=True) else: - await msg.reply_text(locale("reapply_left_chat", "message"), reply_markup=InlineKeyboardMarkup([ + await msg.reply_text(locale("reapply_left_chat", "message", locale=holo_user), reply_markup=InlineKeyboardMarkup([ [ - InlineKeyboardButton(locale("reapply_old_one", "button"), f"reapply_old_{msg.id}") + InlineKeyboardButton(locale("reapply_old_one", "button", locale=holo_user), f"reapply_old_{msg.id}") ], [ - InlineKeyboardButton(locale("reapply_new_one", "button"), f"reapply_new_{msg.id}") + InlineKeyboardButton(locale("reapply_new_one", "button", locale=holo_user), f"reapply_new_{msg.id}") ] ])) else: - await msg.reply_text(locale("reapply_in_progress", "message").format(locale("confirm", "keyboard")[1][0]), reply_markup=InlineKeyboardMarkup([ + await msg.reply_text(locale("reapply_in_progress", "message", locale=holo_user).format(locale("confirm", "keyboard", locale=holo_user)[1][0]), reply_markup=InlineKeyboardMarkup([ [ - InlineKeyboardButton(locale("applying_stop", "button"), f"reapply_stop_{msg.id}") + InlineKeyboardButton(locale("applying_stop", "button", locale=holo_user), f"reapply_stop_{msg.id}") ] ])) else: if (holo_user.application_state()[0] == "fill") and (col_tmp.find_one({"user": holo_user.id, "type": "application"})["sent"] is True): - await msg.reply_text(locale("reapply_forbidden", "message")) + await msg.reply_text(locale("reapply_forbidden", "message", locale=holo_user)) else: - await msg.reply_text(locale("reapply_in_progress", "message").format(locale("confirm", "keyboard")[1][0]), reply_markup=InlineKeyboardMarkup([ + await msg.reply_text(locale("reapply_in_progress", "message", locale=holo_user).format(locale("confirm", "keyboard", locale=holo_user)[1][0]), reply_markup=InlineKeyboardMarkup([ [ - InlineKeyboardButton(locale("applying_stop", "button"), f"reapply_stop_{msg.id}") + InlineKeyboardButton(locale("applying_stop", "button", locale=holo_user), f"reapply_stop_{msg.id}") ] ])) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/reboot.py b/modules/commands/reboot.py index 6945079..876d163 100644 --- a/modules/commands/reboot.py +++ b/modules/commands/reboot.py @@ -2,7 +2,7 @@ from app import app, isAnAdmin from os import getpid from sys import exit from pyrogram import filters -from modules.utils import logWrite, should_quote +from modules.utils import locale, logWrite, should_quote from modules.scheduled import scheduler pid = getpid() @@ -13,7 +13,7 @@ async def cmd_kill(app, msg): if await isAnAdmin(msg.from_user.id) is True: logWrite(f"Shutting down bot with pid {pid}") - await msg.reply_text(f"Вимкнення бота з підом `{pid}`", quote=should_quote(msg)) + await msg.reply_text(locale("shutdown", "message", locale=msg.from_user).format(pid), quote=should_quote(msg)) scheduler.shutdown() exit() # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/rules.py b/modules/commands/rules.py index f4cfe37..b75102f 100644 --- a/modules/commands/rules.py +++ b/modules/commands/rules.py @@ -1,34 +1,40 @@ +from typing import Union from app import app from pyrogram import filters -from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, User from modules.utils import locale +from classes.holo_user import HoloUser + +class DefaultRulesMarkup(list): + def __init__(self, language_code: Union[str, HoloUser, User, None]): + super().__init__([]) + self.keyboard = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton(locale("rules_home", "button", locale=language_code), callback_data="rules_home"), + InlineKeyboardButton(locale("rules_additional", "button", locale=language_code), callback_data="rules_additional") + ], + [ + InlineKeyboardButton("1", callback_data="rule_1"), + InlineKeyboardButton("2", callback_data="rule_2"), + InlineKeyboardButton("3", callback_data="rule_3") + ], + [ + InlineKeyboardButton("4", callback_data="rule_4"), + InlineKeyboardButton("5", callback_data="rule_5"), + InlineKeyboardButton("6", callback_data="rule_6") + ], + [ + InlineKeyboardButton("7", callback_data="rule_7"), + InlineKeyboardButton("8", callback_data="rule_8"), + InlineKeyboardButton("9", callback_data="rule_9") + ] + ] + ) + # Rules command ============================================================================================================= -default_rules_markup = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton(locale("rules_home", "button"), callback_data="rules_home"), - InlineKeyboardButton(locale("rules_additional", "button"), callback_data="rules_additional") - ], - [ - InlineKeyboardButton("1", callback_data="rule_1"), - InlineKeyboardButton("2", callback_data="rule_2"), - InlineKeyboardButton("3", callback_data="rule_3") - ], - [ - InlineKeyboardButton("4", callback_data="rule_4"), - InlineKeyboardButton("5", callback_data="rule_5"), - InlineKeyboardButton("6", callback_data="rule_6") - ], - [ - InlineKeyboardButton("7", callback_data="rule_7"), - InlineKeyboardButton("8", callback_data="rule_8"), - InlineKeyboardButton("9", callback_data="rule_9") - ] - ] -) - @app.on_message(~ filters.scheduled & filters.private & filters.command(["rules"], prefixes=["/"])) async def cmd_rules(app, msg): - await msg.reply_text(locale("rules_msg"), disable_web_page_preview=True, reply_markup=default_rules_markup) + 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/start.py b/modules/commands/start.py index e4260ba..6c89afe 100644 --- a/modules/commands/start.py +++ b/modules/commands/start.py @@ -23,5 +23,5 @@ async def cmd_start(app, msg): }) logWrite(f"User {msg.from_user.id} started bot interaction") - await msg.reply_text(locale("start", "message"), reply_markup=ReplyKeyboardMarkup(locale("welcome", "keyboard"), resize_keyboard=True)) + await msg.reply_text(locale("start", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("welcome", "keyboard", locale=msg.from_user), resize_keyboard=True)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands/warnings.py b/modules/commands/warnings.py index 843817e..fe43186 100644 --- a/modules/commands/warnings.py +++ b/modules/commands/warnings.py @@ -11,7 +11,8 @@ async def cmd_warnings(app, msg): if await isAnAdmin(msg.from_user.id) is True: if len(msg.command) <= 1: - await msg.reply_text(locale("syntax_warnings", "message"), quote=should_quote(msg)) + await msg.reply_text(locale("syntax_warnings", "message", locale=msg.from_user), quote=should_quote(msg)) + return try: user_db = col_users.find_one({"user": int(msg.command[1])}) @@ -27,16 +28,16 @@ async def cmd_warnings(app, msg): target_name = target.first_name target_id = str(target.id) else: - await msg.reply_text(locale("no_user_warnings", "message").format(msg.command[1])) + await msg.reply_text(locale("no_user_warnings", "message", locale=msg.from_user).format(msg.command[1])) return warns = len(list(col_warnings.find({"user": target_id}))) if warns == 0: - await msg.reply_text(locale("no_warnings", "message").format(target_name, target_id), quote=should_quote(msg)) + await msg.reply_text(locale("no_warnings", "message", locale=msg.from_user).format(target_name, target_id), quote=should_quote(msg)) else: if warns <= 5: - await msg.reply_text(locale("warnings_1", "message").format(target_name, target_id, warns), quote=should_quote(msg)) + await msg.reply_text(locale("warnings_1", "message", locale=msg.from_user).format(target_name, target_id, warns), quote=should_quote(msg)) else: - await msg.reply_text(locale("warnings_2", "message").format(target_name, target_id, warns), quote=should_quote(msg)) + await msg.reply_text(locale("warnings_2", "message", locale=msg.from_user).format(target_name, target_id, warns), quote=should_quote(msg)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/commands_register.py b/modules/commands_register.py index 20a1419..84f6c34 100644 --- a/modules/commands_register.py +++ b/modules/commands_register.py @@ -1,23 +1,36 @@ +from os import listdir from modules.logging import logWrite -from modules.utils import configGet +from modules.utils import configGet, locale from pyrogram.types import BotCommand, BotCommandScopeChat from pyrogram.errors import bad_request_400 def commands_register(app): + valid_locales = [] + files_locales = listdir(f'{configGet("locale", "locations")}') + for entry in files_locales: + valid_locales.append(".".join(entry.split(".")[:-1])) + # Registering user commands commands_list = [] - for command in configGet("commands"): - commands_list.append(BotCommand(command, configGet("commands")[command])) + for command in locale("commands"): + commands_list.append(BotCommand(command, locale("commands")[command])) app.set_bot_commands(commands_list) + # Registering user commands for each locale + for lc in valid_locales: + commands_list = [] + for command in locale("commands", locale=lc): + commands_list.append(BotCommand(command, locale("commands",locale=lc)[command])) + app.set_bot_commands(commands_list, language_code=lc) + # Registering admin commands commands_admin_list = [] - for command in configGet("commands"): - commands_admin_list.append(BotCommand(command, configGet("commands")[command])) + for command in locale("commands"): + commands_admin_list.append(BotCommand(command, locale("commands")[command])) - for command in configGet("commands_admin"): - commands_admin_list.append(BotCommand(command, configGet("commands_admin")[command])) + for command in locale("commands_admin"): + commands_admin_list.append(BotCommand(command, locale("commands_admin")[command])) for admin in configGet("admins"): try: @@ -32,8 +45,8 @@ def commands_register(app): # Registering admin group commands commands_group_admin_list = [] - for command in configGet("commands_group_admin"): - commands_group_admin_list.append(BotCommand(command, configGet("commands_group_admin")[command])) + for command in locale("commands_group_admin"): + commands_group_admin_list.append(BotCommand(command, locale("commands_group_admin")[command])) try: app.set_bot_commands(commands_group_admin_list, scope=BotCommandScopeChat(chat_id=configGet("admin_group"))) except bad_request_400.ChannelInvalid: @@ -41,8 +54,8 @@ def commands_register(app): # Registering destination group commands commands_group_destination_list = [] - for command in configGet("commands_group_destination"): - commands_group_destination_list.append(BotCommand(command, configGet("commands_group_destination")[command])) + for command in locale("commands_group_destination"): + commands_group_destination_list.append(BotCommand(command, locale("commands_group_destination")[command])) try: app.set_bot_commands(commands_group_destination_list, scope=BotCommandScopeChat(chat_id=configGet("destination_group"))) except bad_request_400.ChannelInvalid: diff --git a/modules/handlers/confirmation.py b/modules/handlers/confirmation.py index edd97a9..207c6be 100644 --- a/modules/handlers/confirmation.py +++ b/modules/handlers/confirmation.py @@ -5,12 +5,15 @@ from pyrogram import filters from pyrogram.types import ReplyKeyboardRemove, InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.enums.parse_mode import ParseMode from classes.holo_user import HoloUser -from modules.utils import configGet, locale, logWrite +from modules.utils import all_locales, configGet, locale, logWrite from modules.handlers.welcome import welcome_pass from modules.database import col_tmp # Confirmation ================================================================================================================= -@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[0][0]))) +confirmation_1 = [] +for pattern in all_locales("confirm", "keyboard"): + confirmation_1.append(pattern[0][0]) +@app.on_message(~ filters.scheduled & filters.private & filters.command(confirmation_1, prefixes=[""])) async def confirm_yes(app, msg): holo_user = HoloUser(msg.from_user) @@ -81,7 +84,10 @@ async def confirm_yes(app, msg): # configSet(["sent"], True, file=str(holo_user.id)) # configSet(["confirmed"], True, file=str(holo_user.id)) -@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[1][0]))) +confirmation_2 = [] +for pattern in all_locales("confirm", "keyboard"): + confirmation_2.append(pattern[1][0]) +@app.on_message(~ filters.scheduled & filters.private & filters.command(confirmation_2, prefixes=[""])) async def confirm_no(app, msg): holo_user = HoloUser(msg.from_user) diff --git a/modules/handlers/contact.py b/modules/handlers/contact.py index 787848b..745e549 100644 --- a/modules/handlers/contact.py +++ b/modules/handlers/contact.py @@ -20,7 +20,7 @@ async def get_contact(app, msg): if application is None: logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id} but user does not exists") - await msg.reply_text(locale("contact_invalid", "message")) + await msg.reply_text(locale("contact_invalid", "message", locale=holo_user.locale)) return application_content = [] @@ -30,24 +30,24 @@ async def get_contact(app, msg): 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} р.)") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") elif i == 3: if application['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']}") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=holo_user.locale)} {application['application'][question]}") i += 1 - application_status = locale("application_status_accepted", "message").format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) + application_status = locale("application_status_accepted", "message", locale=holo_user.locale).format((await app.get_users(application["admin"])).first_name, application["date"].strftime("%d.%m.%Y, %H:%M")) logWrite(f"User {holo_user.id} requested application of {msg.contact.user_id}") - await msg.reply_text(locale("contact", "message").format(str(msg.contact.user_id), "\n".join(application_content), application_status)) + await msg.reply_text(locale("contact", "message", locale=holo_user.locale).format(str(msg.contact.user_id), "\n".join(application_content), application_status)) else: logWrite(f"User {holo_user.id} requested application of someone but user is not telegram user") - await msg.reply_text(locale("contact_not_member", "message")) + await msg.reply_text(locale("contact_not_member", "message", locale=holo_user.locale)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/handlers/welcome.py b/modules/handlers/welcome.py index b0d8940..ca04c7f 100644 --- a/modules/handlers/welcome.py +++ b/modules/handlers/welcome.py @@ -1,10 +1,15 @@ from app import app from pyrogram import filters from pyrogram.types import ForceReply, ReplyKeyboardMarkup -from modules.utils import locale, logWrite +from modules.utils import all_locales, locale, logWrite # Welcome check ================================================================================================================ -@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("welcome", "keyboard")[0][0]) | filters.regex(locale("return", "keyboard")[0][0]))) +welcome_1 = [] +for pattern in all_locales("welcome", "keyboard"): + welcome_1.append(pattern[0][0]) +for pattern in all_locales("return", "keyboard"): + welcome_1.append(pattern[0][0]) +@app.on_message(~ filters.scheduled & filters.private & filters.command(welcome_1, prefixes=[""])) async def welcome_pass(app, msg, once_again: bool = True) -> None: """Set user's stage to 1 and start a fresh application @@ -18,13 +23,16 @@ async def welcome_pass(app, msg, once_again: bool = True) -> None: await msg.reply_text(locale("privacy_notice", "message")) logWrite(f"User {msg.from_user.id} confirmed starting the application") - await msg.reply_text(locale("question1", "message"), reply_markup=ForceReply(placeholder=locale("question1", "force_reply"))) + await msg.reply_text(locale("question1", "message", locale=msg.from_user), reply_markup=ForceReply(placeholder=locale("question1", "force_reply", locale=msg.from_user))) # configSet(["stage"], 1, file=str(msg.from_user.id)) # configSet(["sent"], False, file=str(msg.from_user.id)) -@app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("welcome", "keyboard")[1][0]))) +welcome_2 = [] +for pattern in all_locales("welcome", "keyboard"): + welcome_2.append(pattern[1][0]) +@app.on_message(~ filters.scheduled & filters.private & filters.command(welcome_2, prefixes=[""])) async def welcome_reject(app, msg): logWrite(f"User {msg.from_user.id} rejected to start the application") - await msg.reply_text(locale("goodbye", "message"), reply_markup=ReplyKeyboardMarkup(locale("return", "keyboard"), resize_keyboard=True)) + await msg.reply_text(locale("goodbye", "message", locale=msg.from_user), reply_markup=ReplyKeyboardMarkup(locale("return", "keyboard", locale=msg.from_user), resize_keyboard=True)) # ============================================================================================================================== \ No newline at end of file diff --git a/modules/inline.py b/modules/inline.py index 229b988..4faf39f 100644 --- a/modules/inline.py +++ b/modules/inline.py @@ -16,11 +16,11 @@ async def inline_answer(client, inline_query): await inline_query.answer( results=[ InlineQueryResultArticle( - title=locale("title", "inline", "not_pm"), + title=locale("title", "inline", "not_pm", locale=inline_query.from_user), input_message_content=InputTextMessageContent( - locale("message_content", "inline", "not_pm") + locale("message_content", "inline", "not_pm", locale=inline_query.from_user) ), - description=locale("description", "inline", "not_pm") + description=locale("description", "inline", "not_pm", locale=inline_query.from_user) ) ] ) @@ -32,11 +32,11 @@ async def inline_answer(client, inline_query): await inline_query.answer( results=[ InlineQueryResultArticle( - title=locale("title", "inline", "forbidden"), + title=locale("title", "inline", "forbidden", locale=inline_query.from_user), input_message_content=InputTextMessageContent( - locale("message_content", "inline", "forbidden") + locale("message_content", "inline", "forbidden", locale=inline_query.from_user) ), - description=locale("description", "inline", "forbidden") + description=locale("description", "inline", "forbidden", locale=inline_query.from_user) ) ] ) @@ -64,14 +64,14 @@ async def inline_answer(client, inline_query): 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} р.)") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application']['2'].strftime('%d.%m.%Y')} ({age.years} р.)") elif i == 3: if application['application']['3']['countryCode'] == "UA": - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application']['3']['name']}") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {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']})") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application']['3']['name']} ({application['application']['3']['adminName1']}, {application['application']['3']['countryName']})") else: - application_content.append(f"{locale(f'question{i}', 'message', 'question_titles')} {application['application'][question]}") + application_content.append(f"{locale(f'question{i}', 'message', 'question_titles', locale=inline_query.from_user)} {application['application'][question]}") i += 1 @@ -84,9 +84,9 @@ async def inline_answer(client, inline_query): 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)) + locale("message_content", "inline", "user", locale=inline_query.from_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), + description=locale("description", "inline", "user", locale=inline_query.from_user).format(match.user.first_name, match.user.username), thumb_url=f'{configGet("api")}/?avatar_id={match.user.photo.big_file_id}' ) ) @@ -95,9 +95,9 @@ async def inline_answer(client, inline_query): 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)) + locale("message_content", "inline", "user", locale=inline_query.from_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) + description=locale("description", "inline", "user", locale=inline_query.from_user).format(match.user.first_name, match.user.username) ) ) except FileNotFoundError: @@ -105,9 +105,9 @@ async def inline_answer(client, inline_query): 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)) + locale("message_content", "inline", "user", locale=inline_query.from_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) + description=locale("description", "inline", "user", locale=inline_query.from_user).format(match.user.first_name, match.user.username) ) ) else: @@ -115,9 +115,9 @@ async def inline_answer(client, inline_query): 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)) + locale("message_content", "inline", "user", locale=inline_query.from_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) + description=locale("description", "inline", "user", locale=inline_query.from_user).format(match.user.first_name, match.user.username) ) ) diff --git a/modules/utils.py b/modules/utils.py index c100fb0..317bb97 100644 --- a/modules/utils.py +++ b/modules/utils.py @@ -7,10 +7,9 @@ from ujson import JSONDecodeError as JSONDecodeError from ujson import loads, dumps from sys import exit -from os import kill, sep +from os import kill, listdir, sep from os import name as osname from traceback import print_exc -from classes.holo_user import HoloUser from modules.logging import logWrite @@ -103,7 +102,7 @@ def configGet(key: str, *args: str, file: str = "config"): this_key = this_key[dict_key] return this_key[key] -def locale(key: str, *args: str, locale: Union[str, User, HoloUser] = configGet("locale")) -> Any: +def locale(key: str, *args: str, locale: Union[str, User] = configGet("locale")) -> Any: """Get value of locale string ### Args: * key (`str`): The last key of the locale's keys path. @@ -114,7 +113,7 @@ def locale(key: str, *args: str, locale: Union[str, User, HoloUser] = configGet( """ if isinstance(locale, User): locale = locale.language_code - elif isinstance(locale, HoloUser): + elif hasattr(locale, "locale"): locale = locale.locale if locale is None: @@ -137,6 +136,41 @@ def locale(key: str, *args: str, locale: Union[str, User, HoloUser] = configGet( except KeyError: return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"' +def all_locales(key: str, *args: str) -> list: + """Get value of the provided key and path in all available locales + + ### Args: + * key (`str`): The last key of the locale's keys path. + * *args (`list`): Path to key like: dict[args][key]. + + ### Returns: + * `list`: List of all values in all locales + """ + + output = [] + valid_locales = [] + + files_locales = listdir(f'{configGet("locale", "locations")}') + for entry in files_locales: + valid_locales.append(".".join(entry.split(".")[:-1])) + + for lc in valid_locales: + try: + this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{lc}.json') + except FileNotFoundError: + continue + + this_key = this_dict + for dict_key in args: + this_key = this_key[dict_key] + + try: + output.append(this_key[key]) + except KeyError: + continue + + return output + try: from psutil import Process except ModuleNotFoundError: