update json structure

This commit is contained in:
kr0sh512
2024-09-01 01:42:50 +03:00
parent ee3b23ad59
commit 3c0be433ae
6 changed files with 130 additions and 56 deletions
+2 -1
View File
@@ -1,6 +1,7 @@
__pycache__
users.json users.json
schedule.json schedule.json
settings.json
json/students.json json/students.json
json/schedule_2sem.json json/schedule_2sem.json
nohup.out nohup.out
config.yaml
+67 -28
View File
@@ -4,7 +4,8 @@ import schedules as bot
from datetime import datetime from datetime import datetime
path_users = "json/users.json" # Нужный путь до json файлов path_users = "json/users.json" # Нужный путь до json файлов
path_schedule = "json/schedule_3sem.json" # path_schedule = "json/schedule_3sem.json"
path_schedule = "json/groups/{}.json"
path_students = "json/students.json" path_students = "json/students.json"
allow_update = True allow_update = True
@@ -69,7 +70,7 @@ def change_user_param(id, key, value):
return return
def parse_lesson(time, lesson): def parse_lesson_tmp(time, lesson):
text = "" text = ""
start, end = time.split("-") start, end = time.split("-")
@@ -101,6 +102,37 @@ def parse_lesson(time, lesson):
return text return text
def parse_lesson(lesson: dict[str, str]) -> str:
text = ""
start, end = lesson["begin"], lesson["end"]
if not lesson["name"]:
return ""
if len(lesson["teacher.room"]) == 1:
text = "{}-{} | {}\
\n<b>{}</b>\
\n<i>{}</i>".format(
start,
end,
lesson["teacher.room"][0]["r"],
lesson["name"],
lesson["teacher.room"][0]["t"],
)
else:
text = "{}-{}\
\n<b>{}</b>".format(
start,
end,
lesson["name"],
)
for tr in lesson["teacher.room"]:
text += "\n({}) <i>{}</i>".format(tr["r"], tr["t"])
return text
def create_schedule_tasks(manual=False): def create_schedule_tasks(manual=False):
global allow_update global allow_update
@@ -117,24 +149,25 @@ def create_schedule_tasks(manual=False):
schdl = {} schdl = {}
with open(path_users, "r", encoding="utf-8") as json_file: with open(path_users, "r", encoding="utf-8") as json_file:
users = json.load(json_file) users = json.load(json_file)
with open(path_schedule, "r", encoding="utf-8") as json_file:
schdl = json.load(json_file)
for id, params in users.items(): for id, params in users.items():
if params["allow_message"] != "yes": if params["allow_message"] != "yes":
continue continue
group = params["group"] group = params["group"]
if group == "other": if group == "other":
continue continue
timeout = params["timeout"]
for day in schdl[group]: with open(path_schedule.format(group), "r", encoding="utf-8") as json_file:
for i, lesson in schdl[group][day].items(): schdl = json.load(json_file)["schedule"]
if lesson["name"] == "": # Неправильный формат schedule
for day in schdl:
for lesson in schdl[day]:
if not lesson["name"]: # Неправильный формат schedule
continue continue
start = i.split("-")[0] start = lesson["begin"]
text = parse_lesson(i, lesson) text = parse_lesson(lesson)
if text == "": if not text:
continue continue
thread_id = params["thread"] thread_id = params["thread"]
@@ -151,41 +184,41 @@ def create_schedule_tasks(manual=False):
if day == "mon": if day == "mon":
schedule.every().monday.at(start_task).do( schedule.every().monday.at(start_task).do(
bot.send_message, id, text, thread_id, True bot.send_message, id, text, thread_id, lesson["partity"]
) )
elif day == "tue": elif day == "tue":
schedule.every().tuesday.at(start_task).do( schedule.every().tuesday.at(start_task).do(
bot.send_message, id, text, thread_id, True bot.send_message, id, text, thread_id, lesson["partity"]
) )
elif day == "wed": elif day == "wed":
schedule.every().wednesday.at(start_task).do( schedule.every().wednesday.at(start_task).do(
bot.send_message, id, text, thread_id, True bot.send_message, id, text, thread_id, lesson["partity"]
) )
elif day == "thu": elif day == "thu":
schedule.every().thursday.at(start_task).do( schedule.every().thursday.at(start_task).do(
bot.send_message, id, text, thread_id, True bot.send_message, id, text, thread_id, lesson["partity"]
) )
elif day == "fri": elif day == "fri":
schedule.every().friday.at(start_task).do( schedule.every().friday.at(start_task).do(
bot.send_message, id, text, thread_id, True bot.send_message, id, text, thread_id, lesson["partity"]
) )
elif day == "sat": elif day == "sat":
schedule.every().saturday.at(start_task).do( schedule.every().saturday.at(start_task).do(
bot.send_message, id, text, thread_id, True bot.send_message, id, text, thread_id, lesson["partity"]
) )
return return
def groups_in_json(): def groups_in_json() -> list[str]:
schdl = {} schdl = {}
with open(path_schedule, "r", encoding="utf-8") as json_file: with open(path_schedule.format("groups"), "r", encoding="utf-8") as json_file:
schdl = json.load(json_file) schdl = json.load(json_file)
return schdl.keys() return schdl
def students_in_group(group): def students_in_group(group) -> list[str]:
group = str(group) group = str(group)
data = {} data = {}
@@ -201,7 +234,7 @@ def students_in_group(group):
return students return students
def students_in_json(id="", key=""): def students_in_json(id: str, key: str = "") -> list[str] | None:
id = str(id) id = str(id)
group = {} group = {}
@@ -223,7 +256,7 @@ def students_in_json(id="", key=""):
return stud[key] return stud[key]
def return_infos(id): def return_infos(id) -> dict[str, str] | None:
id = str(id) id = str(id)
data = {} data = {}
with open(path_users, "r", encoding="utf-8") as json_file: with open(path_users, "r", encoding="utf-8") as json_file:
@@ -248,17 +281,19 @@ def pause_bot():
return return
def get_schedule(id, day): def get_schedule(id: str, day: str) -> str:
id = str(id) id = str(id)
if day == "sun": if day == "sun":
day = "mon" day = "mon"
days = ["mon", "tue", "wed", "thu", "fri", "sat"] days = ["mon", "tue", "wed", "thu", "fri", "sat"]
russian_days = ["понедельник", "вторник", "среду", "четверг", "пятницу", "субботу"] russian_days = ["понедельник", "вторник", "среду", "четверг", "пятницу", "субботу"]
text = "<u>Расписание на {}</u>:\n\n".format(russian_days[days.index(day)]) text = "<u>Расписание на {}</u>:\n\n".format(russian_days[days.index(day)])
schdl_today = {} schdl_today = {}
with open(path_schedule, "r", encoding="utf-8") as schedule_file:
group = "" group = ""
with open(path_users, "r", encoding="utf-8") as user_file: with open(path_users, "r", encoding="utf-8") as user_file:
group = json.load(user_file)[id]["group"] group = json.load(user_file)[id]["group"]
@@ -267,13 +302,17 @@ def get_schedule(id, day):
return "У тебя не выбрана группа для рассылки сообщений" return "У тебя не выбрана группа для рассылки сообщений"
try: try:
schdl_today = json.load(schedule_file)[group][day] with open(path_schedule.format(group), "r", encoding="utf-8") as schedule_file:
try:
schdl_today = json.load(schedule_file)["schedule"][day]
except: except:
return "Расписания твоей группы на {} нет".format( return "Расписания твоей группы на {} нет".format(
russian_days[days.index(day)] russian_days[days.index(day)]
) )
for i, lesson in schdl_today.items(): for lesson in schdl_today:
text += "" + parse_lesson(i, lesson) + "\n\n" text += "" + parse_lesson(lesson) + "\n\n"
except:
return "Расписания твоей группы нет"
return text return text
+18
View File
@@ -28,6 +28,14 @@
"end": "12:05", "end": "12:05",
"name": "Практикум на ЭВМ", "name": "Практикум на ЭВМ",
"teacher.room": [ "teacher.room": [
{
"t": "Тюляева В.В.",
"r": "МЗ-3"
},
{
"t": "Тюляева В.В.",
"r": "МЗ-3"
},
{ {
"t": "Тюляева В.В.", "t": "Тюляева В.В.",
"r": "МЗ-3" "r": "МЗ-3"
@@ -36,6 +44,16 @@
"building": "2-й гуманитарный корпус", "building": "2-й гуманитарный корпус",
"note": "Какое-то примечание", "note": "Какое-то примечание",
"type": "seminar" "type": "seminar"
},
{
"partity": null,
"begin": "10:30",
"end": "12:05",
"name": "Практикум на ЭВМ",
"teacher.room": [],
"building": "2-й гуманитарный корпус",
"note": "Какое-то примечание",
"type": "seminar"
} }
] ]
} }
+24
View File
@@ -0,0 +1,24 @@
[
"201",
"202",
"203",
"204",
"205",
"206",
"219",
"207",
"208",
"209",
"210",
"211",
"212",
"213",
"214",
"215",
"216",
"217",
"218",
"220",
"241",
"242"
]
-6
View File
@@ -1,6 +0,0 @@
{
"time": {
"func": "",
"params": ""
}
}
+9 -11
View File
@@ -1,5 +1,5 @@
#!/usr/bin/python3.3 #!/usr/bin/python3.3
import threading, telebot, schedule, time, random import threading, telebot, schedule, time, random, yaml
from datetime import datetime from datetime import datetime
import os, sys import os, sys
from telebot import types from telebot import types
@@ -7,9 +7,10 @@ from telegram.constants import ParseMode
import for_json import for_json
from admin import admin_command, is_admin, send_admin_message, send_admin_document from admin import admin_command, is_admin, send_admin_message, send_admin_document
# bot = telebot.TeleBot("TOKEN_API") config = yaml.safe_load(open("config.yaml"))
bot = telebot.TeleBot("6998513979:AAGgpjgdDsCEqPE0hC8yxrzclsNSd-oRP1s") # test bot = telebot.TeleBot(config["test_token"])
# bot = telebot.TeleBot("6355753103:AAGniZ7Wf5XyPkn3z753UJvn6afbhOlImjA") # sсhedule
PARTITY_FIRST = 1
@bot.message_handler(commands=["help", "faq"]) @bot.message_handler(commands=["help", "faq"])
@@ -657,18 +658,15 @@ def text_message(message):
return return
def send_message(id, text, thread_id="General", distribution=False): def send_message(id, text, thread_id="General", partity=None):
if thread_id == "General": if thread_id == "General":
thread_id = None thread_id = None
if distribution: if partity:
count_of_weeks = (datetime.now() - datetime(2024, 2, 5)).days // 7 count_of_weeks = (datetime.now() - datetime(2024, 2, 5)).days // 7
is_odd = (count_of_weeks + 1) % 2 == 1 is_odd = (count_of_weeks + 1) % 2 == PARTITY_FIRST
if is_odd and ("(чёт)" in text): if is_odd != bool(partity):
return
if (not is_odd) and ("(нечёт)" in text):
return return
try: try: