PEP8 autoformat and message formatting changes. #9

Closed
Rhinemann wants to merge 1 commits from Rhinemann/modular-bot-framework-for-telegram:dev into dev
2 changed files with 33 additions and 29 deletions

16
main.py
View File

@ -98,7 +98,7 @@ class ModuleControlUnit:
print(f"[WARN] module_loader: no meta.json found in module folder \"{folder}\"") print(f"[WARN] module_loader: no meta.json found in module folder \"{folder}\"")
continue continue
meta = json.loads( meta_raw ) meta = json.loads(meta_raw)
if "version" in meta: if "version" in meta:
if meta["version"] == 1: if meta["version"] == 1:
if "index_file" in meta: if "index_file" in meta:
@ -106,8 +106,8 @@ class ModuleControlUnit:
else: else:
index_file = "index.py" index_file = "index.py"
code = readfile( "modules/{}/{}".format(folder, index_file) ) code = readfile("modules/{}/{}".format(folder, index_file))
if not code: # False both when readfile() returns False and when the code string is empty if not code: # False both when readfile() returns False and when the code string is empty
print("[WARN] reload_modules: module {} does not have any code, skipping...".format(folder)) print("[WARN] reload_modules: module {} does not have any code, skipping...".format(folder))
continue continue
@ -166,7 +166,7 @@ def queue_processor():
try: try:
if len(message_queue) > 0: if len(message_queue) > 0:
msg = message_queue[0] msg = message_queue[0]
print("[DEBUG] queue_processor: {}".format(msg)) # debug print("[DEBUG] queue_processor: {}".format(msg)) # debug
# check for control commands # check for control commands
if msg["chat"]["id"] == 575246355: if msg["chat"]["id"] == 575246355:
@ -203,9 +203,10 @@ def queue_processor():
elif formatting in ["Markdown", "MarkdownV2", "HTML"]: elif formatting in ["Markdown", "MarkdownV2", "HTML"]:
updater.bot.send_message(chat_id=msg.chat.id, text=response, updater.bot.send_message(chat_id=msg.chat.id, text=response,
disable_web_page_preview=True, disable_web_page_preview=True,
parse_mode=formatting) parse_mode=formatting)
print(f"Responded using module {mod.path} ({mod.alias}) with text (using {formatting}): {response}") print(
f"Responded using module {mod.path} ({mod.alias}) with text (using {formatting}): {response}")
break break
del message_queue[0] del message_queue[0]
@ -247,7 +248,6 @@ mcu = ModuleControlUnit()
processor_thread = threading.Thread(target=queue_processor, args=[]) processor_thread = threading.Thread(target=queue_processor, args=[])
processor_thread.start() processor_thread.start()
# connecting to Telegram servers and listening for messages # connecting to Telegram servers and listening for messages
TOKEN = readfile("config/token") TOKEN = readfile("config/token")

View File

@ -19,15 +19,15 @@ WEEKDAYS_GENITIVE_THIS = ["цього понеділка", "цього вівт
"цієї суботи", "цієї неділі"] "цієї суботи", "цієї неділі"]
lesson_types_to_strings = { lesson_types_to_strings = {
"lec": "лекція", "lec": "лекція",
"prac": "практика", "prac": "практика",
"lab": "лабораторна" "lab": "лабораторна"
} }
# global variables # global variables
module_path = "" module_path = ""
def escaped_string_markdownV2(input_string): def escaped_string_markdownV2(input_string):
result_string = input_string result_string = input_string
@ -78,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={}, def generate_lesson_description(lesson, start_datetime, end_datetime, current_day, current_week, overrides={},
custom_name_prefix="<b>Назва</b>"): custom_name_prefix="<b>Назва</b>"):
output_settings = {"name": True, "date": True, "teacher": True, "link": True, "comment": True} output_settings = {"name": True, "date": True, "teacher": True, "link": True, "comment": True}
output_settings.update(overrides) output_settings.update(overrides)
result = "" result = ""
if output_settings['name']: if output_settings['name']:
result += f"{custom_name_prefix}: {escaped_string_html(lesson['name'])} ({escaped_string_html(get_name_of_lesson_type(lesson['type']))})\n" result += f"<b>{escaped_string_html(lesson['name'])}<b> ({escaped_string_html(get_name_of_lesson_type(lesson['type']))})\n"
if output_settings['date']: if output_settings['date']:
human_readable_date = get_human_readable_date(start_datetime, end_datetime, human_readable_date = get_human_readable_date(start_datetime, end_datetime,
current_day, current_week) current_day, current_week)
result += f"<b>Дата</b>: {escaped_string_html(human_readable_date)}\n" result += f"<i>Дата</ii>: {escaped_string_html(human_readable_date)}\n"
if output_settings['teacher']: if output_settings['teacher']:
result += f"<b>Викладач</b>: {escaped_string_html(lesson['teacher'])}\n" result += f"<i>Викладач</i>: {escaped_string_html(lesson['teacher'])}\n"
if output_settings['link']: if output_settings['link']:
result += f"<b>Посилання</b>: {escaped_string_html(lesson['link'])}\n" result += f"<i>Посилання</i>: {escaped_string_html(lesson['link'])}\n"
if output_settings['comment'] and 'comment' in lesson: if output_settings['comment'] and 'comment' in lesson:
result += f"<b>Примітка</b>: {escaped_string_html(lesson['comment'])}\n" result += f"<i>Примітка</i>: {escaped_string_html(lesson['comment'])}\n"
return result return result
@ -151,7 +151,7 @@ def process_arguments(args, base_day):
def get_lesson_description(schedule, reference_time, lesson_time, current_day, current_week, overrides={}, def get_lesson_description(schedule, reference_time, lesson_time, current_day, current_week, overrides={},
custom_name_prefix="<b>Назва</b>", force_date_at_top=False): custom_name_prefix="<b>Назва</b>", force_date_at_top=False):
lesson_record = schedule[lesson_time] lesson_record = schedule[lesson_time]
lesson_start_datetime = datetime.fromtimestamp(reference_time + lesson_time) lesson_start_datetime = datetime.fromtimestamp(reference_time + lesson_time)
@ -163,18 +163,19 @@ def get_lesson_description(schedule, reference_time, lesson_time, current_day, c
internal_overrides = dict(overrides) internal_overrides = dict(overrides)
internal_overrides['date'] = False internal_overrides['date'] = False
description = generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day, description = generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime,
current_week, overrides=internal_overrides) current_day,
current_week, overrides=internal_overrides)
if 'date' in user_defined_overrides and not user_defined_overrides['date']: if 'date' in user_defined_overrides and not user_defined_overrides['date']:
return description return description
else: else:
human_readable_date = get_human_readable_date(lesson_start_datetime, lesson_end_datetime, human_readable_date = get_human_readable_date(lesson_start_datetime, lesson_end_datetime,
current_day, current_week) current_day, current_week)
return f"<b><u>{human_readable_date.capitalize()}</u></b>:\n" + description return f"<b><u>{human_readable_date.capitalize()}</u></b>:\n" + description
else: else:
return generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day, return generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day,
current_week, overrides=overrides) current_week, overrides=overrides)
elif lesson_record.__class__ == list: elif lesson_record.__class__ == list:
user_defined_overrides = dict(overrides) user_defined_overrides = dict(overrides)
@ -182,13 +183,14 @@ def get_lesson_description(schedule, reference_time, lesson_time, current_day, c
internal_overrides['date'] = False internal_overrides['date'] = False
descriptions = [generate_lesson_description(i, lesson_start_datetime, lesson_end_datetime, current_day, descriptions = [generate_lesson_description(i, lesson_start_datetime, lesson_end_datetime, current_day,
current_week, overrides=internal_overrides, custom_name_prefix=custom_name_prefix) for i in lesson_record] 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']: if 'date' in user_defined_overrides and not user_defined_overrides['date']:
return "\n".join(descriptions) return "\n".join(descriptions)
else: else:
human_readable_date = get_human_readable_date(lesson_start_datetime, lesson_end_datetime, human_readable_date = get_human_readable_date(lesson_start_datetime, lesson_end_datetime,
current_day, current_week) current_day, current_week)
return f"<b><u>{human_readable_date.capitalize()}</u></b>:\n" + "\n".join(descriptions) return f"<b><u>{human_readable_date.capitalize()}</u></b>:\n" + "\n".join(descriptions)
@ -224,7 +226,7 @@ def process(message, path):
study_begin_ts = int(datetime(year=2023, month=9, day=4).strftime("%s")) study_begin_ts = int(datetime(year=2023, month=9, day=4).strftime("%s"))
current_ts = int(datetime.now().strftime("%s")) current_ts = int(datetime.now().strftime("%s"))
if -3600*4 < study_begin_ts - current_ts < 0: if -3600 * 4 < study_begin_ts - current_ts < 0:
return "Навчання незабаром розпочнеться!", None return "Навчання незабаром розпочнеться!", None
elif 0 <= study_begin_ts - current_ts < 1209600: elif 0 <= study_begin_ts - current_ts < 1209600:
return f"До навчання залишилося {study_begin_ts - current_ts} секунд...", None return f"До навчання залишилося {study_begin_ts - current_ts} секунд...", None
@ -239,7 +241,7 @@ def process(message, path):
closest_lesson_time = min(schedule) closest_lesson_time = min(schedule)
return get_lesson_description(schedule, reference_time, closest_lesson_time, current_day, return get_lesson_description(schedule, reference_time, closest_lesson_time, current_day,
current_week, custom_name_prefix="<b>Актуальна пара</b>"), "HTML" current_week, custom_name_prefix="<b>Актуальна пара</b>"), "HTML"
elif base_command == "!пари": elif base_command == "!пари":
base_day = current_week * 7 + current_day base_day = current_week * 7 + current_day
@ -254,7 +256,9 @@ def process(message, path):
lesson_list = [i for i in schedule if selected_day * 86400 <= i < (selected_day + 1) * 86400] 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, lesson_descriptions_list = [get_lesson_description(schedule, reference_time, lesson_time, current_day,
current_week, overrides=preferences, custom_name_prefix="<b>Назва</b>", force_date_at_top=True) current_week, overrides=preferences,
custom_name_prefix="<b>Назва</b>", force_date_at_top=True)
for lesson_time in lesson_list] for lesson_time in lesson_list]
return f"<b><u>Пари у {WEEKDAYS_ACCUSATIVE[selected_day % 7]}</u></b>:\n\n\n" + "\n\n".join(lesson_descriptions_list), "HTML" return f"<b><u>Пари у {WEEKDAYS_ACCUSATIVE[selected_day % 7]}</u></b>:\n\n\n" + "\n\n".join(
lesson_descriptions_list), "HTML"