Compare commits

..
8 Commits
22 changed files with 81 additions and 737 deletions
+1
View File
@@ -0,0 +1 @@
masters-schedules/term1/schedule-v2-term1-2026-08-31.json
-26
View File
@@ -1,26 +0,0 @@
[
{
},
{
},
{
},
{
},
{
},
{},
{},
{
},
{
},
{
},
{
},
{
},
{},
{}
]
-186
View File
@@ -1,186 +0,0 @@
## code ##
if (self.MESSAGE["text"].lower() == "!пара-old2" or self.MESSAGE["text"].lower().split()[0] == "!пари-old2"):
#getting current time
current_time = datetime.datetime.now()
current_week = current_time.isocalendar()[1] % 2
current_day = current_time.weekday()
current_seconds = current_week*604800 + current_day*86400 + current_time.hour*3600 + current_time.minute*60 + current_time.second
reference_time = int(current_time.strftime("%s")) - current_seconds
# baking defined schedule
raw_schedule = json.loads( readfile(self.path + "schedule.json") )
schedule = {}
for day in range(len(raw_schedule)):
for i in raw_schedule[day]:
ts = day*86400 + int(i.split(":")[0])*3600 + int(i.split(":")[1])*60
new_item = dict(raw_schedule[day][i])
new_item["source"] = "schedule"
schedule[ts] = new_item
# baking additions (extra lessons)
raw_additions = json.loads( readfile(self.path + "additions.json") )
additions = {}
for day in range(len(raw_additions)):
for i in raw_additions[day]:
ts = day*86400 + int(i.split(":")[0])*3600 + int(i.split(":")[1])*60
new_item = dict(raw_additions[day][i])
new_item["source"] = "additions"
schedule[ts] = new_item
full_schedule = dict(list(schedule.items()) + list(additions.items()))
if self.MESSAGE["text"].lower() == "!пара-old2":
print("test1")
print(f"Full schedule printout: {full_schedule}")
print(f"Current delta_time: {current_seconds}")
p = None
next_lesson_time = None
key_list = list(full_schedule.keys())
key_list.sort()
for i in key_list:
if i > current_seconds - 5400:
p = full_schedule[i]
next_lesson_time = i
break
print("test2")
if next_lesson_time == None:
if len(full_schedule.keys()) > 0:
print("test3.1")
actual_lesson_ts = reference_time + min(full_schedule.keys())
dt_lesson = datetime.datetime.fromtimestamp(actual_lesson_ts)
dt_lesson_finish = datetime.datetime.fromtimestamp(actual_lesson_ts + 5400)
p = full_schedule[min(full_schedule.keys())]
print("test3.1.1")
print("{} == 6 && {} == 1, {}".format(current_day, dt_lesson.strftime('%u'), str( ((current_day + 2) == int(dt_lesson.strftime("%u"))) or ((str(current_day) == "6") and (dt_lesson.strftime("%u") == "1")) )))
human_readable_date = ""
if ((current_day + 2) == int(dt_lesson.strftime("%u"))) or ((str(current_day) == "6") and (dt_lesson.strftime("%u") == "1")):
human_readable_date += "завтра "
elif current_week != int(dt_lesson.strftime("%W")) % 2:
human_readable_date += "{} ".format(self.WEEKDAYS_GENITIVE_NEXT[int(dt_lesson.strftime("%u")) - 1])
elif current_day != (int(dt_lesson.strftime("%u")) - 1):
human_readable_date += "{} ".format(self.WEEKDAYS_GENITIVE_THIS[int(dt_lesson.strftime("%u")) - 1])
else:
human_readable_date += "сьогодні "
print("test3.1.2")
human_readable_date += "з "
print("test3.1.3")
human_readable_date += dt_lesson.strftime("%H:%M")
print("test3.1.4")
human_readable_date += " до "
human_readable_date += dt_lesson_finish.strftime("%H:%M")
self.RESPONSE = "Актуальна пара: {}\nДата: {}\nВикладач: {}\nПосилання на пару: {}".format(p['name'], human_readable_date, p['teacher'], p['link'])
print("test3.1.5")
else:
self.RESPONSE = "Пар немає взагалі. Ми вільні!"
else:
print("test3.2")
actual_lesson_ts = reference_time + next_lesson_time
dt_lesson = datetime.datetime.fromtimestamp(actual_lesson_ts)
dt_lesson_finish = datetime.datetime.fromtimestamp(actual_lesson_ts + 5400)
human_readable_date = ""
if ((current_day + 2) == int(dt_lesson.strftime("%u"))) or ((str(current_day) == "6") and (dt_lesson.strftime("%u") == "1")):
human_readable_date += "завтра "
elif current_week != int(dt_lesson.strftime("%W")) % 2:
human_readable_date += "{} ".format(self.WEEKDAYS_GENITIVE_NEXT[int(dt_lesson.strftime("%u")) - 1])
elif current_day != (int(dt_lesson.strftime("%u")) - 1):
human_readable_date += "{} ".format(self.WEEKDAYS_GENITIVE_THIS[int(dt_lesson.strftime("%u")) - 1])
else:
human_readable_date += "сьогодні "
human_readable_date += "з "
human_readable_date += dt_lesson.strftime("%H:%M")
human_readable_date += " до "
human_readable_date += dt_lesson_finish.strftime("%H:%M")
self.RESPONSE = "Актуальна пара: {}\nДата: {}\nВикладач: {}\nПосилання на пару: {}".format(p['name'], human_readable_date, p['teacher'], p['link'])
if self.MESSAGE["text"].lower().split()[0] == "!пари-old2":
command = self.MESSAGE["text"].lower().split()
preferences = {"name": True, "date": True, "teacher": True, "link": True}
selected_day = current_week*7 + current_day
if len(command) >= 2 and len(command[1]) > 0:
if command[1][0] == "+":
try:
selected_day += int(command[1][1:])
except Exception as e:
print(f"[auto-schedule-pro:error] Got exception '{e}' while parsing {command[1]}")
elif command[1][0] == "-":
try:
selected_day -= int(command[1][1:])
except Exception as e:
print(f"[auto-schedule-pro:error] Got exception '{e}' while parsing {command[1]}")
else:
try:
selected_day = int(command[1])
except Exception as e:
print(f"[auto-schedule-pro:error] Got exception '{e}' while parsing {command[1]}")
# keeping day in bounds
selected_day = selected_day % 14
if len(command) > 2:
for i in command[2:]:
if len(i) >= 2:
if i[1:] in preferences:
if i[0] == "+":
preferences[i[1:]] = True
elif i[0] == "-":
preferences[i[1:]] = False
found_lessons = {}
for i in full_schedule:
if selected_day*86400 <= i < (selected_day+1)*86400:
found_lessons[i] = dict(full_schedule[i])
result_text = f"Пари у {self.WEEKDAYS_ACCUSATIVE[selected_day%7]}:\n\n"
for i in found_lessons:
actual_lesson_ts = reference_time + i
dt_lesson = datetime.datetime.fromtimestamp(actual_lesson_ts)
dt_lesson_finish = datetime.datetime.fromtimestamp(actual_lesson_ts + 5400)
p = found_lessons[i]
human_readable_date = ""
if ((current_day + 2) == int(dt_lesson.strftime("%u"))) or ((str(current_day) == "6") and (dt_lesson.strftime("%u") == "1")):
human_readable_date += "завтра "
elif current_week != int(dt_lesson.strftime("%W")) % 2:
human_readable_date += "{} ".format(self.WEEKDAYS_GENITIVE_NEXT[int(dt_lesson.strftime("%u")) - 1])
elif current_day != (int(dt_lesson.strftime("%u")) - 1):
human_readable_date += "{} ".format(self.WEEKDAYS_GENITIVE_THIS[int(dt_lesson.strftime("%u")) - 1])
else:
human_readable_date += "сьогодні "
human_readable_date += "з "
human_readable_date += dt_lesson.strftime("%H:%M")
human_readable_date += " до "
human_readable_date += dt_lesson_finish.strftime("%H:%M")
if preferences['name']:
result_text += f"Назва: {p['name']}\n"
if preferences['date']:
result_text += f"Дата: {human_readable_date}\n"
if preferences['teacher']:
result_text += f"Викладач: {p['teacher']}\n"
if preferences['link']:
result_text += f"Посилання на пару: {p['link']}\n"
result_text += "\n"
self.RESPONSE = result_text
-7
View File
@@ -1,7 +0,0 @@
{
"start_on_boot": true,
"alias": "auto-schedule-pro",
"version": 1,
"index_file": "index.py",
"predefine": "predefine.py"
}
-6
View File
@@ -1,6 +0,0 @@
# Accusative - znahidnyj
self.WEEKDAYS_ACCUSATIVE = ["понеділок", "вівторок", "середу", "четвер", "п'ятницю", "суботу", "неділю"]
# Genitive - rodovyj
self.WEEKDAYS_GENITIVE_NEXT = ["наступного понеділка", "наступного вівторка", "наступної середи", "наступного четверга", "наступної п'ятниці", "наступної суботи", "наступної неділі"]
self.WEEKDAYS_GENITIVE_THIS = ["цього понеділка", "цього вівторка", "цієї середи", "цього четверга", "цієї п'ятниці", "цієї суботи", "цієї неділі"]
self.current_seconds = 0
-56
View File
@@ -1,56 +0,0 @@
[
{
"8:30": {"name": "Політична наука: конфліктологічний підхід (лекція)", "teacher": "Багінський Андрій Владиславович", "link": "(посилання відсутнє!)"},
"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"},
"14:15": {"name": "Основи електронного урядування (лекція)", "teacher": "Чукут Світлана Анатоліївна", "link": "(посилання відсутнє!)"}
},
{
"12:20": {"name": "Інженерія програмного забезпечення (лабораторна)", "teacher": "Васильєва Марія Давидівна", "link": "https://do.ipo.kpi.ua/mod/bigbluebuttonbn/view.php?id=171039"},
"14:15": {"name": "Теорія електричних кіл та сигналів (лабораторна)", "teacher": "Лободзинський В. Ю. & Ілліна О. О.", "link": "https://meet.google.com/gwx-sshq-sqb"}
},
{
"8:30": {"name": "Теорія ймовірності та математична статистика (лекція)", "teacher": "Марковський Олександр Петрович", "link": "https://bbb.comsys.kpi.ua/b/ole-9ru-7vc"},
"10:25": {"name": "Вступ до операційної системи Linux (лекція)", "teacher": "Роковий Олександр Петрович", "link": "https://bbb.comsys.kpi.ua/b/ole-knq-z9h-pyl"},
"12:20": {"name": "Інженерія програмного забезпечення (лекція)", "teacher": "Васильєва Марія Давидівна", "link": "https://do.ipo.kpi.ua/mod/bigbluebuttonbn/view.php?id=171039"}
},
{
"10:25": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (практика)", "teacher": "Стаматієва Вікторія В'ячеславівна", "link": "https://us04web.zoom.us/j/2313886209?pwd=dnZHanV3cU9LUXJBVWYyYVArUFg5dz09"},
"12:20": {"name": "Практичний курс іноземної мови. Частина 2 (практика)", "teacher": "Шевченко Ольга Миколаївна", "link": "https://meet.google.com/tno-cxef-zyi"},
"14:15": {"name": "Соціальна психологія (практика)", "teacher": "Блохіна Ірина Олександрівна", "link": "(посилання відсутнє!)"},
"16:10": {"name": "Основи електронного урядування (практика)", "teacher": "Чукут Світлана Анатоліївна", "link": "(посилання відсутнє!)"}
},
{
"8:30": {"name": "Вступ до філософії (лекція)", "teacher": "Руденко Тамара Петрівна", "link": "https://zoom.us/j/9358038101?pwd=d0pwUHRDY0dxbngrU09PYll6UXpNZz09"},
"10:25": {"name": "Теорія електричних кіл та сигналів (лекція)", "teacher": "Лободзинський Вадим Юрійович", "link": "https://meet.google.com/gwx-sshq-sqb"},
"12:20": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (лекція)", "teacher": "Овчар Раїса Федорівна", "link": "https://us02web.zoom.us/j/84532519615?pwd=eDFRMWtJTkxKcklpa1JUSjFmZHNyUT09"}
},
{},
{},
{
"10:25": {"name": "Психологія (практика) & Психологія конфлікту (лекція)", "teacher": "Сербова О. В. & Кононець М. О.", "link": "https://us05web.zoom.us/j/9299459744?pwd=Z3VQdWEvQ0tyc3pMbzl2bHN6Y1VlUT09 & https://zoom.us/j/9953120638?pwd=WGZsYUhPK2hxbUc4YVJmT0lhdysyZz09"},
"12:20": {"name": "Політична наука: конфліктологічний підхід & Захист персональних даних: стандарти ЄС та Ради Європи (практики)", "teacher": "Северинчик О. П. & Самчинська О. А.", "link": "(посилання відсутнє!) & https://us04web.zoom.us/j/72149205587?pwd=Ld2Xj7RORYEwnUYauB5yEbATwwsNan.1"},
"14:15": {"name": "Розумні міста (лекція)", "teacher": "Чукут Світлана Анатоліївна", "link": "https://zoom.us/j/5439919039?pwd=Um8wWHV4ZjZpallCWkpVQ08wZGNzdz09"}
},
{
"10:25": {"name": "Вступ до філософії (практика)", "teacher": "Руденко Тамара Петрівна", "link": "https://zoom.us/j/9358038101?pwd=d0pwUHRDY0dxbngrU09PYll6UXpNZz09"},
"14:15": {"name": "Теорія ймовірності та математична статистика (практика)", "teacher": "Марковський Олександр Петрович", "link": "https://bbb.comsys.kpi.ua/b/ole-9ru-7vc"}
},
{
"8:30": {"name": "Теорія ймовірності та математична статистика (лекція)", "teacher": "Марковський Олександр Петрович", "link": "https://bbb.comsys.kpi.ua/b/ole-9ru-7vc"},
"10:25": {"name": "Вступ до операційної системи Linux (лекція)", "teacher": "Роковий Олександр Петрович", "link": "https://bbb.comsys.kpi.ua/b/ole-knq-z9h-pyl"},
"12:20": {"name": "Інженерія програмного забезпечення (лекція)", "teacher": "Васильєва Марія Давидівна", "link": "https://do.ipo.kpi.ua/mod/bigbluebuttonbn/view.php?id=171039"},
"14:15": {"name": "Інженерія програмного забезпечення (лекція)", "teacher": "Васильєва Марія Давидівна", "link": "https://do.ipo.kpi.ua/mod/bigbluebuttonbn/view.php?id=171039"}
},
{
"8:30": {"name": "Вступ до операційної системи Linux (лабораторна)", "teacher": "Алєнін Олег Ігорович", "link": "https://us04web.zoom.us/j/4122071690?pwd=bANFi3fk9pWvRu9TSBRGzfxFHuEkZC.1"},
"10:25": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (практика)", "teacher": "Стаматієва Вікторія В'ячеславівна", "link": "https://us04web.zoom.us/j/2313886209?pwd=dnZHanV3cU9LUXJBVWYyYVArUFg5dz09"},
"12:20": {"name": "Практичний курс іноземної мови. Частина 2 (практика)", "teacher": "Шевченко Ольга Миколаївна", "link": "https://meet.google.com/tno-cxef-zyi"},
"14:15": {"name": "Соціальна психологія (лекція) & Розумні міста (практика)", "teacher": "Винославська О. В. & Чукут С. А.", "link": "(посилання відсутнє!) & https://zoom.us/j/5439919039?pwd=Um8wWHV4ZjZpallCWkpVQ08wZGNzdz09"}
},
{
"10:25": {"name": "Теорія електричних кіл та сигналів (лекція)", "teacher": "Лободзинський Вадим Юрійович", "link": "https://meet.google.com/gwx-sshq-sqb"},
"12:20": {"name": "Вища математика. Частина 3. Ряди. Теорія функцій комплексної змінної. Операційне числення (лекція)", "teacher": "Овчар Раїса Федорівна", "link": "https://us02web.zoom.us/j/84532519615?pwd=eDFRMWtJTkxKcklpa1JUSjFmZHNyUT09"}
},
{},
{}
]
-166
View File
@@ -1,166 +0,0 @@
import datetime
import json
import time
import os
current_time = datetime.datetime.now()
current_week = current_time.isocalendar()[1] % 2
current_day = current_time.weekday()
current_seconds = current_week*604800 + current_day*86400 + current_time.hour*3600 + current_time.minute*60 + current_time.second
reference_time = int(current_time.strftime("%s")) - current_seconds
# baking defined schedule
raw_schedule = json.loads( open("../schedule.json").read() )
schedule = {}
for day in range(len(raw_schedule)):
for i in raw_schedule[day]:
ts = day*86400 + int(i.split(":")[0])*3600 + int(i.split(":")[1])*60
new_item = dict(raw_schedule[day][i])
new_item["source"] = "schedule"
schedule[ts] = new_item
# baking additions (extra pairs)
raw_additions = json.loads( open("../additions.json").read() )
additions = {}
for day in range(len(raw_additions)):
for i in raw_additions[day]:
ts = day*86400 + int(i.split(":")[0])*3600 + int(i.split(":")[1])*60
new_item = dict(raw_additions[day][i])
new_item["source"] = "additions"
schedule[ts] = new_item
full_schedule = dict(list(schedule.items()) + list(additions.items()))
#print("test1")
#print(f"Full schedule #printout: {full_schedule}")
#print(f"Current delta_time: {current_seconds}")
p = None
next_pair_time = None
key_list = list(full_schedule.keys())
key_list.sort()
for i in key_list:
if i > current_seconds - 5400:
p = full_schedule[i]
next_pair_time = i
break
#print("test2")
if next_pair_time == None:
if len(full_schedule.keys()) > 0:
#print("test3.1")
#actual_pair_ts = reference_time + min(full_schedule.keys())
#dt_pair = datetime.datetime.fromtimestamp(actual_pair_ts)
#dt_pair_finish = datetime.datetime.fromtimestamp(actual_pair_ts + 5400)
p = full_schedule[min(full_schedule.keys())]
#print("test3.1.1")
#print("{} == 6 && {} == 1, {}".format(current_day, dt_pair.strftime('%u'), str( ((current_day + 2) == int(dt_pair.strftime("%u"))) or ((str(current_day) == "6") and (dt_pair.strftime("%u") == "1")) )))
'''
human_readable_date = ""
if ((current_day + 2) == int(dt_pair.strftime("%u"))) or ((str(current_day) == "6") and (dt_pair.strftime("%u") == "1")):
human_readable_date += "завтра "
elif current_week != int(dt_pair.strftime("%W")) % 2:
human_readable_date += "{} ".format(self.WEEKDAY_NAMES_ROD_WITH_NEXT[int(dt_pair.strftime("%u")) - 1])
elif current_day != (int(dt_pair.strftime("%u")) - 1):
human_readable_date += "{} ".format(self.WEEKDAY_NAMES_ROD_WITH_THIS[int(dt_pair.strftime("%u")) - 1])
else:
human_readable_date += "сьогодні "
#print("test3.1.2")
human_readable_date += "з "
#print("test3.1.3")
human_readable_date += dt_pair.strftime("%H:%M")
#print("test3.1.4")
human_readable_date += " до "
human_readable_date += dt_pair_finish.strftime("%H:%M")
'''
#self.RESPONCE = "Актуальна пара: {}\nДата: {}\nВикладач: {}\nПосилання на пару: {}".format(p['name'], human_readable_date, p['teacher'], p['link'])
#print("test3.1.5")
if 'container_id' in p:
try:
cont = json.loads(open(f"../containers/{p['container_id']}", 'r').read())
if (time.time() - cont['update_ts']) > 43200:
if ("QUERY_STRING" in os.environ) and ("force" in os.environ['QUERY_STRING'].lower()):
print(f"Location: {cont['link']}\n\n", end = '')
else:
import random
new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s")
random.seed(new_seed)
surprise_pool = ["Йой!", "От халепа!", "Ой лишенько!"]
print(f"Content-Type: text/html; charset=UTF-8\n\n<h2>{random.choice(surprise_pool)}</h2><br><p>Посилання на пару {p['name']}, яке зберігається у сховищі, було отримане більш ніж 12 годин тому (рівно {time.time() - cont['update_ts']} секунд тому), тому, скоріш за все, не є дійсним.</p><p>На жаль, нового посилання ще не надходило, тому Ви можете або чекати на нього і оновлювати цю сторінку (перенаправлення станеться, щойно з'явиться нове посилання), або перейти вручну за старим посиланням (не рекомендується):</p><a href=\"{cont['link']}\">{cont['link']}</a><br><p>PS: щоб обійти цю сторінку та завжди автоматично переходити за будь-яким наявним посиланням, можна додати у рядок URL в кінці напис: ?force</p>")
else:
print(f"Location: {cont['link']}\n\n", end = '')
except Exception as e:
import random
new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s")
random.seed(new_seed)
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><p>(технічна інформація про помилку: {e}</p>")
else:
print(f"Location: {p['link'].split()[0]}\n\n", end = '')
else:
#self.RESPONCE = "Пар немає взагалі. Ми вільні!"
pass
else:
#print("test3.2")
'''
actual_pair_ts = reference_time + next_pair_time
dt_pair = datetime.datetime.fromtimestamp(actual_pair_ts)
dt_pair_finish = datetime.datetime.fromtimestamp(actual_pair_ts + 5400)
human_readable_date = ""
if ((current_day + 2) == int(dt_pair.strftime("%u"))) or ((str(current_day) == "6") and (dt_pair.strftime("%u") == "1")):
human_readable_date += "завтра "
elif current_week != int(dt_pair.strftime("%W")) % 2:
human_readable_date += "{} ".format(self.WEEKDAY_NAMES_ROD_WITH_NEXT[int(dt_pair.strftime("%u")) - 1])
elif current_day != (int(dt_pair.strftime("%u")) - 1):
human_readable_date += "{} ".format(self.WEEKDAY_NAMES_ROD_WITH_THIS[int(dt_pair.strftime("%u")) - 1])
else:
human_readable_date += "сьогодні "
human_readable_date += "з "
human_readable_date += dt_pair.strftime("%H:%M")
human_readable_date += " до "
human_readable_date += dt_pair_finish.strftime("%H:%M")
'''
#self.RESPONCE = "Актуальна пара: {}\nДата: {}\nВикладач: {}\nПосилання на пару: {}".format(p['name'], human_readable_date, p['teacher'], p['link'])
if 'container_id' in p:
try:
cont = json.loads(open(f"../containers/{p['container_id']}", 'r').read())
if (time.time() - cont['update_ts']) > 43200:
if ("QUERY_STRING" in os.environ) and ("force" in os.environ['QUERY_STRING'].lower()):
print(f"Location: {cont['link']}\n\n", end = '')
else:
import random
new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s")
random.seed(new_seed)
surprise_pool = ["Йой!", "От халепа!", "Ой лишенько!"]
print(f"Content-Type: text/html; charset=UTF-8\n\n<h2>{random.choice(surprise_pool)}</h2><br><p>Посилання на пару {p['name']}, яке зберігається у сховищі, було отримане більш ніж 12 годин тому (рівно {time.time() - cont['update_ts']} секунд тому), тому, скоріш за все, не є дійсним.</p><p>На жаль, нового посилання ще не надходило, тому Ви можете або чекати на нього і оновлювати цю сторінку (перенаправлення станеться, щойно з'явиться нове посилання), або перейти вручну за старим посиланням (не рекомендується):</p><a href=\"{cont['link']}\">{cont['link']}</a><br><p>PS: щоб обійти цю сторінку та завжди автоматично переходити за будь-яким наявним посиланням, можна додати у рядок URL в кінці напис: ?force</p>")
else:
print(f"Location: {cont['link']}\n\n", end = '')
except Exception as e:
import random
new_seed = os.environ['REMOTE_ADDR'] + datetime.datetime.now().replace(minute = 0, second = 0).strftime("%s")
random.seed(new_seed)
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><p>(технічна інформація про помилку: {e}</p>")
else:
print(f"Location: {p['link'].split()[0]}\n\n", end = '')
#print(f"Location: {p['link'].split()[0]}\n\n")
-45
View File
@@ -1,45 +0,0 @@
if self.MESSAGE["text"].lower() == "!пара-old":
try:
schedule = json.loads( readfile(self.path + "schedule.json") )
current_time = datetime.datetime.now()
current_week = current_time.isocalendar()[1] % 2
current_day = current_time.weekday()
current_seconds = current_time.hour * 3600 + current_time.minute * 60 + current_time.second
print(f"[DEBUG] Current day is {type(current_day)}({current_day})")
if current_day > 4 or current_day < 0:
next_week = int(not bool(current_week))
day = -1
next_pair = None
pair_found = False
for i in schedule[next_week]:
if not pair_found:
day += 1
for j in schedule[next_week][day]:
next_pair = schedule[next_week][day][j]
pair_found = True
break
self.RESPONSE = f"Сьогодні вихідний, тому пар немає)\n"\
f"Наступна пара - {next_pair['subject']} ({next_pair['lector']}) о {self.reverse_timetable[int(j)]} у {self.days_rod[day]}\n"\
f"Посилання (якщо воно чомусь треба): {next_pair['link']}"
else:
for i in self.timetable:
if current_seconds < i:
print("[DEBUG] Looking up a relevant pair...")
try:
relevant_pair = schedule[current_week][current_day][str(self.timetable[i])]
self.RESPONSE = f"Актуальна пара: {relevant_pair['subject']} ({relevant_pair['lector']}), початок о {self.reverse_timetable[self.timetable[i]]}\n"\
f"Посилання: {relevant_pair['link']}"
break
except Exception as e:
print(f"[WARN] module: auto-schedule: exception {e} while looking up the pair")
else:
self.RESPONSE = "Сьогодні більше немає пар"
except Exception as e:
print(f"[WARN] module: auto-schedule: failed to process schedule.json ({e})")
-7
View File
@@ -1,7 +0,0 @@
{
"start_on_boot": true,
"alias": "auto-schedule",
"version": 1,
"index_file": "index.py",
"predefine": "predefine.py"
}
-4
View File
@@ -1,4 +0,0 @@
self.timetable = {36300: 0, 43200: 1, 50100: 2, 57000: 3, 63900: 4, 72300: 5, 78900: 6}
self.days_rod = ["понеділок", "вівторок", "середу", "четвер", "п'ятницю"]
self.reverse_timetable = ["8:30", "10:25", "12:20", "14:15", "16:10", "18:30", "20:20"]
-160
View File
@@ -1,160 +0,0 @@
[
[
{
"0": {
"link": "https://bbb.comsys.kpi.ua/b/ana-gca-2xm",
"subject": "Структури даних та алгоритми",
"lector": "Сергієнко А. М."
},
"1": {
"link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09",
"subject": "Вища математика",
"lector": "Ординська З. П."
},
"2": {
"link": "https://us02web.zoom.us/j/4387354937?pwd=R3R3NkpWU09GY3kvanZBeEcrQWZoUT09",
"subject": "Основи здорового способу життя",
"lector": "Хіміч І. Ю."
},
"3": {
"link": "https://us02web.zoom.us/j/5060383482?pwd=Qk9HZGtIdVdFVHNFd0ZCY1lJbitvdz09",
"subject": "Програмування",
"lector": "Новотарський М. А."
}
},
{
"1": {
"link": "https://meet.google.com/fyi-bwkm-qyf",
"subject": "Історія науки й техніки",
"lector": "Шевчук Т. В."
}
},
{
"0": {
"link": "https://meet.google.com/idu-adtd-rvr?authuser=0",
"subject": " Історія науки й техніки",
"lector": "Костилєва С. О."
},
"1": {
"link": "https://us02web.zoom.us/j/4911162386?pwd=OU43Q0thZEk1bFhvcFBRUm13VXlZZz09",
"subject": "Аналітична геометрія та лінійна алгебра",
"lector": "Ванєєва О. О."
},
"2": {
"link": "https://us02web.zoom.us/j/5060383482?pwd=Qk9HZGtIdVdFVHNFd0ZCY1lJbitvdz09",
"subject": "Програмування",
"lector": "Новотарський М. А."
},
"3": {
"link": "https://bbb.ugrid.org/b/val-zdp-vw0-dbr",
"subject": "Комп'ютерна логіка",
"lector": "Жабін В. І."
}
},
{
"1": {
"link": "https://meet.google.com/bwg-pdnr-evh",
"subject": "Практичний курс іноземної мови",
"lector": "Шевченко О. М."
},
"2": {
"link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09",
"subject": "Вища математика",
"lector": "Ординська З. П."
},
"3": {
"link": "https://us05web.zoom.us/j/7089075754?pwd=TWRlZmxyVlFiTWU1UGlVVU1XcFE0Zz09",
"subject": "Програмування",
"lector": "Пономаренко"
},
"4": {
"link": "https://us05web.zoom.us/j/7089075754?pwd=TWRlZmxyVlFiTWU1UGlVVU1XcFE0Zz09",
"subject": "Програмування",
"lector": "Пономаренко"
}
},
{
"1": {
"link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09",
"subject": "Вища математика",
"lector": "Ординська З. П."
},
"2": {
"link": "https://us04web.zoom.us/j/7382214783?pwd=RnZ3SWgwK1JoVkZtNndnKzdPZjFGdz09",
"subject": "Комп'ютерна логіка",
"lector": "Верба О. А."
}
}
],
[
{
"0": {
"link": "https://bbb.comsys.kpi.ua/b/ana-gca-2xm",
"subject": "Структури даних та алгоритми",
"lector": "Сергієнко А. М."
},
"1": {
"link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09",
"subject": "Вища математика",
"lector": "Ординська З. П."
},
"2": {
"link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09",
"subject": "Вища математика",
"lector": "Ординська З. П."
},
"3": {
"link": "https://us02web.zoom.us/j/5060383482?pwd=Qk9HZGtIdVdFVHNFd0ZCY1lJbitvdz09",
"subject": "Програмування",
"lector": "Новотарський М. А."
}
},
{},
{
"1": {
"link": "https://us02web.zoom.us/j/4911162386?pwd=OU43Q0thZEk1bFhvcFBRUm13VXlZZz09",
"subject": "Аналітична геометрія та лінійна алгебра",
"lector": "Ванєєва О. О."
},
"2": {
"link": "https://us02web.zoom.us/j/5060383482?pwd=Qk9HZGtIdVdFVHNFd0ZCY1lJbitvdz09",
"subject": "Програмування",
"lector": "Новотарський М. А."
},
"3": {
"link": "https://bbb.ugrid.org/b/val-zdp-vw0-dbr",
"subject": "Комп'ютерна логіка",
"lector": "Жабін В. І."
}
},
{
"1": {
"link": "https://meet.google.com/bwg-pdnr-evh",
"subject": "Практичний курс іноземної мови",
"lector": "Шевченко О. М."
},
"2": {
"link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09",
"subject": "Вища математика",
"lector": "Ординська З. П."
},
"3": {
"link": "https://us02web.zoom.us/j/4911162386?pwd=OU43Q0thZEk1bFhvcFBRUm13VXlZZz09",
"subject": "Аналітична геометрія та лінійна алгебра",
"lector": "Ванєєва О. О."
}
},
{
"0": {
"link": "https://zoom.us/j/2035574145?pwd=bk1wTVhGbjJsQTR4WmVQMlROWFBCZz09",
"subject": " Основи здорового способу життя",
"lector": "Соболенко А. І."
},
"1": {
"link": "https://us02web.zoom.us/j/88932218187?pwd=MUpFNjE3bHAxeEZ0NDE3NU0vYUUxZz09",
"subject": "Структури даних та алгоритми",
"lector": "Молчанова А. А."
}
}
]
]
+1 -5
View File
@@ -3,11 +3,7 @@
"ss": "Головна сторінка сервера: http://10.1.1.1:12010/",
"u": "Універсальне посилання: http://10.1.1.1:12025/?d=1",
"c": "Розклад навчального року: http://kpi.ua/year",
"r": "Записи пар (8 семестр): http://10.1.1.1:12076/cgi/main-full.py",
"d": "Навчальні дисципліни (5-8 семестри): http://10.1.1.1:12022/generic/disciplines-terms5-8.png",
"d1": "Навчальні дисципліни (1-4 семестри): http://10.1.1.1:12022/generic/disciplines-terms1-4.png",
"d2": "Навчальні дисципліни (5-8 семестри): http://10.1.1.1:12022/generic/disciplines-terms5-8.png",
"h": "Стисла довідка:\n!s - головна сторінка сервера\n!u - універсальне посилання\n!r - записи пар (7 семестр)\n!c - календар навчального року\n!d - перелік навчальних дисциплін\n@all [повідомлення] - тег усіх користувачів\nПовна довідка: http://10.1.1.1:12032/generic/bot-help/short-help.html",
"h": "Стисла довідка:\n!s - головна сторінка сервера\n!u - універсальне посилання\n!c - календар навчального року",
"пари_для_артема": "🧐",
"пари_для_артема_хоч_і_не_на_завтра": "🤨",
"перекур": "😮\u200d💨",
+1 -1
View File
@@ -1,5 +1,5 @@
{
"start_on_boot": true,
"start_on_boot": false,
"alias": "help",
"version": 2,
"index_file": "index.py"
+71
View File
@@ -0,0 +1,71 @@
import os
import json
import datetime
def readfile(path):
if os.path.exists(module_path + path):
return open(module_path + path).read()
else:
return ''
def load_from(path):
data = readfile(path)
if data:
return json.loads(data)
else:
return {}
def writefile(path, data):
open(module_path + path, "w").write(data)
def update_db(path, db_data):
writefile(path, json.dumps(db_data))
def append_file(path, data):
open(module_path + path, "a").write(data)
def log(data):
print(f"[mass-tagger-v2 {datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}]: {data}")
append_file("db/update_log.txt", f"{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}: {data}\n")
module_path = ""
def process(msg, path):
global module_path
module_path = path
current_db = load_from("db/all.json")
chat_id = str(msg.chat.id)
user_id = str(msg.from_user.id)
user_name = str(msg.from_user.username)
if ("@all" in msg.text) and (chat_id in current_db):
tags_from_db = set(current_db[chat_id].values())
real_tags = [f"@{i}" for i in tags_from_db if i != "None"]
return f"Користувач {msg.from_user.username} використав масовий" \
f" тег з повідомленням:\n{msg.text}\n\n" \
f"{' '.join(real_tags)}", ""
if chat_id not in current_db:
log(f"Added chat {chat_id}")
current_db[chat_id] = dict()
update_db("db/all.json", current_db)
if (user_id not in current_db[chat_id]) or (current_db[chat_id][user_id] != user_name):
if (user_id in current_db[chat_id]):
log(f"Updated record for {user_id} in {chat_id}: @{current_db[chat_id][user_id]} -> @{user_name}")
else:
log(f"Updated record for {user_id} in {chat_id}: <none> -> @{user_name}")
current_db[chat_id][user_id] = user_name
update_db("db/all.json", current_db)
return "", ""
+7
View File
@@ -0,0 +1,7 @@
{
"version": 2,
"index_file": "index.py",
"predefine": "predefine.py",
"start_on_boot": true,
"alias": "mass-tagger-v2"
}
-13
View File
@@ -1,13 +0,0 @@
if "%" in self.MESSAGE["text"]:
tagging_issued = False
tags_used = set()
tagged_users = set()
for i in self.tag_sets:
if i in self.MESSAGE["text"]:
tagging_issued = True
tags_used.add(i)
tagged_users |= self.tag_sets[i]
if tagging_issued:
self.RESPONSE = f"Користувач використав масовий тег з повідомленням: {self.MESSAGE['text']}\n\n" \
f"{' '.join(tagged_users)}"
-7
View File
@@ -1,7 +0,0 @@
{
"version": 1,
"index_file": "index.py",
"predefine": "predefine.py",
"start_on_boot": false,
"alias": "mass-tagger"
}
-6
View File
@@ -1,6 +0,0 @@
{
"trigger_lists": [
["коли", "тест", "обж"]
],
"response_text": "Тести з ОБЖ необхідно проходити лише тим студентам, які не були на практичному занятті. Якщо Ви були на практиці, але все одно пройдете тест, то ризикуєте отримати нижчу оцінку та знизити свій загальний бал"
}
-34
View File
@@ -1,34 +0,0 @@
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://10.1.1.1:5010/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
@@ -1,7 +0,0 @@
{
"version": 1,
"index_file": "index.py",
"start_on_boot": false,
"alias": "translator",
"predefine": "predefine.py"
}
-1
View File
@@ -1 +0,0 @@
self.aliases = ["!translate", "!t"]