15 Commits

Author SHA1 Message Date
dymik739 8cc68080e8 auto-schedule-pro: update schedule.json 2023-09-05 13:17:15 +03:00
dymik739 94275048bb auto-schedule-pro: updated schedule.json 2023-09-05 11:47:34 +03:00
dymik739 1504e03e13 main.py: added temporary fix for MarkdownV2 support 2023-09-05 11:46:59 +03:00
dymik739 87424c8786 transliteration-decoder: add support for MarkdownV2 2023-09-04 21:36:13 +03:00
dymik739 b21b16b817 auto-schedule-pro-v2: add initial support for MarkdownV2 2023-09-04 21:34:33 +03:00
dymik739 12ee02cee0 main.py: enable MarkdownV2 formatting 2023-09-04 21:33:23 +03:00
dymik739 ba353a3609 auto-schedule-pro: update schedule.json 2023-09-03 07:56:45 +03:00
dymik739 69cb179d87 auto-schedule-pro: update schedule for 3 semester 2023-08-08 18:18:46 +03:00
dymik739 1bd7fc2ef1 auto-schedule-pro-v2: improve holiday exclusive easter egg (triggered at !пара) 2023-08-07 23:32:45 +03:00
dymik739 535087fae1 auto-schedule-pro-v2: temporary change responce to !пара (holidays exclusive) 2023-08-07 22:58:32 +03:00
dymik739 e8a61a9e36 auto-schedule-pro: commit last additions.json edit as of 2 semester 2023-08-07 22:33:37 +03:00
dymik739 5d7f89cff0 auto-schedule-pro: fix issues related to reading links from containers 2023-08-07 22:32:10 +03:00
dymik739 763cc4d131 add new module: translator 2023-08-01 12:09:35 +03:00
dymik739 bd22e8e9b6 hotfix: make bot core API v1 respect recent change from self.RESPONCE to self.RESPONSE 2023-06-29 13:46:44 +03:00
dymik739 44628a3021 qna-basic: fix broken database file after code refactoring 2023-06-27 16:01:42 +03:00
10 changed files with 112 additions and 51 deletions
+17 -11
View File
@@ -38,7 +38,7 @@ class ModuleV1:
# set environmental variables # set environmental variables
def set_env(self): def set_env(self):
self.RESPONCE = "" self.RESPONSE = ""
def set_predefine(self): def set_predefine(self):
try: try:
@@ -54,7 +54,7 @@ class ModuleV1:
self.MESSAGE = msg self.MESSAGE = msg
try: try:
exec(self.code) exec(self.code)
return self.RESPONCE 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}\"")
return "" return ""
@@ -72,8 +72,7 @@ class ModuleV2:
# running the module # running the module
def process(self, msg): def process(self, msg):
try: try:
response = self.obj.process(msg, self.path) return self.obj.process(msg, self.path)
return response
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}\"")
return None return None
@@ -189,11 +188,18 @@ def queue_processor():
for mod in mcu.modules: for mod in mcu.modules:
if mod.enabled: if mod.enabled:
if mod.version == 1 or mod.version == 2: if mod.version == 1 or mod.version == 2:
responce = mod.process(msg) response = mod.process(msg)
if responce:
updater.bot.send_message(chat_id=msg.chat.id, text=responce, if response:
disable_web_page_preview=True) # protecting output
print(f"Responded using module {mod.path} ({mod.alias}) with text: {responce}") symbols_to_escape = ['[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
for symbol in symbols_to_escape:
response = response.replace(symbol, f"\\{symbol}")
updater.bot.send_message(chat_id=msg.chat.id, text=response,
disable_web_page_preview=True,
parse_mode="MarkdownV2")
print(f"Responded using module {mod.path} ({mod.alias}) with text: {response}")
break break
del message_queue[0] del message_queue[0]
@@ -204,9 +210,9 @@ def queue_processor():
break break
else: else:
time.sleep(1) time.sleep(1)
except Exception: 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("[ERROR] queue_processor: error while processing message, 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]
print("[INFO] queue_processor: deleted broken message from the queue") print("[INFO] queue_processor: deleted broken message from the queue")
+16 -6
View File
@@ -55,13 +55,13 @@ def generate_lesson_description(lesson, start_datetime, end_datetime, current_da
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"*Дата*: {human_readable_date}\n"
if output_settings['teacher']: if output_settings['teacher']:
result += f"Викладач: {lesson['teacher']}\n" result += f"*Викладач*: {lesson['teacher']}\n"
if output_settings['link']: if output_settings['link']:
result += f"Посилання на пару: {lesson['link']}" result += f"*Посилання*: {lesson['link']}"
return result return result
@@ -144,6 +144,16 @@ def process(message, path):
reference_time = int(current_time.strftime("%s")) - current_seconds reference_time = int(current_time.strftime("%s")) - current_seconds
if base_command == "!пара": if base_command == "!пара":
study_begin_ts = int(datetime(year=2023, month=9, day=4).strftime("%s"))
current_ts = int(datetime.now().strftime("%s"))
if -3600*4 < study_begin_ts - current_ts < 0:
return "Навчання незабаром розпочнеться!"
elif 0 <= study_begin_ts - current_ts < 1209600:
return f"До навчання залишилося {study_begin_ts - current_ts} секунд..."
elif study_begin_ts - current_ts >= 1209600:
return "Ви маєте законне право відпочити, пари почнуться не скоро"
upcoming_lessons = [timestamp for timestamp in schedule if timestamp > current_seconds - 5400] upcoming_lessons = [timestamp for timestamp in schedule if timestamp > current_seconds - 5400]
if len(upcoming_lessons) > 0: if len(upcoming_lessons) > 0:
@@ -151,7 +161,7 @@ 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)
elif base_command == "!пари": elif base_command == "!пари":
@@ -166,8 +176,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_week, overrides=preferences) current_day, current_week, overrides=preferences)
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)
-1
View File
@@ -1,6 +1,5 @@
[ [
{ {
"12:20": {"name": "Культура мовлення та ділове мовлення", "teacher": "Кушлаба М. П.", "link": "https://bbb.comsys.kpi.ua/b/myk-0iw-red-p01"}
}, },
{ {
}, },
+30 -27
View File
@@ -1,52 +1,55 @@
[ [
{ {
"8:30": {"name": "Дискретна математика (лекція)", "teacher": "Новотарський М. А.", "link": "https://us02web.zoom.us/j/87578307057?pwd=UGwyVGlwc3M4Q0Q0Q0NLWUt6bmVpUT09"}, "8:30": {"name": "Політична наука: конфліктологічний підхід (лекція)", "teacher": "Багінський Андрій Владиславович", "link": "(посилання відсутнє!)"},
"10:25": {"name": "Комп'ютерна логіка (лекція)", "teacher": "Жабін В. І.", "link": "https://bbb.comsys.kpi.ua/b/val-2vb-o7w-y5y АБО https://bbb.ugrid.org/b/val-osi-lup-ou8"}, "10:25": {"name": "Захист персональних даних: стандарти ЄС та Ради Європи & Психологія & Психологія конфлікту (лекції/практики)", "teacher": "Дубняк М. В. & Волянюк Н. Ю. & Москаленко О. В.", "link": "https://us04web.zoom.us/j/7423381732?pwd=c1pJclU2ZDRUWDgyUE10dmhJUDhiZz09 & https://us04web.zoom.us/j/6762396563?pwd=L1EvTmpFZHBSdkRHUjZyRG95SFl4QT09 & https://zoom.us/j/5175581158?pwd=UlhFY3lBOUUrNG9pclRVNndTNTZzQT09"},
"12:20": {"name": "Культура мовлення та ділове мовлення (лекція)", "teacher": "Онуфрієнко О. П.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"} "14:15": {"name": "Основи електронного урядування (лекція)", "teacher": "Чукут Світлана Анатоліївна", "link": "(посилання відсутнє!)"}
}, },
{ {
"12:20": {"name": "Англійська мова I (практика)", "teacher": "Шевченко О. М.", "link": "https://meet.google.com/bwg-pdnr-evh"}, "12:20": {"name": "Інженерія програмного забезпечення (лабораторна)", "teacher": "Васильєва Марія Давидівна", "link": "https://zoom.us/wc/88696149166/join?from=join&_x_zm_rtaid=qhdJKhYLQNakh-zwxMG4lg.1693903841334.ad606145c892a54a4b450526e2394cbe&_x_zm_rhtaid=531"},
"14:15": {"name": "Фізика (лабораторна)", "teacher": "Федотов В. В. & Іванова І. М.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"} "14:15": {"name": "Теорія електричних кіл та сигналів (лабораторна)", "teacher": "Лободзинський В. Ю. & Ілліна О. О.", "link": "https://meet.google.com/gwx-sshq-sqb"}
}, },
{ {
"8:30": {"name": "Програмування II. Об'єктно-орієнтоване програмування (лабораторна)", "teacher": "Алещенко О. В.", "link": "https://us02web.zoom.us/j/2711546637?pwd=Ry82RHp3SjV6WTZRMXl6WUNod25hUT09"}, "8:30": {"name": "Теорія ймовірності та математична статистика (лекція)", "teacher": "Марковський Олександр Петрович", "link": "(посилання відсутнє!)"},
"10:25": {"name": "Вища математика (практика)", "teacher": "Ординська З. П.", "link": "https://us04web.zoom.us/j/2684350438?pwd=kiOi3BrgbJHeYvkrx7qaSxa08J8m8O.1"} "10:25": {"name": "Вступ до операційної системи Linux (лекція)", "teacher": "Роковий Олександр Петрович", "link": "(посилання відсутнє!)"},
"12:20": {"name": "Інженерія програмного забезпечення (лекція)", "teacher": "Васильєва Марія Давидівна", "link": "(посилання відсутнє!)"}
}, },
{ {
"10:25": {"name": "Вища математика (лекція)", "teacher": "Ординська З. П.", "link": "https://us04web.zoom.us/j/2684350438?pwd=kiOi3BrgbJHeYvkrx7qaSxa08J8m8O.1"}, "10:25": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (практика)", "teacher": "Стаматієва Вікторія В'ячеславівна", "link": "(посилання відсутнє!)"},
"12:20": {"name": "Фізика (лекція)", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!", "container_id": "1"}, "12:20": {"name": "Практичний курс іноземної мови. Частина 2 (практика)", "teacher": "Шевченко Ольга Миколаївна", "link": "(старе посилання!) https://meet.google.com/bwg-pdnr-evh"},
"14:15": {"name": "Програмування II. Об'єктно-орієнтоване програмування (лекція)", "teacher": "Алещенко О. В.", "link": "https://us02web.zoom.us/j/2711546637?pwd=Ry82RHp3SjV6WTZRMXl6WUNod25hUT09"} "14:15": {"name": "Соціальна психологія (практика)", "teacher": "Блохіна Ірина Олександрівна", "link": "(посилання відсутнє!)"},
"16:10": {"name": "Основи електронного урядування (практика)", "teacher": "Чукут Світлана Анатоліївна", "link": "(посилання відсутнє!)"}
}, },
{ {
"10:25": {"name": "Фізика (практика)", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!", "container_id": "1"}, "8:30": {"name": "Вступ до філософії (лекція)", "teacher": "Руденко Тамара Петрівна", "link": "(посилання відсутнє!)"},
"12:20": {"name": "Дискретна математика (лабораторна)", "teacher": "Пономаренко А. М.", "link": "https://us05web.zoom.us/j/7089075754?pwd=TWRlZmxyVlFiTWU1UGlVVU1XcFE0Zz09"}, "10:25": {"name": "Теорія електричних кіл та сигналів (лекція)", "teacher": "Лободзинський Вадим Юрійович", "link": "https://meet.google.com/gwx-sshq-sqb"},
"14:15": {"name": "Основи здорового способу життя (практика)", "teacher": "Соболенко А. І.", "link": "https://zoom.us/j/2035574145?pwd=bk1wTVhGbjJsQTR4WmVQMlROWFBCZz09"} "12:20": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (лекція)", "teacher": "Овчар Раїса Федорівна", "link": "(посилання відсутнє!)"}
}, },
{}, {},
{}, {},
{ {
"8:30": {"name": "Дискретна математика (лекція)", "teacher": "Новотарський М. А.", "link": "https://us02web.zoom.us/j/87578307057?pwd=UGwyVGlwc3M4Q0Q0Q0NLWUt6bmVpUT09"}, "10:25": {"name": "Психологія & Психологія конфлікту (практики)", "teacher": "Сербова О. В. & Кононець М. О.", "link": "https://us04web.zoom.us/j/6762396563?pwd=L1EvTmpFZHBSdkRHUjZyRG95SFl4QT09 & https://zoom.us/j/5175581158?pwd=UlhFY3lBOUUrNG9pclRVNndTNTZzQT09"},
"10:25": {"name": "Комп'ютерна логіка (лекція)", "teacher": "Жабін В. І.", "link": "https://bbb.comsys.kpi.ua/b/val-2vb-o7w-y5y АБО https://bbb.ugrid.org/b/val-osi-lup-ou8"}, "12:20": {"name": "Політична наука: конфліктологічний підхід & Захист персональних даних: стандарти ЄС та Ради Європи (практики)", "teacher": "Северинчик О. П. & Самчинська О. А.", "link": "https://zoom.us/j/5175581158?pwd=UlhFY3lBOUUrNG9pclRVNndTNTZzQT09 & (посилання відсутнє!)"},
"12:20": {"name": "Вища математика (лекція)", "teacher": "Ординська З. П.", "link": "https://us04web.zoom.us/j/2684350438?pwd=kiOi3BrgbJHeYvkrx7qaSxa08J8m8O.1"} "14:15": {"name": "Розумні міста (лекція)", "teacher": "Чукут Світлана Анатоліївна", "link": "(посилання відсутнє!)"}
}, },
{ {
"8:30": {"name": "Комп'ютерна логіка (лабораторна)", "teacher": "Верба О. А.", "link": "https://us04web.zoom.us/j/7382214783?pwd=RnZ3SWgwK1JoVkZtNndnKzdPZjFGdz09"}, "10:25": {"name": "Вступ до філософії (практика)", "teacher": "Руденко Тамара Петрівна", "link": "(посилання відсутнє!)"},
"10:25": {"name": "Вища математика (практика)", "teacher": "Ординська З. П.", "link": "https://us04web.zoom.us/j/2684350438?pwd=kiOi3BrgbJHeYvkrx7qaSxa08J8m8O.1"}, "14:15": {"name": "Теорія ймовірності та математична статистика (практика)", "teacher": "Марковський Олександр Петрович", "link": "(посилання відсутнє!)"}
"12:20": {"name": "Англійська мова I (практика)", "teacher": "Шевченко О. М.", "link": "https://meet.google.com/bwg-pdnr-evh"},
"14:15": {"name": "Фізика (лабораторна)", "teacher": "Федотов В. В. & Іванова І. М.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"}
}, },
{ {
"10:25": {"name": "Вища математика (практика)", "teacher": "Ординська З. П.", "link": "https://us04web.zoom.us/j/2684350438?pwd=kiOi3BrgbJHeYvkrx7qaSxa08J8m8O.1"} "8:30": {"name": "Теорія ймовірності та математична статистика (лекція)", "teacher": "Марковський Олександр Петрович", "link": "(посилання відсутнє!)"},
"10:25": {"name": "Вступ до операційної системи Linux (лекція)", "teacher": "Роковий Олександр Петрович", "link": "(посилання відсутнє!)"},
"12:20": {"name": "Інженерія програмного забезпечення (лекція)", "teacher": "Васильєва Марія Давидівна", "link": "(посилання відсутнє!)"},
"14:15": {"name": "Інженерія програмного забезпечення (лекція)", "teacher": "Васильєва Марія Давидівна", "link": "(посилання відсутнє!)"}
}, },
{ {
"10:25": {"name": "Вища математика (лекція)", "teacher": "Ординська З. П.", "link": "https://us04web.zoom.us/j/2684350438?pwd=kiOi3BrgbJHeYvkrx7qaSxa08J8m8O.1"}, "8:30": {"name": "Вступ до операційної системи Linux (лабораторна)", "teacher": "Алєнін Олег Ігорович", "link": "(посилання відсутнє!)"},
"12:20": {"name": "Фізика (лекція)", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!", "container_id": "1"}, "10:25": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (практика)", "teacher": "Стаматієва Вікторія В'ячеславівна", "link": "(старе посилання!) https://us04web.zoom.us/j/2313886209?pwd=dnZHanV3cU9LUXJBVWYyYVArUFg5dz09"},
"14:15": {"name": "Програмування II. Об'єктно-орієнтоване програмування (лекція)", "teacher": "Алещенко О. В.", "link": "https://us02web.zoom.us/j/2711546637?pwd=Ry82RHp3SjV6WTZRMXl6WUNod25hUT09"} "12:20": {"name": "Практичний курс іноземної мови. Частина 2 (практика)", "teacher": "Шевченко Ольга Миколаївна", "link": "(старе посилання!) https://meet.google.com/bwg-pdnr-evh"},
"14:15": {"name": "Соціальна психологія (лекція) & Розумні міста (практика)", "teacher": "Винославська О. В. & Чукут С. А.", "link": "(посилання відсутні!)"}
}, },
{ {
"10:25": {"name": "Фізика (практика)", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!", "container_id": "1"}, "10:25": {"name": "Теорія електричних кіл та сигналів (лекція)", "teacher": "Лободзинський Вадим Юрійович", "link": "https://meet.google.com/gwx-sshq-sqb"},
"12:20": {"name": "Культура мовлення та ділове мовлення (практика)", "teacher": "Кушлаба М. П.", "link": "https://bbb.comsys.kpi.ua/b/myk-0iw-red-p01"}, "12:20": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (лекція)", "teacher": "Овчар Раїса Федорівна", "link": "(посилання відсутнє!)"}
"14:15": {"name": "Основи здорового способу життя (практика)", "teacher": "Соболенко А. І.", "link": "https://zoom.us/j/2035574145?pwd=bk1wTVhGbjJsQTR4WmVQMlROWFBCZz09"}
}, },
{}, {},
{} {}
+5 -4
View File
@@ -1,5 +1,6 @@
import datetime import datetime
import json import json
import time
import os import os
current_time = datetime.datetime.now() current_time = datetime.datetime.now()
@@ -84,7 +85,7 @@ if next_pair_time == None:
#print("test3.1.5") #print("test3.1.5")
if 'container_id' in p: if 'container_id' in p:
try: try:
cont = json.decode(open(f"../containers/{p['container_id']}", 'r').read()) cont = json.loads(open(f"../containers/{p['container_id']}", 'r').read())
if (time.time() - cont['update_ts']) > 43200: if (time.time() - cont['update_ts']) > 43200:
if ("QUERY_STRING" in os.environ) and ("force" in os.environ['QUERY_STRING'].lower()): if ("QUERY_STRING" in os.environ) and ("force" in os.environ['QUERY_STRING'].lower()):
print(f"Location: {cont['link']}\n\n", end = '') print(f"Location: {cont['link']}\n\n", end = '')
@@ -102,7 +103,7 @@ if next_pair_time == None:
new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s") new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s")
random.seed(new_seed) random.seed(new_seed)
surprise_pool = ["Йой!", "От халепа!", "Ой лишенько!"] surprise_pool = ["Йой!", "От халепа!", "Ой лишенько!"]
print(f"Content-Type: text/html; charset=UTF-8\n\n<h2>{random.choice(surprise_pool)}</h2><br><p>Під час спроби отримання посилання на пару {p['name']} сталася непередбачена помилка. Ви можете оновлювати сторінку, поки проблема не зникне (перенаправлення відбудеться, щойно все запрацює), або пошукати посилання де-інде.</p><p>Вибачте за тимчасові незручності(</p>") print(f"Content-Type: text/html; charset=UTF-8\n\n<h2>{random.choice(surprise_pool)}</h2><br><p>Під час спроби отримання посилання на пару {p['name']} сталася непередбачена помилка. Ви можете оновлювати сторінку, поки проблема не зникне (перенаправлення відбудеться, щойно все запрацює), або пошукати посилання де-інде.</p><p>Вибачте за тимчасові незручності(</p><p>(технічна інформація про помилку: {e}</p>")
else: else:
print(f"Location: {p['link'].split()[0]}\n\n", end = '') print(f"Location: {p['link'].split()[0]}\n\n", end = '')
@@ -139,7 +140,7 @@ else:
if 'container_id' in p: if 'container_id' in p:
try: try:
cont = json.decode(open(f"../containers/{p['container_id']}", 'r').read()) cont = json.loads(open(f"../containers/{p['container_id']}", 'r').read())
if (time.time() - cont['update_ts']) > 43200: if (time.time() - cont['update_ts']) > 43200:
if ("QUERY_STRING" in os.environ) and ("force" in os.environ['QUERY_STRING'].lower()): if ("QUERY_STRING" in os.environ) and ("force" in os.environ['QUERY_STRING'].lower()):
print(f"Location: {cont['link']}\n\n", end = '') print(f"Location: {cont['link']}\n\n", end = '')
@@ -157,7 +158,7 @@ else:
new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s") new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s")
random.seed(new_seed) random.seed(new_seed)
surprise_pool = ["Йой!", "От халепа!", "Ой лишенько!"] surprise_pool = ["Йой!", "От халепа!", "Ой лишенько!"]
print(f"Content-Type: text/html; charset=UTF-8\n\n<h2>{random.choice(surprise_pool)}</h2><br><p>Під час спроби отримання посилання на пару {p['name']} сталася непередбачена помилка. Ви можете оновлювати сторінку, поки проблема не зникне (перенаправлення відбудеться, щойно все запрацює), або пошукати посилання де-інде.</p><p>Вибачте за тимчасові незручності(</p>") print(f"Content-Type: text/html; charset=UTF-8\n\n<h2>{random.choice(surprise_pool)}</h2><br><p>Під час спроби отримання посилання на пару {p['name']} сталася непередбачена помилка. Ви можете оновлювати сторінку, поки проблема не зникне (перенаправлення відбудеться, щойно все запрацює), або пошукати посилання де-інде.</p><p>Вибачте за тимчасові незручності(</p><p>(технічна інформація про помилку: {e}</p>")
else: else:
print(f"Location: {p['link'].split()[0]}\n\n", end = '') print(f"Location: {p['link'].split()[0]}\n\n", end = '')
+1 -1
View File
@@ -2,5 +2,5 @@
"trigger_lists": [ "trigger_lists": [
["коли", "тест", "обж"] ["коли", "тест", "обж"]
], ],
"responce_text": "Тести з ОБЖ необхідно проходити лише тим студентам, які не були на практичному занятті. Якщо Ви були на практиці, але все одно пройдете тест, то ризикуєте отримати нижчу оцінку та знизити свій загальний бал" "response_text": "Тести з ОБЖ необхідно проходити лише тим студентам, які не були на практичному занятті. Якщо Ви були на практиці, але все одно пройдете тест, то ризикуєте отримати нижчу оцінку та знизити свій загальний бал"
} }
+34
View File
@@ -0,0 +1,34 @@
command = self.MESSAGE['text'].split(" ", 2)
command_length = len(command)
if (command[0] in self.aliases) and (1 <= command_length <= 3):
try:
import requests
if command_length == 1:
chosen_model = "auto-uk"
else:
chosen_model = command[1]
source, target = chosen_model.split("-")
if command_length == 3:
text_to_translate = command[2]
else:
text_to_translate = self.MESSAGE['reply_to_message']['text']
data = {"q": text_to_translate,
"source": source,
"target": target,
"format": "text"}
res = requests.post("http://127.0.0.1:5000/translate", data = data)
result = json.loads(res.text)
if source == "auto":
self.RESPONSE = f"Результат ({result['detectedLanguage']['language']} - {result['detectedLanguage']['confidence']}%): {result['translatedText']}"
else:
self.RESPONSE = f"Результат: {result['translatedText']}"
except Exception as e:
print(f"[translit-decoder] Got exception: {e}")
+7
View File
@@ -0,0 +1,7 @@
{
"version": 1,
"index_file": "index.py",
"start_on_boot": true,
"alias": "translator",
"predefine": "predefine.py"
}
+1
View File
@@ -0,0 +1 @@
self.aliases = ["!translate", "!t"]
+1 -1
View File
@@ -25,7 +25,7 @@ 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].capitalize(), i[1].capitalize())
decoded_text = decoded_text.replace(i[0].upper(), i[1].upper()) decoded_text = decoded_text.replace(i[0].upper(), i[1].upper())
self.RESPONSE = f"Результат: {decoded_text}" self.RESPONSE = f"__Результат__\n{decoded_text}"
except Exception as e: except Exception as e:
print(f"[translit-decoder] Got exception: {e}") print(f"[translit-decoder] Got exception: {e}")