Compare commits

...

4 Commits

11 changed files with 364 additions and 2 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
config/*
modules/irc-bridge/error.log

View File

@ -0,0 +1,26 @@
[
{
},
{
},
{
},
{
},
{
},
{},
{},
{
},
{
},
{
},
{
},
{
},
{},
{}
]

View File

@ -0,0 +1,127 @@
## env approximation ##
'''
import datetime, json, time
class Self:
def __init__(self):
self.path = ""
self.WEEKDAY_NAMES_ROD = ["понеділка", "вівторка", "середи", "четверга", "п'ятниці", "суботи", "неділі"]
self.WEEKDAY_NAMES_ROD_WITH_NEXT = ["наступного понеділка", "наступного вівторка", "наступної середи", "наступного четверга", "наступної п'ятниці", "наступної суботи", "наступної неділі"]
self.WEEKDAY_NAMES_ROD_WITH_THIS = ["цього понеділка", "цього вівторка", "цієї середи", "цього четверга", "цієї п'ятниці", "цієї суботи", "цієї неділі"]
def readfile(path):
return open(path).read()
self = Self()
'''
## code ##
if self.MESSAGE["text"].lower() == "!пара":
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 pairs)
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()))
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)
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")
if int(dt_pair.strftime("%H")) == 11:
human_readable_date += "об "
else:
human_readable_date += "о "
print("test3.1.3")
human_readable_date += dt_pair.strftime("%H:%M")
print("test3.1.4")
self.RESPONCE = "Актуальна пара: {}\nДата: {}\nВикладач: {}\nПосилання на пару: {}".format(p['name'], human_readable_date, p['teacher'], p['link'])
print("test3.1.5")
else:
self.RESPONCE = "Пар немає взагалі. Ми вільні!"
else:
print("test3.2")
actual_pair_ts = reference_time + next_pair_time
dt_pair = datetime.datetime.fromtimestamp(actual_pair_ts)
print(f"Debug: selected pair at {next_pair_time}")
print(f"{current_day} == 6 && {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 += "сьогодні "
if int(dt_pair.strftime("%H")) == 11:
human_readable_date += "об "
else:
human_readable_date += "о "
human_readable_date += dt_pair.strftime("%H:%M")
self.RESPONCE = "Актуальна пара: {}\nДата: {}\nВикладач: {}\nПосилання на пару: {}".format(p['name'], human_readable_date, p['teacher'], p['link'])

View File

@ -0,0 +1,7 @@
{
"start_on_boot": true,
"alias": "auto-schedule-pro",
"version": 1,
"index_file": "index.py",
"predefine": "predefine.py"
}

View File

@ -0,0 +1,3 @@
self.WEEKDAY_NAMES_ROD_WITH_NEXT = ["наступного понеділка", "наступного вівторка", "наступної середи", "наступного четверга", "наступної п'ятниці", "наступної суботи", "наступної неділі"]
self.WEEKDAY_NAMES_ROD_WITH_THIS = ["цього понеділка", "цього вівторка", "цієї середи", "цього четверга", "цієї п'ятниці", "цієї суботи", "цієї неділі"]
self.current_seconds = 0

View File

@ -0,0 +1,53 @@
[
{
"8:30": {"name": "Дискретна математика", "teacher": "Новотарський М. А.", "link": "https://us02web.zoom.us/j/87578307057?pwd=UGwyVGlwc3M4Q0Q0Q0NLWUt6bmVpUT09"},
"10:25": {"name": "Комп'ютерна логіка", "teacher": "Жабін В. І.", "link": "https://bbb.comsys.kpi.ua/b/val-2vb-o7w-y5y АБО https://bbb.ugrid.org/b/val-2vb-o7w-y5y"},
"12:20": {"name": "Культура мовлення та ділове мовлення", "teacher": "Онуфрієнко О. П.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"}
},
{
"12:20": {"name": "Практичний курс іноземної мови. Частина 1", "teacher": "Шевченко О. М.", "link": "https://meet.google.com/bwg-pdnr-evh"},
"14:15": {"name": "Фізика", "teacher": "Федотов В. В.", "link": "https://us04web.zoom.us/j/77206071753?pwd=8Ui3XaBNmA626wkHwJf3JhB6ecB5N3.1"}
},
{
"8:30": {"name": "Програмування. Частина 2. Об'єктно-орієнтоване програмування", "teacher": "Алещенко О. В.", "link": "https://us02web.zoom.us/j/2711546637?pwd=Ry82RHp3SjV6WTZRMXl6WUNod25hUT09"},
"10:25": {"name": "Вища математика", "teacher": "Ординська З. П.", "link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09"}
},
{
"10:25": {"name": "Вища математика", "teacher": "Ординська З. П.", "link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09"},
"12:20": {"name": "Фізика", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"},
"14:15": {"name": "Програмування. Частина 2. Об'єктно-орієнтоване програмування", "teacher": "Алещенко О. В.", "link": "https://us02web.zoom.us/j/2711546637?pwd=Ry82RHp3SjV6WTZRMXl6WUNod25hUT09"}
},
{
"10:25": {"name": "Фізика", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"},
"12:20": {"name": "Дискретна математика", "teacher": "Пономаренко А. М.", "link": "(Старе посилання!) https://us05web.zoom.us/j/7089075754?pwd=TWRlZmxyVlFiTWU1UGlVVU1XcFE0Zz09"},
"14:15": {"name": "Основи здорового способу життя", "teacher": "Соболенко А. І.", "link": "(Старе посилання!) https://zoom.us/j/2035574145?pwd=bk1wTVhGbjJsQTR4WmVQMlROWFBCZz09"}
},
{},
{},
{
"8:30": {"name": "Дискретна математика", "teacher": "Новотарський М. А.", "link": "https://us02web.zoom.us/j/87578307057?pwd=UGwyVGlwc3M4Q0Q0Q0NLWUt6bmVpUT09"},
"10:25": {"name": "Комп'ютерна логіка", "teacher": "Жабін В. І.", "link": "https://bbb.comsys.kpi.ua/b/val-2vb-o7w-y5y АБО https://bbb.ugrid.org/b/val-2vb-o7w-y5y"},
"12:20": {"name": "Вища математика", "teacher": "Ординська З. П.", "link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09"}
},
{
"8:30": {"name": "Комп'ютерна логіка", "teacher": "Верба О. А.", "link": "(Старе посилання!) https://us04web.zoom.us/j/7382214783?pwd=RnZ3SWgwK1JoVkZtNndnKzdPZjFGdz09"},
"10:25": {"name": "Вища математика", "teacher": "Ординська З. П.", "link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09"},
"12:20": {"name": "Практичний курс іноземної мови. Частина 1", "teacher": "Шевченко О. М.", "link": "https://meet.google.com/bwg-pdnr-evh"},
"14:15": {"name": "Фізика", "teacher": "Федотов В. В.", "link": ""}
},
{
"10:25": {"name": "Вища математика", "teacher": "Ординська З. П.", "link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09"}
},
{
"10:25": {"name": "Вища математика", "teacher": "Ординська З. П.", "link": "https://us05web.zoom.us/j/81227675458?pwd=SWFuQTZLY2w5a2dMMjd0cTdxSUN6dz09"},
"12:20": {"name": "Фізика", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"},
"14:15": {"name": "Програмування. Частина 2. Об'єктно-орієнтоване програмування", "teacher": "Алещенко О. В.", "link": "https://us02web.zoom.us/j/2711546637?pwd=Ry82RHp3SjV6WTZRMXl6WUNod25hUT09"}
},
{
"10:25": {"name": "Фізика", "teacher": "Русаков В. Ф.", "link": "В житті не буває нічого вічного. Життя мінливе, як і посилання на кожну нову пару. Щасти вам його віднайти!"},
"12:20": {"name": "Культура мовлення та ділове мовлення", "teacher": "Кушлаба М. П.", "link": "https://bbb.comsys.kpi.ua/b/myk-0iw-red-p01"},
"14:15": {"name": "Основи здорового способу життя", "teacher": "Соболенко А. І.", "link": "(Старе посилання!) https://zoom.us/j/2035574145?pwd=bk1wTVhGbjJsQTR4WmVQMlROWFBCZz09"}
},
{},
{}
]

View File

@ -1,4 +1,4 @@
if self.MESSAGE["text"].lower() == "!пара":
if self.MESSAGE["text"].lower() == "!пара-old":
try:
schedule = json.loads( readfile(self.path + "schedule.json") )
@ -6,7 +6,7 @@ if self.MESSAGE["text"].lower() == "!пара":
current_week = current_time.isocalendar()[1] % 2
current_day = current_time.weekday()
current_seconds = (current_time.hour + 1) * 3600 + current_time.minute * 60 + current_time.second
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:

122
modules/irc-bridge/bot.py Normal file
View File

@ -0,0 +1,122 @@
import time
import socket
import threading
login_lines_raw = [
"NICK bridge",
"USER bridge bridge * !",
"JOIN #io23-bridge"
]
login_lines = map( lambda x: (x + "\n").encode("utf-8"), login_lines_raw )
recv_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
send_buffer = []
reconnecting = False
LINE_END = "\r\n".encode("utf-8")
recv_s.bind( ("127.0.0.1", 5001) )
def reconnect():
global s, reconnecting
reconnecting = True
while True:
try:
s.close()
except:
pass
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect( ("10.1.1.1", 6667) )
for i in login_lines:
s.send(i)
time.sleep(0.5)
reconnecting = False
break
except Exception as e:
print(f"[reconnect:main] ERROR: got exception {e}")
t = time.time()
open("error.log", "a", encoding = "utf-8").write(f"[{t}] recv_thread:main ERROR: got exception {e}\n")
time.sleep(2)
def recv_thread():
global s, send_buffer, reconnecting
databuffer = bytes()
while True:
try:
new_data = s.recv(1024)
print(f"[DEBUG] new_data: {new_data}")
if len(new_data) == 0:
if not reconnecting:
reconnect() # bin the old socket and get a new one instead
continue
databuffer += new_data
if LINE_END in databuffer:
commands = map( lambda x: x.decode("UTF-8"), databuffer.split(LINE_END)[:-1])
for command in commands:
if len(command) > 0:
if command.split(" ")[0] == "PING":
print("[DEBUG] recv_thread:command:ping: Responding with {}".format(command.split(" ")[1]).encode("UTF-8"))
send_buffer.append(("PONG {}\n".format( command.split(" ")[1]).encode("UTF-8") ))
else:
pass
databuffer = databuffer.split(LINE_END)[-1]
except Exception as e:
print(f"[recv_thread:main] ERROR: got exception {e}")
t = time.time()
open("error.log", "a", encoding = "utf-8").write(f"[{t}] recv_thread:main ERROR: got exception {e}\n")
try:
if not reconnecting:
reconnect()
except Exception as e:
print(f"[recv_thread:except:reconnect] ERROR: got exception {e}")
t = time.time()
open("error.log", "a", encoding = "utf-8").write(f"[{t}] recv_thread:except:reconnect ERROR: got exception {e}\n")
def send_thread():
global s, send_buffer, reconnecting
while True:
if len(send_buffer) > 0:
try:
print(f"[DEBUG] send_thread: sending {send_buffer[0]}")
s.send(send_buffer[0])
del send_buffer[0]
except Exception as e:
print(f"[send_thread:main] ERROR: got exception {e}")
t = time.time()
open("error.log", "a", encoding = "utf-8").write(f"[{t}] send_thread:main ERROR: got exception {e}\n")
if not reconnecting:
reconnect()
time.sleep(0.2)
else:
time.sleep(3)
def msg_thread():
global recv_s, send_buffer
while True:
d = recv_s.recvfrom(16384)
print(f"[DEBUG] msg_thread:d: {d}")
send_buffer.append(d[0])
st = threading.Thread(target = send_thread, args = [])
rt = threading.Thread(target = recv_thread, args = [])
mt = threading.Thread(target = msg_thread, args = [])
reconnect()
st.start()
rt.start()
mt.start()

View File

@ -0,0 +1,10 @@
if self.MESSAGE["chat"]["id"] == -1001570221452:
l = min( len(self.MESSAGE["text"]), 300 )
new_msg = "{} {}: {}".format(self.MESSAGE.from_user.first_name,\
self.MESSAGE.from_user.last_name,\
self.MESSAGE.text.replace("\n", " | ")[:l])
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(f"PRIVMSG #io23-bridge :{new_msg}\n".encode("utf-8"), ("127.0.0.1", 5001))
del s

View File

@ -0,0 +1,7 @@
{
"start_on_boot": true,
"alias": "irc-bridge",
"version": 1,
"index_file": "index.py",
"predefine": "predefine.py"
}

View File

@ -0,0 +1,5 @@
import socket
SEND_ADDR = ( "127.0.0.1", 5001 )
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)