forked from dymik739/modular-bot-framework-for-telegram
		
	improve error reporting system, switch to schedule-v2 format in auto-schedule-pro-v2
This commit is contained in:
		
							parent
							
								
									fc450f633e
								
							
						
					
					
						commit
						2b9ac41ced
					
				
							
								
								
									
										4
									
								
								main.py
									
									
									
									
									
								
							
							
						
						
									
										4
									
								
								main.py
									
									
									
									
									
								
							@ -7,6 +7,7 @@ import sys
 | 
				
			|||||||
import os
 | 
					import os
 | 
				
			||||||
import threading
 | 
					import threading
 | 
				
			||||||
import importlib
 | 
					import importlib
 | 
				
			||||||
 | 
					import traceback
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# global variables
 | 
					# global variables
 | 
				
			||||||
STOP_REQUESTED = False
 | 
					STOP_REQUESTED = False
 | 
				
			||||||
@ -57,6 +58,7 @@ class ModuleV1:
 | 
				
			|||||||
            return self.RESPONSE
 | 
					            return self.RESPONSE
 | 
				
			||||||
        except Exception as e:
 | 
					        except Exception as e:
 | 
				
			||||||
            print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{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 ""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -75,6 +77,7 @@ class ModuleV2:
 | 
				
			|||||||
            return self.obj.process(msg, self.path)
 | 
					            return self.obj.process(msg, self.path)
 | 
				
			||||||
        except Exception as e:
 | 
					        except Exception as e:
 | 
				
			||||||
            print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{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
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -213,6 +216,7 @@ def queue_processor():
 | 
				
			|||||||
                    time.sleep(1)
 | 
					                    time.sleep(1)
 | 
				
			||||||
        except Exception as e:
 | 
					        except Exception as e:
 | 
				
			||||||
            print(f"[ERROR] queue_processor: current message queue: {message_queue}")
 | 
					            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...")
 | 
					            print(f"[ERROR] queue_processor: error while processing message ({e}), trying to delete it...")
 | 
				
			||||||
            try:
 | 
					            try:
 | 
				
			||||||
                del message_queue[0]
 | 
					                del message_queue[0]
 | 
				
			||||||
 | 
				
			|||||||
@ -6,6 +6,7 @@ import sys
 | 
				
			|||||||
import os
 | 
					import os
 | 
				
			||||||
import threading
 | 
					import threading
 | 
				
			||||||
import importlib
 | 
					import importlib
 | 
				
			||||||
 | 
					import traceback
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from telegram import Message, Chat
 | 
					from telegram import Message, Chat
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -58,6 +59,7 @@ class ModuleV1:
 | 
				
			|||||||
            return self.RESPONSE
 | 
					            return self.RESPONSE
 | 
				
			||||||
        except Exception as e:
 | 
					        except Exception as e:
 | 
				
			||||||
            print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{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 ""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -77,6 +79,7 @@ class ModuleV2:
 | 
				
			|||||||
            return responce
 | 
					            return responce
 | 
				
			||||||
        except Exception as e:
 | 
					        except Exception as e:
 | 
				
			||||||
            print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{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
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -203,6 +206,7 @@ def queue_processor():
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        except Exception:
 | 
					        except Exception:
 | 
				
			||||||
            print(f"[ERROR] queue_processor: current message queue: {message_queue}")
 | 
					            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...")
 | 
					            print("[ERROR] queue_processor: error while processing message, trying to delete it...")
 | 
				
			||||||
            try:
 | 
					            try:
 | 
				
			||||||
                del message_queue[0]
 | 
					                del message_queue[0]
 | 
				
			||||||
 | 
				
			|||||||
@ -10,6 +10,7 @@ def readfile(filename):
 | 
				
			|||||||
# global constants
 | 
					# global constants
 | 
				
			||||||
# Accusative - znahidnyj
 | 
					# Accusative - znahidnyj
 | 
				
			||||||
WEEKDAYS_ACCUSATIVE = ["понеділок", "вівторок", "середу", "четвер", "п'ятницю", "суботу", "неділю"]
 | 
					WEEKDAYS_ACCUSATIVE = ["понеділок", "вівторок", "середу", "четвер", "п'ятницю", "суботу", "неділю"]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Genitive - rodovyj
 | 
					# Genitive - rodovyj
 | 
				
			||||||
WEEKDAYS_GENITIVE_NEXT = ["наступного понеділка", "наступного вівторка", "наступної середи", "наступного четверга",
 | 
					WEEKDAYS_GENITIVE_NEXT = ["наступного понеділка", "наступного вівторка", "наступної середи", "наступного четверга",
 | 
				
			||||||
                          "наступної п'ятниці", "наступної суботи", "наступної неділі"]
 | 
					                          "наступної п'ятниці", "наступної суботи", "наступної неділі"]
 | 
				
			||||||
@ -17,9 +18,25 @@ WEEKDAYS_GENITIVE_NEXT = ["наступного понеділка", "насту
 | 
				
			|||||||
WEEKDAYS_GENITIVE_THIS = ["цього понеділка", "цього вівторка", "цієї середи", "цього четверга", "цієї п'ятниці",
 | 
					WEEKDAYS_GENITIVE_THIS = ["цього понеділка", "цього вівторка", "цієї середи", "цього четверга", "цієї п'ятниці",
 | 
				
			||||||
                          "цієї суботи", "цієї неділі"]
 | 
					                          "цієї суботи", "цієї неділі"]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					lesson_types_to_strings = {
 | 
				
			||||||
 | 
					        "lec": "лекція",
 | 
				
			||||||
 | 
					        "prac": "практика",
 | 
				
			||||||
 | 
					        "lab": "лабораторна"
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# global variables
 | 
					# global variables
 | 
				
			||||||
module_path = ""
 | 
					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,
 | 
					def get_human_readable_date(start_datetime, end_datetime,
 | 
				
			||||||
                            current_day, current_week):
 | 
					                            current_day, current_week):
 | 
				
			||||||
@ -43,25 +60,34 @@ def get_human_readable_date(start_datetime, end_datetime,
 | 
				
			|||||||
    return human_readable_date
 | 
					    return human_readable_date
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def generate_lesson_description(lesson, start_datetime, end_datetime, current_day, current_week, overrides={}):
 | 
					def get_name_of_lesson_type(lesson_type):
 | 
				
			||||||
    output_settings = {"name": True, "date": True, "teacher": True, "link": True}
 | 
					    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)
 | 
					    output_settings.update(overrides)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    result = ""
 | 
					    result = ""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    if output_settings['name']:
 | 
					    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']:
 | 
					    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"*Дата*: {human_readable_date}\n"
 | 
					        result += f"*Дата*: {escaped_string(human_readable_date)}\n"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    if output_settings['teacher']:
 | 
					    if output_settings['teacher']:
 | 
				
			||||||
        result += f"*Викладач*: {lesson['teacher']}\n"
 | 
					        result += f"*Викладач*: {escaped_string(lesson['teacher'])}\n"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    if output_settings['link']:
 | 
					    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
 | 
					    return result
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -76,8 +102,15 @@ def get_schedule_data_from(filename):
 | 
				
			|||||||
            timestamp = day_number * 86400 + int(lesson_time.split(":")[0]) * 3600 \
 | 
					            timestamp = day_number * 86400 + int(lesson_time.split(":")[0]) * 3600 \
 | 
				
			||||||
                        + int(lesson_time.split(":")[1]) * 60
 | 
					                        + int(lesson_time.split(":")[1]) * 60
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            new_record = dict(raw_schedule[day_number][lesson_time])
 | 
					            new_record = raw_schedule[day_number][lesson_time]
 | 
				
			||||||
            new_record["source"] = filename.split(".json")[0]
 | 
					            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
 | 
					            baked_schedule[timestamp] = new_record
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    return baked_schedule
 | 
					    return baked_schedule
 | 
				
			||||||
@ -105,14 +138,30 @@ def process_arguments(args, base_day):
 | 
				
			|||||||
    return preferences, selected_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_record = schedule[lesson_time]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    lesson_start_datetime = datetime.fromtimestamp(reference_time + lesson_time)
 | 
					    lesson_start_datetime = datetime.fromtimestamp(reference_time + lesson_time)
 | 
				
			||||||
    lesson_end_datetime = datetime.fromtimestamp(reference_time + lesson_time + 5400)
 | 
					    lesson_end_datetime = datetime.fromtimestamp(reference_time + lesson_time + 5400)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    return generate_lesson_description(lesson_record, lesson_start_datetime, lesson_end_datetime, current_day,
 | 
					    if lesson_record.__class__ == dict:
 | 
				
			||||||
                                       current_week, overrides=overrides)
 | 
					        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):
 | 
					def process(message, path):
 | 
				
			||||||
@ -130,8 +179,8 @@ def process(message, path):
 | 
				
			|||||||
    global module_path
 | 
					    global module_path
 | 
				
			||||||
    module_path = path
 | 
					    module_path = path
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    schedule = get_schedule_data_from("schedule.json")
 | 
					    schedule = get_schedule_data_from("schedule-v2.json")
 | 
				
			||||||
    schedule.update(get_schedule_data_from("additions.json"))
 | 
					    schedule.update(get_schedule_data_from("additions-v2.json"))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    current_time = datetime.now()
 | 
					    current_time = datetime.now()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -161,8 +210,8 @@ def process(message, path):
 | 
				
			|||||||
        else:
 | 
					        else:
 | 
				
			||||||
            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)
 | 
					                current_week, custom_name_prefix="*Актуальна пара*")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    elif base_command == "!пари":
 | 
					    elif base_command == "!пари":
 | 
				
			||||||
        base_day = current_week * 7 + current_day
 | 
					        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_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,
 | 
					        lesson_descriptions_list = [get_lesson_description(schedule, reference_time, lesson_time, current_day,
 | 
				
			||||||
                                                                       current_day, current_week, overrides=preferences)
 | 
					                current_week, overrides=preferences, custom_name_prefix="*Назва*")
 | 
				
			||||||
                                    for lesson_time in lesson_list]
 | 
					                                    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)
 | 
				
			||||||
 | 
				
			|||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user