This commit is contained in:
kr0sh512
2024-09-01 00:52:33 +03:00
parent 681c3eee64
commit ee3b23ad59
4 changed files with 211 additions and 141 deletions
+14 -6
View File
@@ -1,12 +1,15 @@
import schedules as bot import schedules as bot
admin_id = '856850518' admin_id = "856850518"
def admin_command(func): def admin_command(func):
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
message = args[0] message = args[0]
if str(message.from_user.id) != admin_id: if str(message.from_user.id) != admin_id:
bot.send_message(message.from_user.id, 'Команда доступна только администратору') bot.send_message(
message.from_user.id, "Команда доступна только администратору"
)
return return
func(*args, **kwargs) func(*args, **kwargs)
@@ -14,15 +17,20 @@ def admin_command(func):
return wrapper return wrapper
def is_admin(message): def is_admin(message):
if str(message.from_user.id) == admin_id and message.from_user.id == message.chat.id: if (
str(message.from_user.id) == admin_id
and message.from_user.id == message.chat.id
):
return True return True
return False return False
def send_admin_message(text): def send_admin_message(text):
bot.send_message(admin_id, '🛑 ' + text) bot.send_message(admin_id, "🛑 " + text)
def send_admin_document(file): def send_admin_document(file):
bot.send_document(admin_id, file, '🛑 Admin file') bot.send_document(admin_id, file, "🛑 Admin file")
+108 -90
View File
@@ -4,23 +4,16 @@ 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_2sem.json" path_schedule = "json/schedule_3sem.json"
path_students = "json/students.json" path_students = "json/students.json"
# path_logs = "json/logs.json"
allow_update = True allow_update = True
# Возможно разбиение добавление логов на 2 функции: Распарсирование message/call
# 2) добавление самого текста в json
# def add_logs(logs): # TODO: реализация добавления логов
# pass
# return
def save_user(infos): def save_user(infos):
for i in range(len(infos)): for i in range(len(infos)):
if type(infos[i]) == type(None): if type(infos[i]) == type(None):
infos[i] = '' infos[i] = ""
infos[i] = str(infos[i]) infos[i] = str(infos[i])
infos = { infos = {
@@ -28,11 +21,11 @@ def save_user(infos):
"first_name": infos[1], "first_name": infos[1],
"last_name": infos[2], "last_name": infos[2],
"username": infos[3], "username": infos[3],
"group" : infos[4] "group": infos[4],
} }
data = {} data = {}
with open(path_users, 'r', encoding='utf-8') as json_file: with open(path_users, "r", encoding="utf-8") as json_file:
data = json.load(json_file) data = json.load(json_file)
data[infos["id"]] = { data[infos["id"]] = {
@@ -42,94 +35,97 @@ def save_user(infos):
"group": infos["group"], "group": infos["group"],
"timeout": "10", "timeout": "10",
"allow_message": "yes", "allow_message": "yes",
"thread": "General" "thread": "General",
} }
with open(path_users, 'w', encoding='utf-8') as json_file: with open(path_users, "w", encoding="utf-8") as json_file:
json.dump(data, json_file, ensure_ascii=False, indent=4) json.dump(data, json_file, ensure_ascii=False, indent=4)
create_schedule_tasks(manual=True)
# bot.send_admin_message("Новый пользователь:\ create_schedule_tasks()
# \n<i>user:</i> @{}\
# \n<i>group:</i> <code>{}</code>\
# \n<i>id:</i> <code>{}</code>\
# \n<i>name:</i> <code>{} {}</code>".format(data[infos["id"]]["username"],
# data[infos["id"]]["group"],
# infos["id"],
# data[infos["id"]]["first_name"],
# data[infos["id"]]["last_name"]))
return return
def change_user_param(id, key, value): def change_user_param(id, key, value):
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:
data = json.load(json_file) data = json.load(json_file)
data[id][key] = value data[id][key] = value
with open(path_users, 'w', encoding='utf-8') as json_file: with open(path_users, "w", encoding="utf-8") as json_file:
json.dump(data, json_file, ensure_ascii=False, indent=4) json.dump(data, json_file, ensure_ascii=False, indent=4)
create_schedule_tasks() create_schedule_tasks()
bot.send_admin_message("Изменения:\ bot.send_admin_message(
"Изменения:\
\n<i>user:</i> @{}\ \n<i>user:</i> @{}\
\n<i>id:</i> <code>{}</code>\ \n<i>id:</i> <code>{}</code>\
\n<i>key:</i> <code>{}</code>\ \n<i>key:</i> <code>{}</code>\
\n<i>value:</i> <code>{}</code>".format(data[id]["username"], id, key, value)) \n<i>value:</i> <code>{}</code>".format(
data[id]["username"], id, key, value
)
)
return return
def parse_lesson(time, lesson): def parse_lesson(time, lesson):
text = '' text = ""
start, end = time.split("-") start, end = time.split("-")
if len(lesson["infos"].split('|')) == 2: if len(lesson["infos"].split("|")) == 2:
teacher = lesson["infos"].split('|')[0] teacher = lesson["infos"].split("|")[0]
room = lesson["infos"].split('|')[1] room = lesson["infos"].split("|")[1]
text = '{}-{} | {}\ text = "{}-{} | {}\
\n<b>{}</b>\ \n<b>{}</b>\
\n<i>{}</i>'.format(start, end, room, lesson["name"], teacher) \n<i>{}</i>".format(
elif len(lesson["infos"].split('|')) == 4: start, end, room, lesson["name"], teacher
infos = lesson["infos"].split('|') )
text = '{}-{}\ elif len(lesson["infos"].split("|")) == 4:
infos = lesson["infos"].split("|")
text = "{}-{}\
\n<b>{}</b>\ \n<b>{}</b>\
\n({}) <i>{}</i>\ \n({}) <i>{}</i>\
\n({}) <i>{}</i>'.format(start, end, lesson["name"], \n({}) <i>{}</i>".format(
infos[1], start, end, lesson["name"], infos[1], infos[0], infos[3], infos[2]
infos[0], )
infos[3], elif len(lesson["infos"].split("|")) == 1:
infos[2]) text = "{}-{}\
elif len(lesson["infos"].split('|')) == 1: \n<b>{}</b>".format(
text = '{}-{}\ start, end, lesson["name"]
\n<b>{}</b>'.format(start, end, lesson["name"]) )
else: else:
print("что-то не так") print("что-то не так")
print(lesson["name"]) print(lesson["name"])
return text return text
def create_schedule_tasks(manual=False): def create_schedule_tasks(manual=False):
global allow_update global allow_update
if not manual: if not manual:
bot.send_admin_message('Произошёл auto-update')
if not allow_update: if not allow_update:
return return
bot.send_admin_message("Произошёл auto-update")
allow_update = True allow_update = True
schedule.clear() schedule.clear()
users = {} users = {}
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: with open(path_schedule, "r", encoding="utf-8") as json_file:
schdl = json.load(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'] timeout = params["timeout"]
for day in schdl[group]: for day in schdl[group]:
for i, lesson in schdl[group][day].items(): for i, lesson in schdl[group][day].items():
if lesson["name"] == "": # Неправильный формат schedule if lesson["name"] == "": # Неправильный формат schedule
@@ -138,46 +134,62 @@ def create_schedule_tasks(manual=False):
start = i.split("-")[0] start = i.split("-")[0]
text = parse_lesson(i, lesson) text = parse_lesson(i, lesson)
if text == '': if text == "":
continue continue
thread_id = params["thread"] thread_id = params["thread"]
delta = '00:' + params["timeout"] delta = "00:" + params["timeout"]
format = '%H:%M' format = "%H:%M"
start_task = datetime.strptime(start, format) - datetime.strptime(delta, format) start_task = datetime.strptime(start, format) - datetime.strptime(
tmp = '' delta, format
for i in str(start_task).split(':'): )
tmp += (('0' + i ) if len(i) < 2 else i) + ":" tmp = ""
for i in str(start_task).split(":"):
tmp += (("0" + i) if len(i) < 2 else i) + ":"
start_task = tmp[:-1] start_task = tmp[:-1]
if day == 'mon': if day == "mon":
schedule.every().monday.at(start_task).do(bot.send_message, id, text, thread_id, True) schedule.every().monday.at(start_task).do(
elif day == 'tue': bot.send_message, id, text, thread_id, True
schedule.every().tuesday.at(start_task).do(bot.send_message, id, text, thread_id, True) )
elif day == 'wed': elif day == "tue":
schedule.every().wednesday.at(start_task).do(bot.send_message, id, text, thread_id, True) schedule.every().tuesday.at(start_task).do(
elif day == 'thu': bot.send_message, id, text, thread_id, True
schedule.every().thursday.at(start_task).do(bot.send_message, id, text, thread_id, True) )
elif day == 'fri': elif day == "wed":
schedule.every().friday.at(start_task).do(bot.send_message, id, text, thread_id, True) schedule.every().wednesday.at(start_task).do(
elif day == 'sat': bot.send_message, id, text, thread_id, True
schedule.every().saturday.at(start_task).do(bot.send_message, id, text, thread_id, True) )
elif day == "thu":
schedule.every().thursday.at(start_task).do(
bot.send_message, id, text, thread_id, True
)
elif day == "fri":
schedule.every().friday.at(start_task).do(
bot.send_message, id, text, thread_id, True
)
elif day == "sat":
schedule.every().saturday.at(start_task).do(
bot.send_message, id, text, thread_id, True
)
return return
def groups_in_json(): def groups_in_json():
schdl = {} schdl = {}
with open(path_schedule, 'r', encoding='utf-8') as json_file: with open(path_schedule, "r", encoding="utf-8") as json_file:
schdl = json.load(json_file) schdl = json.load(json_file)
return schdl.keys() return schdl.keys()
def students_in_group(group): def students_in_group(group):
group = str(group) group = str(group)
data = {} data = {}
with open(path_users, 'r', encoding='utf-8') as json_file: with open(path_users, "r", encoding="utf-8") as json_file:
data = json.load(json_file) data = json.load(json_file)
students = [] students = []
@@ -188,16 +200,17 @@ def students_in_group(group):
return students return students
def students_in_json(id="", key=""): def students_in_json(id="", key=""):
id = str(id) id = str(id)
group = {} group = {}
with open(path_users, 'r', encoding='utf-8') as json_file: with open(path_users, "r", encoding="utf-8") as json_file:
group = json.load(json_file) group = json.load(json_file)
group = group[id]["group"] group = group[id]["group"]
stud = {} stud = {}
with open(path_students, 'r', encoding='utf-8') as json_file: with open(path_students, "r", encoding="utf-8") as json_file:
stud = json.load(json_file) stud = json.load(json_file)
stud = stud.get(group) stud = stud.get(group)
@@ -213,49 +226,54 @@ def students_in_json(id="", key=""):
def return_infos(id): def return_infos(id):
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:
data = json.load(json_file) data = json.load(json_file)
data = data.get(id) data = data.get(id)
return data return data
def pause_bot(): def pause_bot():
global allow_update global allow_update
if allow_update: if allow_update:
schedule.clear() schedule.clear()
allow_update = False allow_update = False
bot.send_admin_message('Бот больше не отправляет расписание') bot.send_admin_message("Бот больше не отправляет расписание")
else: else:
create_schedule_tasks(True) create_schedule_tasks(True)
allow_update = True allow_update = True
bot.send_admin_message('Бот возобновил рассылку!') bot.send_admin_message("Бот возобновил рассылку!")
return return
def get_schedule(id, day): def get_schedule(id, day):
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: 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"]
if (group == 'other'): if group == "other":
return 'У тебя не выбрана группа для рассылки сообщений' return "У тебя не выбрана группа для рассылки сообщений"
try: try:
schdl_today = json.load(schedule_file)[group][day] schdl_today = json.load(schedule_file)[group][day]
except: except:
return 'Расписания твоей группы на {} нет'.format(russian_days[days.index(day)]) return "Расписания твоей группы на {} нет".format(
russian_days[days.index(day)]
)
for i, lesson in schdl_today.items(): for i, lesson in schdl_today.items():
text += '' + parse_lesson(i, lesson) + '\n\n' text += "" + parse_lesson(i, lesson) + "\n\n"
return text return text
+42
View File
@@ -0,0 +1,42 @@
{
"studies.begin": {
"y": 2024,
"m": 9,
"d": 1
},
"studies.end": null,
"schedule": {
"mon": [
{
"partity": 1,
"begin": "10:30",
"end": "12:05",
"name": "Практикум на ЭВМ",
"teacher.room": [
{
"t": "Тюляева В.В.",
"r": "МЗ-3"
}
],
"building": "2-й гуманитарный корпус",
"note": "Какое-то примечание",
"type": "seminar"
},
{
"partity": null,
"begin": "10:30",
"end": "12:05",
"name": "Практикум на ЭВМ",
"teacher.room": [
{
"t": "Тюляева В.В.",
"r": "МЗ-3"
}
],
"building": "2-й гуманитарный корпус",
"note": "Какое-то примечание",
"type": "seminar"
}
]
}
}
+4 -2
View File
@@ -7,7 +7,9 @@ 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") # bot = telebot.TeleBot("TOKEN_API")
bot = telebot.TeleBot("6998513979:AAGgpjgdDsCEqPE0hC8yxrzclsNSd-oRP1s") # test
# bot = telebot.TeleBot("6355753103:AAGniZ7Wf5XyPkn3z753UJvn6afbhOlImjA") # sсhedule
@bot.message_handler(commands=["help", "faq"]) @bot.message_handler(commands=["help", "faq"])
@@ -60,7 +62,7 @@ def test(message):
return return
@bot.message_handler(commands=["restart", 'r']) @bot.message_handler(commands=["restart", "r"])
@admin_command @admin_command
def restart_bot(message): def restart_bot(message):
send_admin_message("bye") send_admin_message("bye")