diff --git a/for_json.py b/for_json.py
index a917c4e..dadfa7c 100644
--- a/for_json.py
+++ b/for_json.py
@@ -6,6 +6,8 @@ from datetime import datetime
path_users = "json/users.json" # Нужный путь до json файлов
path_schedule = "json/schedule.json"
+allow_update = True
+
def save_user(infos):
for i in range(len(infos)):
if type(infos[i]) == type(None):
@@ -52,7 +54,44 @@ def change_user_param(id, key, value):
create_schedule_tasks()
return
-def create_schedule_tasks():
+def parse_lesson(time, lesson):
+ text = ''
+ start, end = time.split("-")
+
+ if len(lesson["infos"].split('|')) == 2:
+ teacher = lesson["infos"].split('|')[0]
+ room = lesson["infos"].split('|')[1]
+ text = '{}-{} | {}\
+ \n{}\
+ \n{}'.format(start, end, room, lesson["name"], teacher)
+ elif len(lesson["infos"].split('|')) == 4:
+ infos = lesson["infos"].split('|')
+ text = '{}-{}\
+ \n{}\
+ \n({}) {}\
+ \n({}) {}'.format(start, end, lesson["name"],
+ infos[1],
+ infos[0],
+ infos[3],
+ infos[2])
+ elif len(lesson["infos"].split('|')) == 1:
+ text = '{}-{}\
+ \n{}'.format(start, end, lesson["name"])
+ else:
+ print("что-то не так")
+ print(lesson["name"])
+
+ return text
+
+def create_schedule_tasks(manual=False):
+ global allow_update
+ if not manual:
+ bot.send_admin_message('Произошёл auto-update')
+ if not allow_update:
+ return
+
+ allow_update = True
+
schedule.clear()
users = {}
schdl = {}
@@ -72,33 +111,14 @@ def create_schedule_tasks():
if lesson["name"] == "": # Неправильный формат schedule
continue
- start, end = i.split("-")
- text = ''
- if len(lesson["infos"].split('|')) == 2:
- teacher = lesson["infos"].split('|')[0]
- room = lesson["infos"].split('|')[1]
- text = '{}-{} | {}\
- \n{}\
- \n{}'.format(start, end, room, lesson["name"], teacher)
- elif len(lesson["infos"].split('|')) == 4:
- infos = lesson["infos"].split('|')
- text = '{}-{}\
- \n{}\
- \n({}) {}\
- \n({}) {}'.format(start, end, lesson["name"],
- infos[1],
- infos[0],
- infos[3],
- infos[2])
- elif len(lesson["infos"].split('|')) == 1:
- text = '{}-{}\
- \n{}'.format(start, end, lesson["name"])
- else: #неправильный формат infos в json файле
- print("что-то не так")
- print(lesson["name"])
+ start = i.split("-")[0]
+ text = parse_lesson(i, lesson)
+
+ if text == '':
continue
thread_id = params["thread"]
+
delta = '00:' + params["timeout"]
format = '%H:%M'
start_task = datetime.strptime(start, format) - datetime.strptime(delta, format)
@@ -106,6 +126,7 @@ def create_schedule_tasks():
for i in str(start_task).split(':'):
tmp += (('0' + i ) if len(i) < 2 else i) + ":"
start_task = tmp[:-1]
+
if day == 'mon':
schedule.every().monday.at(start_task).do(bot.send_message, id, text, thread_id)
elif day == 'tue':
@@ -121,13 +142,12 @@ def create_schedule_tasks():
return
-
-def check_group_in_json(number):
+def groups_in_json():
schdl = {}
with open(path_schedule, 'r', encoding='utf-8') as json_file:
- schdl = json.load(json_file)
+ schdl = json.load(json_file)
- return str(number) in schdl.keys()
+ return schdl.keys()
def return_infos(id):
id = str(id)
@@ -140,17 +160,20 @@ def return_infos(id):
def pause_bot():
schedule.clear()
+ global allow_update
+ allow_update = False
return
-def get_schedule(id):
+def get_schedule(id, day):
id = str(id)
- text = 'Расписание на сегодня:\n\n'
+ days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat']
+ russian_days = ['понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу']
+
+ text = 'Расписание на {}:\n\n'.format(russian_days[days.index(day)])
schdl_today = {}
with open(path_schedule, 'r', encoding='utf-8') as schedule_file:
- day = datetime.today().strftime('%A').lower()[:3]
-
group = ''
with open(path_users, 'r', encoding='utf-8') as user_file:
group = json.load(user_file)[id]['group']
@@ -161,30 +184,9 @@ def get_schedule(id):
try:
schdl_today = json.load(schedule_file)[group][day]
except:
- return 'Расписания твоей группы на сегодня нет'
+ return 'Расписания твоей группы на {} нет'.format(russian_days[days.index(day)])
for i, lesson in schdl_today.items():
- if len(lesson["infos"].split('|')) == 2:
- teacher = lesson["infos"].split('|')[0]
- room = lesson["infos"].split('|')[1]
- text += '•{} | {}\
- \n{}\
- \n{}'.format(i, room, lesson["name"], teacher)
-
- elif len(lesson["infos"].split('|')) == 4:
- infos = lesson["infos"].split('|')
- text += '•{}\
- \n{}\
- \n({}) {}\
- \n({}) {}'.format(i, lesson["name"],
- infos[1],
- infos[0],
- infos[3],
- infos[2])
- else:
- text += '•{}\
- \n{}'.format(i, lesson["name"])
-
- text += '\n\n'
+ text += '•' + parse_lesson(i, lesson) + '\n\n'
return text
diff --git a/schedules.py b/schedules.py
index 03e0047..d3c034f 100644
--- a/schedules.py
+++ b/schedules.py
@@ -1,12 +1,13 @@
#!/usr/bin/python3.3
-import threading, telebot, schedule, time
+import threading, telebot, schedule, time, re
+from datetime import datetime
import os, sys
from telebot import types
from telegram.constants import ParseMode
import for_json
from admin import admin_command, is_admin, send_admin_message, send_admin_document
-bot = telebot.TeleBot("TOKEN_API")
+bot = telebot.TeleBot("TELEBOT_API")
start_txt = 'Привет! Это бот, который будет кидать тебе сообщения перед нужной парой с номером кабинета/фамилией препода\
\n\nТы можешь настроить отправку сообщений в лс или добавить меня в группу, куда я буду присылать расписание\
@@ -29,7 +30,7 @@ def update_schedules(message):
@bot.message_handler(commands=['update'])
@admin_command
def update_schedules(message):
- for_json.create_schedule_tasks()
+ for_json.create_schedule_tasks(manual=True)
send_admin_message('Произошёл update')
return
@@ -89,7 +90,7 @@ def start(message):
temp
]
- if for_json.check_group_in_json(temp):
+ if temp in for_json.groups_in_json():
send_message(message.chat.id,
'Отлично! Теперь я буду присылать вам расписание {} группы'.format(temp))
else:
@@ -109,16 +110,15 @@ def start(message):
send_message(message.chat.id, start_txt)
markup = types.InlineKeyboardMarkup()
- markup.add(types.InlineKeyboardButton(text="102", callback_data="102"))
- markup.add(types.InlineKeyboardButton(text="103", callback_data="103"))
- markup.add(types.InlineKeyboardButton(text="105", callback_data="105"))
- markup.add(types.InlineKeyboardButton(text="110", callback_data="110"))
+ for i in for_json.groups_in_json():
+ markup.add(types.InlineKeyboardButton(text=i, callback_data=i))
markup.add(types.InlineKeyboardButton(text="Моей группы нет в этом списке", callback_data="other"))
bot.send_message(message.chat.id, 'Пожалуйста, выбери свою группу', parse_mode=ParseMode.HTML, reply_markup=markup)
return
-@bot.callback_query_handler(func=lambda call: True)
+# @bot.callback_query_handler(func=lambda call: True)
+@bot.callback_query_handler(func=lambda call: not(call.data in ['left', 'right']))
def callback_inline(call):
infos = [
call.from_user.id,
@@ -208,10 +208,39 @@ def send_request(message):
def send_schedule(message):
text = 'К сожалению, бот не может отправить тебе расписание твоей группы на сегодня :('
try:
- text = for_json.get_schedule(str(message.chat.id))
+ day = datetime.today().strftime('%A').lower()[:3] # mon tue ...
+ text = for_json.get_schedule(message.chat.id, day)
except Exception as e:
send_admin_message('Schedule error from: {} \n\n {}'.format(message.chat.id, e))
- send_message(message.chat.id, text)
+
+ markup = types.InlineKeyboardMarkup()
+ markup.add(types.InlineKeyboardButton(text="◀️", callback_data="left"),
+ types.InlineKeyboardButton(text="▶️", callback_data="right"))
+ bot.send_message(message.chat.id, text, ParseMode.HTML, reply_markup=markup)
+
+ return
+
+@bot.callback_query_handler(func=lambda call: call.data in ['left', 'right'])
+def change_schedule(call):
+ days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat']
+ russian_days = ['понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу']
+ i = 6 # выходной
+ for day in russian_days:
+ if day in call.message.text:
+ i = russian_days.index(day)
+ break
+
+ delta = (1) if (call.data == 'right') else (-1)
+ ind = ((i + delta) % 6) if (i + delta > 0) else (i + delta)
+
+ text = for_json.get_schedule(call.message.chat.id, days[ind])
+
+ markup = types.InlineKeyboardMarkup()
+ markup.add(types.InlineKeyboardButton(text="◀️", callback_data="left"),
+ types.InlineKeyboardButton(text="▶️", callback_data="right"))
+
+ bot.edit_message_text(text, call.message.chat.id, call.message.message_id,
+ parse_mode=ParseMode.HTML, reply_markup=markup)
return