From 0497cbf9b7ab4db1fc77d32e7ec5d8b0eac12c93 Mon Sep 17 00:00:00 2001 From: dymik739 Date: Wed, 6 Sep 2023 17:22:26 +0300 Subject: [PATCH] add support for parse_mode selection in all module APIs and update modules to respect these changes --- main.py | 32 ++++++------ module-testing.py | 23 +++++---- modules/auto-schedule-pro-v2/main.py | 66 +++++++++++++++++------- modules/module-v2-example/index.py | 4 +- modules/transliteration-decoder/index.py | 11 +++- 5 files changed, 91 insertions(+), 45 deletions(-) diff --git a/main.py b/main.py index a210ad9..cdbeb92 100644 --- a/main.py +++ b/main.py @@ -40,6 +40,7 @@ class ModuleV1: # set environmental variables def set_env(self): self.RESPONSE = "" + self.FORMAT = "" def set_predefine(self): try: @@ -55,11 +56,11 @@ class ModuleV1: self.MESSAGE = msg try: exec(self.code) - return self.RESPONSE + return self.RESPONSE, self.FORMAT except Exception as e: print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"") print(f"[ERROR] module v1: traceback:\ntraceback.format_exc()") - return "" + return "", None class ModuleV2: @@ -78,7 +79,7 @@ class ModuleV2: except Exception as e: print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"") print(f"[ERROR] module v2: traceback:\ntraceback.format_exc()") - return None + return None, None # module control unit @@ -190,21 +191,22 @@ def queue_processor(): # modules are used in here for mod in mcu.modules: if mod.enabled: - if mod.version == 1 or mod.version == 2: - response = mod.process(msg) + if mod.version in [1, 2]: + response, formatting = mod.process(msg) if response: - ''' - # protecting output - symbols_to_escape = ['[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'] - for symbol in symbols_to_escape: - response = response.replace(symbol, f"\\{symbol}") - ''' + if formatting == None: + updater.bot.send_message(chat_id=msg.chat.id, text=response, + disable_web_page_preview=True) + print(f"Responded using module {mod.path} ({mod.alias}) with text: {response}") + break - updater.bot.send_message(chat_id=msg.chat.id, text=response, - disable_web_page_preview=True) - print(f"Responded using module {mod.path} ({mod.alias}) with text: {response}") - break + elif formatting in ["Markdown", "MarkdownV2", "HTML"]: + updater.bot.send_message(chat_id=msg.chat.id, text=response, + disable_web_page_preview=True, + parse_mode=formatting) + print(f"Responded using module {mod.path} ({mod.alias}) with text (using {formatting}): {response}") + break del message_queue[0] diff --git a/module-testing.py b/module-testing.py index af6981f..ef88846 100644 --- a/module-testing.py +++ b/module-testing.py @@ -41,6 +41,7 @@ class ModuleV1: # set environmental variables def set_env(self): self.RESPONSE = "" + self.FORMAT = "" def set_predefine(self): try: @@ -56,11 +57,11 @@ class ModuleV1: self.MESSAGE = msg try: exec(self.code) - return self.RESPONSE + return self.RESPONSE, self.FORMAT except Exception as e: print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"") print(f"[ERROR] module v1: traceback:\ntraceback.format_exc()") - return "" + return "", None class ModuleV2: @@ -75,12 +76,11 @@ class ModuleV2: # running the module def process(self, msg): try: - responce = self.obj.process(msg, self.path) - return responce + return self.obj.process(msg, self.path) except Exception as e: print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"") print(f"[ERROR] module v2: traceback:\n{traceback.format_exc()}") - return None + return None, None # module control unit @@ -191,11 +191,16 @@ def queue_processor(): # modules are used in here for mod in mcu.modules: if mod.enabled: - if mod.version == 1 or mod.version == 2: - response = mod.process(msg) + if mod.version in [1, 2]: + response, formatting = mod.process(msg) + if response: - print(f"Responded using module {mod.path} ({mod.alias}) with text: {response}") - break + if formatting == None: + print(f"Responded using module {mod.path} ({mod.alias}) with text: {response}") + break + elif formatting in ["Markdown", "MarkdownV2", "HTML"]: + print(f"Responded using module {mod.path} ({mod.alias}) with text (using {formatting}): {response}") + break del message_queue[0] else: diff --git a/modules/auto-schedule-pro-v2/main.py b/modules/auto-schedule-pro-v2/main.py index 3014ae7..38b8749 100644 --- a/modules/auto-schedule-pro-v2/main.py +++ b/modules/auto-schedule-pro-v2/main.py @@ -28,7 +28,7 @@ lesson_types_to_strings = { # global variables module_path = "" -def escaped_string(input_string): +def escaped_string_markdownV2(input_string): result_string = input_string symbols_to_escape = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'] @@ -38,6 +38,18 @@ def escaped_string(input_string): return result_string + +def escaped_string_html(input_string): + result_string = input_string + + symbols_to_escape = ['<', '>', '/'] + + for symbol in symbols_to_escape: + result_string = result_string.replace(symbol, f"\\{symbol}") + + return result_string + + def get_human_readable_date(start_datetime, end_datetime, current_day, current_week): human_readable_date = "" @@ -66,28 +78,28 @@ def get_name_of_lesson_type(lesson_type): def generate_lesson_description(lesson, start_datetime, end_datetime, current_day, current_week, overrides={}, - custom_name_prefix="*Назва*"): + custom_name_prefix="Назва"): output_settings = {"name": True, "date": True, "teacher": True, "link": True, "comment": True} output_settings.update(overrides) result = "" if output_settings['name']: - result += f"{custom_name_prefix}: {escaped_string(lesson['name'])} ({escaped_string(get_name_of_lesson_type(lesson['type']))})\n" + result += f"{custom_name_prefix}: {escaped_string_html(lesson['name'])} ({escaped_string_html(get_name_of_lesson_type(lesson['type']))})\n" if output_settings['date']: human_readable_date = get_human_readable_date(start_datetime, end_datetime, current_day, current_week) - result += f"*Дата*: {escaped_string(human_readable_date)}\n" + result += f"Дата: {escaped_string_html(human_readable_date)}\n" if output_settings['teacher']: - result += f"*Викладач*: {escaped_string(lesson['teacher'])}\n" + result += f"Викладач: {escaped_string_html(lesson['teacher'])}\n" if output_settings['link']: - result += f"*Посилання*: {escaped_string(lesson['link'])}\n" + result += f"Посилання: {escaped_string_html(lesson['link'])}\n" if output_settings['comment'] and 'comment' in lesson: - result += f"*Примітка*: {escaped_string(lesson['comment'])}" + result += f"Примітка: {escaped_string_html(lesson['comment'])}\n" return result @@ -139,15 +151,31 @@ def process_arguments(args, base_day): def get_lesson_description(schedule, reference_time, lesson_time, current_day, current_week, overrides={}, - custom_name_prefix="*Назва*"): + custom_name_prefix="Назва", force_date_at_top=False): lesson_record = schedule[lesson_time] lesson_start_datetime = datetime.fromtimestamp(reference_time + lesson_time) lesson_end_datetime = datetime.fromtimestamp(reference_time + lesson_time + 5400) if lesson_record.__class__ == dict: - return generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day, - current_week, overrides=overrides) + if force_date_at_top: + user_defined_overrides = dict(overrides) + internal_overrides = dict(overrides) + internal_overrides['date'] = False + + description = generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day, + current_week, overrides=overrides) + + if 'date' in user_defined_overrides and not user_defined_overrides['date']: + return description + else: + human_readable_date = get_human_readable_date(lesson_start_datetime, lesson_end_datetime, + current_day, current_week) + return f"{human_readable_date.capitalize()}:\n" + description + else: + return generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day, + current_week, overrides=overrides) + elif lesson_record.__class__ == list: user_defined_overrides = dict(overrides) internal_overrides = dict(overrides) @@ -157,11 +185,11 @@ def get_lesson_description(schedule, reference_time, lesson_time, current_day, c current_week, overrides=internal_overrides, custom_name_prefix=custom_name_prefix) for i in lesson_record] if 'date' in user_defined_overrides and not user_defined_overrides['date']: - return "\n\n".join(descriptions) + return "\n".join(descriptions) else: human_readable_date = get_human_readable_date(lesson_start_datetime, lesson_end_datetime, current_day, current_week) - return f"__{human_readable_date.capitalize()}__:\n" + "\n\n".join(descriptions) + return f"{human_readable_date.capitalize()}:\n" + "\n".join(descriptions) def process(message, path): @@ -174,7 +202,7 @@ def process(message, path): base_command = full_command[0].lower() if base_command not in ["!пара", "!пари"]: - return "" + return None, None global module_path module_path = path @@ -197,11 +225,11 @@ def process(message, path): current_ts = int(datetime.now().strftime("%s")) if -3600*4 < study_begin_ts - current_ts < 0: - return "Навчання незабаром розпочнеться!" + return "Навчання незабаром розпочнеться!", None elif 0 <= study_begin_ts - current_ts < 1209600: - return f"До навчання залишилося {study_begin_ts - current_ts} секунд..." + return f"До навчання залишилося {study_begin_ts - current_ts} секунд...", None elif study_begin_ts - current_ts >= 1209600: - return "Ви маєте законне право відпочити, пари почнуться не скоро" + return "Ви маєте законне право відпочити, пари почнуться не скоро", None upcoming_lessons = [timestamp for timestamp in schedule if timestamp > current_seconds - 5400] @@ -211,7 +239,7 @@ def process(message, path): closest_lesson_time = min(schedule) return get_lesson_description(schedule, reference_time, closest_lesson_time, current_day, - current_week, custom_name_prefix="*Актуальна пара*") + current_week, custom_name_prefix="Актуальна пара"), "HTML" elif base_command == "!пари": base_day = current_week * 7 + current_day @@ -226,7 +254,7 @@ def process(message, path): lesson_list = [i for i in schedule if selected_day * 86400 <= i < (selected_day + 1) * 86400] lesson_descriptions_list = [get_lesson_description(schedule, reference_time, lesson_time, current_day, - current_week, overrides=preferences, custom_name_prefix="*Назва*") + current_week, overrides=preferences, custom_name_prefix="Назва", force_date_at_top=True) for lesson_time in lesson_list] - return f"__Пари у {WEEKDAYS_ACCUSATIVE[selected_day % 7]}__:\n" + "\n\n".join(lesson_descriptions_list) + return f"Пари у {WEEKDAYS_ACCUSATIVE[selected_day % 7]}:\n\n" + "\n".join(lesson_descriptions_list), "HTML" diff --git a/modules/module-v2-example/index.py b/modules/module-v2-example/index.py index c48f583..dee9fbb 100644 --- a/modules/module-v2-example/index.py +++ b/modules/module-v2-example/index.py @@ -13,4 +13,6 @@ def get_num(): def process(message, path): if message.text == "!v2-testing": - return f"Testing successful - call number {get_num()}" + return f"Testing successful - call number {get_num()}", None + else: + return None, None diff --git a/modules/transliteration-decoder/index.py b/modules/transliteration-decoder/index.py index dcbf772..9415be2 100644 --- a/modules/transliteration-decoder/index.py +++ b/modules/transliteration-decoder/index.py @@ -1,6 +1,14 @@ command = self.MESSAGE['text'].split(" ", 2) command_length = len(command) +def escaped_string(unescaped_string): + result_string = str(unescaped_string) + + for i in ["/", "<", ">"]: + result_string = result_string.replace(i, f"\\{i}") + + return result_string + if (command[0] in self.aliases) and (1 <= command_length <= 3): try: models = json.loads(readfile(self.path + "translate_models.json")) @@ -25,7 +33,8 @@ if (command[0] in self.aliases) and (1 <= command_length <= 3): decoded_text = decoded_text.replace(i[0].capitalize(), i[1].capitalize()) decoded_text = decoded_text.replace(i[0].upper(), i[1].upper()) - self.RESPONSE = f"__Результат__\n{decoded_text}" + self.RESPONSE = f"Результат\n{escaped_string(decoded_text)}" + self.FORMAT = "HTML" except Exception as e: print(f"[translit-decoder] Got exception: {e}")