Archived
add buttons for changing schedule day in /schedule
This commit is contained in:
+54
-52
@@ -6,6 +6,8 @@ from datetime import datetime
|
|||||||
path_users = "json/users.json" # Нужный путь до json файлов
|
path_users = "json/users.json" # Нужный путь до json файлов
|
||||||
path_schedule = "json/schedule.json"
|
path_schedule = "json/schedule.json"
|
||||||
|
|
||||||
|
allow_update = True
|
||||||
|
|
||||||
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):
|
||||||
@@ -52,28 +54,10 @@ def change_user_param(id, key, value):
|
|||||||
create_schedule_tasks()
|
create_schedule_tasks()
|
||||||
return
|
return
|
||||||
|
|
||||||
def create_schedule_tasks():
|
def parse_lesson(time, lesson):
|
||||||
schedule.clear()
|
|
||||||
users = {}
|
|
||||||
schdl = {}
|
|
||||||
with open(path_users, 'r', encoding='utf-8') as 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():
|
|
||||||
if params['allow_message'] != 'yes':
|
|
||||||
continue
|
|
||||||
group = params['group']
|
|
||||||
if group == 'other':
|
|
||||||
continue
|
|
||||||
timeout = params['timeout']
|
|
||||||
for day in schdl[group]:
|
|
||||||
for i, lesson in schdl[group][day].items():
|
|
||||||
if lesson["name"] == "": # Неправильный формат schedule
|
|
||||||
continue
|
|
||||||
|
|
||||||
start, end = i.split("-")
|
|
||||||
text = ''
|
text = ''
|
||||||
|
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]
|
||||||
@@ -93,12 +77,48 @@ def create_schedule_tasks():
|
|||||||
elif len(lesson["infos"].split('|')) == 1:
|
elif len(lesson["infos"].split('|')) == 1:
|
||||||
text = '{}-{}\
|
text = '{}-{}\
|
||||||
\n<b>{}</b>'.format(start, end, lesson["name"])
|
\n<b>{}</b>'.format(start, end, lesson["name"])
|
||||||
else: #неправильный формат infos в json файле
|
else:
|
||||||
print("что-то не так")
|
print("что-то не так")
|
||||||
print(lesson["name"])
|
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 = {}
|
||||||
|
with open(path_users, 'r', encoding='utf-8') as 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():
|
||||||
|
if params['allow_message'] != 'yes':
|
||||||
|
continue
|
||||||
|
group = params['group']
|
||||||
|
if group == 'other':
|
||||||
|
continue
|
||||||
|
timeout = params['timeout']
|
||||||
|
for day in schdl[group]:
|
||||||
|
for i, lesson in schdl[group][day].items():
|
||||||
|
if lesson["name"] == "": # Неправильный формат schedule
|
||||||
|
continue
|
||||||
|
|
||||||
|
start = i.split("-")[0]
|
||||||
|
text = parse_lesson(i, lesson)
|
||||||
|
|
||||||
|
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(delta, format)
|
||||||
@@ -106,6 +126,7 @@ def create_schedule_tasks():
|
|||||||
for i in str(start_task).split(':'):
|
for i in str(start_task).split(':'):
|
||||||
tmp += (('0' + i ) if len(i) < 2 else i) + ":"
|
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)
|
schedule.every().monday.at(start_task).do(bot.send_message, id, text, thread_id)
|
||||||
elif day == 'tue':
|
elif day == 'tue':
|
||||||
@@ -121,13 +142,12 @@ def create_schedule_tasks():
|
|||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
|
def groups_in_json():
|
||||||
def check_group_in_json(number):
|
|
||||||
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 str(number) in schdl.keys()
|
return schdl.keys()
|
||||||
|
|
||||||
def return_infos(id):
|
def return_infos(id):
|
||||||
id = str(id)
|
id = str(id)
|
||||||
@@ -140,17 +160,20 @@ def return_infos(id):
|
|||||||
|
|
||||||
def pause_bot():
|
def pause_bot():
|
||||||
schedule.clear()
|
schedule.clear()
|
||||||
|
global allow_update
|
||||||
|
allow_update = False
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
||||||
def get_schedule(id):
|
def get_schedule(id, day):
|
||||||
id = str(id)
|
id = str(id)
|
||||||
text = '<u>Расписание на сегодня</u>:\n\n'
|
days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat']
|
||||||
|
russian_days = ['понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу']
|
||||||
|
|
||||||
|
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:
|
||||||
day = datetime.today().strftime('%A').lower()[:3]
|
|
||||||
|
|
||||||
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']
|
||||||
@@ -161,30 +184,9 @@ def get_schedule(id):
|
|||||||
try:
|
try:
|
||||||
schdl_today = json.load(schedule_file)[group][day]
|
schdl_today = json.load(schedule_file)[group][day]
|
||||||
except:
|
except:
|
||||||
return 'Расписания твоей группы на сегодня нет'
|
return 'Расписания твоей группы на {} нет'.format(russian_days[days.index(day)])
|
||||||
|
|
||||||
for i, lesson in schdl_today.items():
|
for i, lesson in schdl_today.items():
|
||||||
if len(lesson["infos"].split('|')) == 2:
|
text += '•' + parse_lesson(i, lesson) + '\n\n'
|
||||||
teacher = lesson["infos"].split('|')[0]
|
|
||||||
room = lesson["infos"].split('|')[1]
|
|
||||||
text += '•{} | {}\
|
|
||||||
\n<b>{}</b>\
|
|
||||||
\n<i>{}</i>'.format(i, room, lesson["name"], teacher)
|
|
||||||
|
|
||||||
elif len(lesson["infos"].split('|')) == 4:
|
|
||||||
infos = lesson["infos"].split('|')
|
|
||||||
text += '•{}\
|
|
||||||
\n<b>{}</b>\
|
|
||||||
\n({}) <i>{}</i>\
|
|
||||||
\n({}) <i>{}</i>'.format(i, lesson["name"],
|
|
||||||
infos[1],
|
|
||||||
infos[0],
|
|
||||||
infos[3],
|
|
||||||
infos[2])
|
|
||||||
else:
|
|
||||||
text += '•{}\
|
|
||||||
\n<b>{}</b>'.format(i, lesson["name"])
|
|
||||||
|
|
||||||
text += '\n\n'
|
|
||||||
|
|
||||||
return text
|
return text
|
||||||
|
|||||||
+40
-11
@@ -1,12 +1,13 @@
|
|||||||
#!/usr/bin/python3.3
|
#!/usr/bin/python3.3
|
||||||
import threading, telebot, schedule, time
|
import threading, telebot, schedule, time, re
|
||||||
|
from datetime import datetime
|
||||||
import os, sys
|
import os, sys
|
||||||
from telebot import types
|
from telebot import types
|
||||||
from telegram.constants import ParseMode
|
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("TELEBOT_API")
|
||||||
|
|
||||||
start_txt = 'Привет! Это бот, который будет кидать тебе сообщения перед нужной парой с номером кабинета/фамилией препода\
|
start_txt = 'Привет! Это бот, который будет кидать тебе сообщения перед нужной парой с номером кабинета/фамилией препода\
|
||||||
\n\nТы можешь настроить отправку сообщений в лс или добавить меня в группу, куда я буду присылать расписание\
|
\n\nТы можешь настроить отправку сообщений в лс или добавить меня в группу, куда я буду присылать расписание\
|
||||||
@@ -29,7 +30,7 @@ def update_schedules(message):
|
|||||||
@bot.message_handler(commands=['update'])
|
@bot.message_handler(commands=['update'])
|
||||||
@admin_command
|
@admin_command
|
||||||
def update_schedules(message):
|
def update_schedules(message):
|
||||||
for_json.create_schedule_tasks()
|
for_json.create_schedule_tasks(manual=True)
|
||||||
send_admin_message('Произошёл update')
|
send_admin_message('Произошёл update')
|
||||||
|
|
||||||
return
|
return
|
||||||
@@ -89,7 +90,7 @@ def start(message):
|
|||||||
temp
|
temp
|
||||||
]
|
]
|
||||||
|
|
||||||
if for_json.check_group_in_json(temp):
|
if temp in for_json.groups_in_json():
|
||||||
send_message(message.chat.id,
|
send_message(message.chat.id,
|
||||||
'Отлично! Теперь я буду присылать вам расписание {} группы'.format(temp))
|
'Отлично! Теперь я буду присылать вам расписание {} группы'.format(temp))
|
||||||
else:
|
else:
|
||||||
@@ -109,16 +110,15 @@ def start(message):
|
|||||||
send_message(message.chat.id, start_txt)
|
send_message(message.chat.id, start_txt)
|
||||||
|
|
||||||
markup = types.InlineKeyboardMarkup()
|
markup = types.InlineKeyboardMarkup()
|
||||||
markup.add(types.InlineKeyboardButton(text="102", callback_data="102"))
|
for i in for_json.groups_in_json():
|
||||||
markup.add(types.InlineKeyboardButton(text="103", callback_data="103"))
|
markup.add(types.InlineKeyboardButton(text=i, callback_data=i))
|
||||||
markup.add(types.InlineKeyboardButton(text="105", callback_data="105"))
|
|
||||||
markup.add(types.InlineKeyboardButton(text="110", callback_data="110"))
|
|
||||||
markup.add(types.InlineKeyboardButton(text="Моей группы нет в этом списке", callback_data="other"))
|
markup.add(types.InlineKeyboardButton(text="Моей группы нет в этом списке", callback_data="other"))
|
||||||
bot.send_message(message.chat.id, 'Пожалуйста, выбери свою группу', parse_mode=ParseMode.HTML, reply_markup=markup)
|
bot.send_message(message.chat.id, 'Пожалуйста, выбери свою группу', parse_mode=ParseMode.HTML, reply_markup=markup)
|
||||||
|
|
||||||
return
|
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):
|
def callback_inline(call):
|
||||||
infos = [
|
infos = [
|
||||||
call.from_user.id,
|
call.from_user.id,
|
||||||
@@ -208,10 +208,39 @@ def send_request(message):
|
|||||||
def send_schedule(message):
|
def send_schedule(message):
|
||||||
text = 'К сожалению, бот не может отправить тебе расписание твоей группы на сегодня :('
|
text = 'К сожалению, бот не может отправить тебе расписание твоей группы на сегодня :('
|
||||||
try:
|
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:
|
except Exception as e:
|
||||||
send_admin_message('Schedule error from: {} \n\n {}'.format(message.chat.id, 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
|
return
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user