add support for parse_mode selection in all module APIs and update modules to respect these changes

This commit is contained in:
dymik739 2023-09-06 17:22:26 +03:00
parent 2b9ac41ced
commit 0497cbf9b7
5 changed files with 91 additions and 45 deletions

32
main.py
View File

@ -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]

View File

@ -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:

View File

@ -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="<b>Назва</b>"):
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"<b>Дата</b>: {escaped_string_html(human_readable_date)}\n"
if output_settings['teacher']:
result += f"*Викладач*: {escaped_string(lesson['teacher'])}\n"
result += f"<b>Викладач</b>: {escaped_string_html(lesson['teacher'])}\n"
if output_settings['link']:
result += f"*Посилання*: {escaped_string(lesson['link'])}\n"
result += f"<b>Посилання</b>: {escaped_string_html(lesson['link'])}\n"
if output_settings['comment'] and 'comment' in lesson:
result += f"*Примітка*: {escaped_string(lesson['comment'])}"
result += f"<b>Примітка</b>: {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="<b>Назва</b>", 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"<b><u>{human_readable_date.capitalize()}</u></b>:\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"<b><u>{human_readable_date.capitalize()}</u></b>:\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="<b>Актуальна пара</b>"), "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="<b>Назва</b>", 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"<b><u>Пари у {WEEKDAYS_ACCUSATIVE[selected_day % 7]}</u></b>:\n\n" + "\n".join(lesson_descriptions_list), "HTML"

View File

@ -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

View File

@ -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"<b><u>Результат</u></b>\n{escaped_string(decoded_text)}"
self.FORMAT = "HTML"
except Exception as e:
print(f"[translit-decoder] Got exception: {e}")