From 9105a0266ca8d1b3391cabbeddd9dc6350ab80b5 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Tue, 29 Nov 2022 18:11:07 +0100 Subject: [PATCH] Fixed that weird behavior on forms setting --- main.py | 74 ++++++++++++++++++++++++------------------------ modules/utils.py | 42 ++++++++++++++------------- 2 files changed, 60 insertions(+), 56 deletions(-) diff --git a/main.py b/main.py index 1a0d059..02d9a8a 100644 --- a/main.py +++ b/main.py @@ -39,10 +39,10 @@ async def cmd_start(app, msg): except FileNotFoundError: jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{msg.from_user.id}.json") user_stage = configGet("stage", file=str(msg.from_user.id)) - configSet("telegram_id", str(msg.from_user.username), file=str(msg.from_user.id)) - configSet("telegram_name", f"{msg.from_user.first_name} {msg.from_user.last_name}", file=str(msg.from_user.id)) - 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)) + configSet(["telegram_id"], str(msg.from_user.username), file=str(msg.from_user.id)) + configSet(["telegram_name"], f"{msg.from_user.first_name} {msg.from_user.last_name}", file=str(msg.from_user.id)) + 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)) 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)) # type: ignore @@ -188,8 +188,8 @@ async def cmd_reapply(app, msg): if configGet("approved", file=str(msg.from_user.id)) or configGet("refused", file=str(msg.from_user.id)): if (configGet("stage", file=str(msg.from_user.id)) == 10) and not (configGet("sent", file=str(msg.from_user.id))): - configSet("reapply", True, file=str(msg.from_user.id)) - configSet("confirmed", False, file=str(msg.from_user.id)) + configSet(["reapply"], True, file=str(msg.from_user.id)) + configSet(["confirmed"], False, file=str(msg.from_user.id)) await welcome_pass(app, msg, once_again=True) else: await msg.reply_text(locale("reapply_in_progress", "message").format(locale("confirm", "keyboard")[1][0])) # type: ignore @@ -210,8 +210,8 @@ async def welcome_pass(app, msg, once_again: bool = True): 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"))) # type: ignore - configSet("stage", 1, file=str(msg.from_user.id)) - configSet("sent", False, file=str(msg.from_user.id)) + 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]))) async def welcome_reject(app, msg): @@ -292,8 +292,8 @@ async def confirm_yes(app, msg): logWrite(f"User {msg.from_user.id} sent his application and it will now be reviewed") - configSet("sent", True, file=str(msg.from_user.id)) - configSet("confirmed", True, file=str(msg.from_user.id)) + configSet(["sent"], True, file=str(msg.from_user.id)) + configSet(["confirmed"], True, file=str(msg.from_user.id)) @app.on_message(~ filters.scheduled & filters.private & (filters.regex(locale("confirm", "keyboard")[1][0]))) async def confirm_no(app, msg): @@ -302,10 +302,10 @@ async def confirm_no(app, msg): if user_stage == 10: jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{msg.from_user.id}.json") - configSet("telegram_id", str(msg.from_user.username), file=str(msg.from_user.id)) - configSet("telegram_name", f"{msg.from_user.first_name} {msg.from_user.last_name}", file=str(msg.from_user.id)) - 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)) + configSet(["telegram_id"], str(msg.from_user.username), file=str(msg.from_user.id)) + configSet(["telegram_name"], f"{msg.from_user.first_name} {msg.from_user.last_name}", file=str(msg.from_user.id)) + 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) logWrite(f"User {msg.from_user.id} restarted the application due to typo in it") # ============================================================================================================================== @@ -340,13 +340,13 @@ async def callback_query_accept(app, clb): ]] )) - configSet("link", link.invite_link, file=fullclb[2]) + configSet(["link"], link.invite_link, file=fullclb[2]) logWrite(f"User {fullclb[2]} got an invite link {link.invite_link}") else: await app.send_message(int(fullclb[2]), locale("approved_joined", "message")) - configSet("approved", True, file=fullclb[2]) - configSet("sent", False, file=fullclb[2]) + configSet(["approved"], True, file=fullclb[2]) + configSet(["sent"], False, file=fullclb[2]) application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json") application[fullclb[2]]["approved"] = True @@ -368,8 +368,8 @@ async def callback_query_refuse_aggressive(app, clb): await app.send_message(int(fullclb[3]), locale("refused", "message")) logWrite(f"User {fullclb[3]} got refused by {clb.from_user.id} due to being aggressive") - configSet("refused", True, file=fullclb[3]) - configSet("sent", False, file=fullclb[3]) + configSet(["refused"], True, file=fullclb[3]) + configSet(["sent"], False, file=fullclb[3]) application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json") application[fullclb[3]]["refused"] = True @@ -392,8 +392,8 @@ async def callback_query_refuse_russian(app, clb): await app.send_message(int(fullclb[3]), locale("refused_russian", "message")) logWrite(f"User {fullclb[3]} got refused by {clb.from_user.id} due to being russian") - configSet("refused", True, file=fullclb[3]) - configSet("sent", False, file=fullclb[3]) + configSet(["refused"], True, file=fullclb[3]) + configSet(["sent"], False, file=fullclb[3]) application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json") application[fullclb[3]]["refused"] = True @@ -415,8 +415,8 @@ async def callback_query_refuse(app, clb): await app.send_message(int(fullclb[2]), locale("refused", "message")) logWrite(f"User {fullclb[2]} got refused by {clb.from_user.id}") - configSet("refused", True, file=fullclb[2]) - configSet("sent", False, file=fullclb[2]) + configSet(["refused"], True, file=fullclb[2]) + configSet(["sent"], False, file=fullclb[2]) application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json") application[fullclb[2]]["refused"] = True @@ -443,8 +443,8 @@ async def callback_reapply_query_accept(app, clb): await app.send_message(int(fullclb[2]), locale("approved_joined", "message")) - configSet("approved", True, file=fullclb[2]) - configSet("sent", False, file=fullclb[2]) + configSet(["approved"], True, file=fullclb[2]) + configSet(["sent"], False, file=fullclb[2]) application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json") application[fullclb[2]]["approved"] = True @@ -466,8 +466,8 @@ async def callback_query_reapply_refuse(app, clb): await app.send_message(int(fullclb[2]), locale("refused", "message")) logWrite(f"User {fullclb[2]} got their reapplication refused by {clb.from_user.id}") - configSet("refused", True, file=fullclb[2]) - configSet("sent", False, file=fullclb[2]) + configSet(["refused"], True, file=fullclb[2]) + configSet(["sent"], False, file=fullclb[2]) application = jsonLoad(f"{configGet('data', 'locations')}{sep}applications.json") application[fullclb[2]]["refused"] = True @@ -520,9 +520,9 @@ async def callback_query_sus_refuse(app, clb): await app.ban_chat_member(configGet("destination_group"), int(fullclb[2])) jsonSave(jsonLoad(f"{configGet('data', 'locations')}{sep}user_default.json"), f"{configGet('data', 'locations')}{sep}users{sep}{fullclb[2]}.json") - configSet("stage", 10, file=fullclb[2]) - configSet("refused", True, file=fullclb[2]) - configSet("refused_by", clb.from_user.id, file=fullclb[2]) + configSet(["stage"], 10, file=fullclb[2]) + configSet(["refused"], True, file=fullclb[2]) + configSet(["refused_by"], clb.from_user.id, file=fullclb[2]) # ============================================================================================================================== @@ -586,14 +586,14 @@ async def any_stage(app, msg): 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)) + configSet(["application", str(user_stage)], str(msg.text), 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)) + configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id)) input_dt = datetime.strptime(msg.text, "%d.%m.%Y") @@ -608,7 +608,7 @@ async def any_stage(app, msg): 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)) + 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") @@ -618,12 +618,12 @@ async def any_stage(app, msg): 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)) + configSet(["application", str(user_stage)], str(msg.text), 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)) + configSet(["application", str(user_stage)], str(msg.text), file=str(msg.from_user.id)) application_content = [] i = 1 for question in configGet("application", file=str(msg.from_user.id)): diff --git a/modules/utils.py b/modules/utils.py index 1d462d4..260bcb6 100644 --- a/modules/utils.py +++ b/modules/utils.py @@ -1,4 +1,4 @@ -from typing import Union +from typing import Any, Union from ujson import JSONDecodeError as JSONDecodeError from ujson import loads, dumps @@ -32,13 +32,27 @@ def jsonSave(contents, filename): return -def configSet(key: str, value, *args: str, file: str = "config"): - """Set key to a value +def nested_set(dic, keys, value, create_missing=True): + d = dic + for key in keys[:-1]: + if key in d: + d = d[key] + elif create_missing: + d = d.setdefault(key, {}) + else: + return dic + if keys[-1] in d or create_missing: + d[keys[-1]] = value + return dic + +def configSet(keys: list, value: Any, file: str = "config", create_missing=True): + """Set config's value to provided one + Args: - * key (str): The last key of the keys path. - * value (str/int/float/list/dict/None): Some needed value. - * *args (str): Path to key like: dict[args][key]. - * file (str): User ID to save. Saved to config if not provided. Defaults to "config". + * keys (list): List of keys from the highest one to target + * value (Any): Needed value + * file (str, optional): File (if not config). Defaults to "config". + * create_missing (bool, optional): Create missing items on the way. Defaults to True. """ if file == "config": filepath = "" @@ -52,18 +66,8 @@ def configSet(key: str, value, *args: str, file: str = "config"): else: filepath = f"data{sep}users{sep}" this_dict = jsonLoad(f"{filepath}{file}.json") - string = "this_dict" - for arg in args: - string += f'["{arg}"]' - if type(value) in [str]: - value.replace("'", "\'").replace('"', '\"') - #if len(value) < 30: - # string += f'["{key}"] = "{value}"' - #else: - string += f'["{key}"] = """{value}"""' - else: - string += f'["{key}"] = {value}' - exec(string) + + this_dict = nested_set(this_dict, keys, value, create_missing=create_missing) jsonSave(this_dict, f"{filepath}{file}.json") return