/
Esgalnor
/
TG_Bot
Обзор
Документация
Войти
/
Esgalnor
/
TG_Bot
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
patch
custom_handlers/command_appoint.py
337 строк
11 KB
Esgalnor
upload files
18 авг 2025, 17:25
18 авг 2025, 17:25
75d31e6
Код
Авторство
О чём код?
import datetime from telebot.types import Message, ReplyKeyboardRemove, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton from loader import bot from database.user_pw import users from database.calendar_pw import my_calendar from utils.my_calendar import calendar_1, cal_1 from utils.check import check_date, check_rec, check_start_time from config.config import WORK_TIME_STOP, WORK_TIME_START, MASTER_ID, MAX_TIME_PROC from config.proc_list import proc_dict, price_dict, time_dict from utils.json_funcs import to_obj, to_str from states.states import MyStates from utils.add_busy_time import add_busy_time from utils.max_time_for_proc import max_time ID = 0 @bot.message_handler(state=None, commands=["appoint"]) def appoint(message: Message): id = message.from_user.id """global ID if id == MASTER_ID: ID = users.id_temp_user() id = ID""" users.set_temp(id) rec_user_no = check_rec(id) if rec_user_no: text = "Выберите дату:" else: text = ("Вы уже записаны ({}).\n" "Дополнительные записи согласовываются с мастером.\n" "Выберите дату для согласования.".format(users.get_curr_rec(id))) text = text + "\n/cancel для отмены" now = datetime.datetime.now() # Get the current date bot.delete_state(id) bot.send_message( chat_id=id, text=text, reply_markup=cal_1.create_calendar( name=calendar_1.prefix, # Specify the NAME of your calendar year=now.year, month=now.month, ), ) @bot.callback_query_handler(func=lambda call: call.data.startswith(calendar_1.prefix), state=None) def callback_inline(call: CallbackQuery): """ Processing inline callback requests for a calendar :param call: :return: """ # At this point, we are sure that this calendar is ours. So we cut the line by the separator of our calendar name, action, year, month, day = call.data.split(calendar_1.sep) # Processing the calendar. Get either the date or None if the buttons are of a different type id = call.from_user.id try: date = cal_1.calendar_query_handler( bot=bot, call=call, name=name, action=action, year=year, month=month, day=day ) except: bot.send_message(id, "К сожалению на эти даты записи пока нет.") bot.delete_state(id) return choice_date = date.strftime('%d.%m.%Y') users.set_temp(id, choice_date) # There are additional steps. Let's say if the date DAY is selected, you can execute your code. I sent a message. if action == "DAY": bot.send_message( chat_id=id, text=f"Выбранная дата: {choice_date}", reply_markup=ReplyKeyboardRemove(), ) users.set_temp(id, choice_date) corr_date = check_date(date) if corr_date[0] == 2: choice_time(id, choice_date) elif corr_date[0] == 0: bot.send_message( id, corr_date[1] ) bot.delete_state(id) else: bot.send_message( id, corr_date[1] + "\n" "Выберите время.\n" "/cancel для отмены" ) choice_time(id, choice_date) users.set_wait(id, True) elif action == "CANCEL": bot.send_message( chat_id=id, text="Отмена", reply_markup=ReplyKeyboardRemove(), ) bot.delete_state(id) @bot.callback_query_handler(func=lambda call: call.data.startswith("time"), state=None) def callback_time(call: CallbackQuery): id = call.from_user.id if users.get_temp(id): print(id, id) time = list(map(int, call.data[5:].split(':'))) date = users.get_temp(id) date_list = list(map(int, date.split('.'))) date_rec = datetime.datetime( date_list[2], date_list[1], date_list[0], time[0], time[1] ).strftime("%d.%m.%Y %H:%M") rec_user_no = check_rec(id) if rec_user_no: if not users.get_wait(id): users.set_curr_rec(id, date_rec) bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Ваша текущая запись: {}".format(users.get_curr_rec(id)), ) else: wait_check_rec(id, call.message.message_id, date_rec) else: tg_name = users.get_tg_name(id) phone = users.get_phone(id) if tg_name or phone: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Ваша запись: {} отправлена на согласование.".format(date_rec), ) bot.send_message( MASTER_ID, "Просьба согласовать запись для клиента {} id={} на время {}" "".format(users.get_name(id), id, date_rec) ) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Для согласования добавьте в профиль " "Имя пользователя Telegram(/tg_name) или контактный телефон(/phone).", ) users.set_temp(id, '') bot.delete_state(id) max_duration = max_time(date, call.data[5:]) choice_proc(id, max_duration) @bot.callback_query_handler(func=lambda call: call.data.startswith("proc"), state=None) def choice_another_proc(call: CallbackQuery): id = call.from_user.id data_list = call.data.split('.') temp_data = users.get_temp(id) if not temp_data: temp = dict() else: temp = to_obj(temp_data) temp_dict = temp temp_dict[data_list[1]] = time_dict[data_list[1]] users.set_temp(id, to_str(temp_dict)) bot.edit_message_text( "Ещё процедуру?", id, call.message.message_id, ) date_start = users.get_curr_rec(id).split() print(date_start) max_duration = max_time(date_start[0], date_start[1]) busy_time = sum(list(map(int, to_obj(users.get_temp(id)).values()))) choice_proc(id, max_duration, busy_time) @bot.callback_query_handler(func=lambda call: call.data.startswith("done"), state=None) def choice_done(call: CallbackQuery): id = call.from_user.id temp_data = users.get_temp(id) if temp_data: temp_dict = to_obj(temp_data) text_recs = 'Выбранные Вами процедуры:\n' summ = 0 for proc in temp_dict.keys(): text_recs += proc + " " summ += price_dict[proc] text_price = "\nИтого на {}р".format(summ) curr_rec = users.get_curr_rec(id) rec = dict() rec[curr_rec] = temp_data users.del_rec(id) users.set_curr_rec(id, to_str(rec)) add_busy_time(to_str(rec)) rec = to_obj(users.get_curr_rec(id)) if rec: for date in rec.keys(): curr_rec = date break bot.edit_message_text( curr_rec + text_price, id, call.message.message_id ) bot.send_message( MASTER_ID, "Запись. {} id={} на {}мин".format(users.get_name(id), id, users.get_curr_rec(id)).replace('{', '').replace('}', '').replace('\\', '').replace('\"', '') ) my_calendar.add_user_on_rec(curr_rec.split()[0], id) else: bot.edit_message_text( 'Отмена записи, так как не выбрано ни одной процедуры.', id, call.message.message_id ) #users.del_rec(id) users.set_temp(id) bot.delete_state(id) @bot.callback_query_handler(func=lambda call: call.data.startswith("busy"), state=None) def choice_busy(call: CallbackQuery): id = call.from_user.id bot.delete_message(id, call.message.message_id) choice_time(id, users.get_temp(id)) def choice_time(id: int, day: str): keyboard_1 = InlineKeyboardMarkup() keyboard_1.max_row_keys = 5 row_key = list() for hour in range(WORK_TIME_START, WORK_TIME_STOP): hour_txt = datetime.time(hour).strftime("%H:%M") half_hour_txt = datetime.time(hour).strftime("%H:") + "30" if check_start_time(day, hour_txt): row_key.append(InlineKeyboardButton(hour_txt, callback_data="time " + hour_txt)) else: row_key.append(InlineKeyboardButton("busy", callback_data="busy")) if check_start_time(day, half_hour_txt): row_key.append(InlineKeyboardButton(half_hour_txt, callback_data="time " + half_hour_txt)) else: row_key.append(InlineKeyboardButton("busy", callback_data="busy")) keyboard_1.row(*row_key) bot.send_message( id, "Выберите время:", reply_markup=keyboard_1 ) def choice_proc(id: int, max_dur: int = MAX_TIME_PROC, busy_time: int = 0, cbd: str = "proc "): keyboard_proc = InlineKeyboardMarkup() keyboard_proc.max_row_keys = 1 left_time = max_dur - busy_time # оставшееся для выбора время row_key = list() temp_txt = users.get_temp(id) if not temp_txt: temp = dict() else: temp = to_obj(temp_txt) for proc_name in proc_dict.keys(): if proc_name[0].isdigit(): row_key.append(InlineKeyboardButton("Группа {}".format(proc_name), callback_data=' ')) else: if proc_name not in temp: if left_time >= time_dict[proc_name]: row_key.append(InlineKeyboardButton("{} {} минут".format(proc_name, time_dict[proc_name]), callback_data=cbd + '.' + proc_name)) row_key.append(InlineKeyboardButton("Готово", callback_data="done")) keyboard_proc.row(*row_key) bot.send_message( id, "Выберите процедуру (максимальное время - {} минут):".format(left_time), reply_markup=keyboard_proc ) def wait_check_rec(id: int, id_message: int, date: str): tg_name = users.get_tg_name(id) phone = users.get_phone(id) if tg_name or phone: bot.edit_message_text( chat_id=id, message_id=id_message, text="Ваша запись: {} отправлена на согласование.".format(date), ) bot.send_message( MASTER_ID, "Просьба согласовать запись для клиента {} id={} на время {}".format(users.get_name(id), id, date) ) else: bot.edit_message_text( chat_id=id, message_id=id_message, text="Для согласования добавьте в профиль " "Имя пользователя Telegram(/tg_name) или контактный телефон(/phone).", )