Merge updates from dev branch to master #10

Merged
dymik739 merged 12 commits from dev into master 2023-09-12 12:32:45 +03:00
3 changed files with 74 additions and 17 deletions
Showing only changes of commit 2b9ac41ced - Show all commits

View File

@ -7,6 +7,7 @@ import sys
import os
import threading
import importlib
import traceback
# global variables
STOP_REQUESTED = False
@ -57,6 +58,7 @@ class ModuleV1:
return self.RESPONSE
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 ""
@ -75,6 +77,7 @@ class ModuleV2:
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:\ntraceback.format_exc()")
return None
@ -213,6 +216,7 @@ def queue_processor():
time.sleep(1)
except Exception as e:
print(f"[ERROR] queue_processor: current message queue: {message_queue}")
print(f"[ERROR] Traceback:\n{traceback.format_exc()}")
print(f"[ERROR] queue_processor: error while processing message ({e}), trying to delete it...")
try:
del message_queue[0]

View File

@ -6,6 +6,7 @@ import sys
import os
import threading
import importlib
import traceback
from telegram import Message, Chat
@ -58,6 +59,7 @@ class ModuleV1:
return self.RESPONSE
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 ""
@ -77,6 +79,7 @@ class ModuleV2:
return responce
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
@ -203,6 +206,7 @@ def queue_processor():
except Exception:
print(f"[ERROR] queue_processor: current message queue: {message_queue}")
print(f"[ERROR] Traceback:\n{traceback.format_exc()}")
print("[ERROR] queue_processor: error while processing message, trying to delete it...")
try:
del message_queue[0]

View File

@ -10,6 +10,7 @@ def readfile(filename):
# global constants
# Accusative - znahidnyj
WEEKDAYS_ACCUSATIVE = ["понеділок", "вівторок", "середу", "четвер", "п'ятницю", "суботу", "неділю"]
# Genitive - rodovyj
WEEKDAYS_GENITIVE_NEXT = ["наступного понеділка", "наступного вівторка", "наступної середи", "наступного четверга",
"наступної п'ятниці", "наступної суботи", "наступної неділі"]
@ -17,9 +18,25 @@ WEEKDAYS_GENITIVE_NEXT = ["наступного понеділка", "насту
WEEKDAYS_GENITIVE_THIS = ["цього понеділка", "цього вівторка", "цієї середи", "цього четверга", "цієї п'ятниці",
"цієї суботи", "цієї неділі"]
lesson_types_to_strings = {
"lec": "лекція",
"prac": "практика",
"lab": "лабораторна"
}
# global variables
module_path = ""
def escaped_string(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):
@ -43,25 +60,34 @@ def get_human_readable_date(start_datetime, end_datetime,
return human_readable_date
def generate_lesson_description(lesson, start_datetime, end_datetime, current_day, current_week, overrides={}):
output_settings = {"name": True, "date": True, "teacher": True, "link": True}
def get_name_of_lesson_type(lesson_type):
if lesson_type in lesson_types_to_strings:
return lesson_types_to_strings[lesson_type]
def generate_lesson_description(lesson, start_datetime, end_datetime, current_day, current_week, overrides={},
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"{lesson['name']}\n"
result += f"{custom_name_prefix}: {escaped_string(lesson['name'])} ({escaped_string(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"*Дата*: {human_readable_date}\n"
result += f"*Дата*: {escaped_string(human_readable_date)}\n"
if output_settings['teacher']:
result += f"*Викладач*: {lesson['teacher']}\n"
result += f"*Викладач*: {escaped_string(lesson['teacher'])}\n"
if output_settings['link']:
result += f"*Посилання*: {lesson['link']}"
result += f"*Посилання*: {escaped_string(lesson['link'])}\n"
if output_settings['comment'] and 'comment' in lesson:
result += f"*Примітка*: {escaped_string(lesson['comment'])}"
return result
@ -76,8 +102,15 @@ def get_schedule_data_from(filename):
timestamp = day_number * 86400 + int(lesson_time.split(":")[0]) * 3600 \
+ int(lesson_time.split(":")[1]) * 60
new_record = dict(raw_schedule[day_number][lesson_time])
new_record["source"] = filename.split(".json")[0]
new_record = raw_schedule[day_number][lesson_time]
item_source = filename.split(".json")[0]
if new_record.__class__ == list:
for item in new_record:
item["source"] = item_source
else:
new_record["source"] = item_source
baked_schedule[timestamp] = new_record
return baked_schedule
@ -105,14 +138,30 @@ def process_arguments(args, base_day):
return preferences, selected_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="*Назва*"):
lesson_record = schedule[lesson_time]
lesson_start_datetime = datetime.fromtimestamp(reference_time + lesson_time)
lesson_end_datetime = datetime.fromtimestamp(reference_time + lesson_time + 5400)
return generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day,
current_week, overrides=overrides)
if lesson_record.__class__ == dict:
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)
internal_overrides['date'] = False
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]
if 'date' in user_defined_overrides and not user_defined_overrides['date']:
return "\n\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)
def process(message, path):
@ -130,8 +179,8 @@ def process(message, path):
global module_path
module_path = path
schedule = get_schedule_data_from("schedule.json")
schedule.update(get_schedule_data_from("additions.json"))
schedule = get_schedule_data_from("schedule-v2.json")
schedule.update(get_schedule_data_from("additions-v2.json"))
current_time = datetime.now()
@ -161,8 +210,8 @@ def process(message, path):
else:
closest_lesson_time = min(schedule)
return "*Актуальна пара*: " + get_lesson_description(schedule, reference_time, closest_lesson_time, current_day,
current_week)
return get_lesson_description(schedule, reference_time, closest_lesson_time, current_day,
current_week, custom_name_prefix="*Актуальна пара*")
elif base_command == "!пари":
base_day = current_week * 7 + current_day
@ -176,8 +225,8 @@ 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)
lesson_descriptions_list = [get_lesson_description(schedule, reference_time, lesson_time, current_day,
current_week, overrides=preferences, custom_name_prefix="*Назва*")
for lesson_time in lesson_list]
return f"__Пари у {WEEKDAYS_ACCUSATIVE[selected_day % 7]}__:\n" + "\n\n".join(lesson_descriptions_list)