async def name(msg: Message, state: FSMContext): text = msg.text data = await state.get_data() user = await correct_user(text, msg) if not user: print( f'{msg.from_user.full_name} не смог зарегестрировать директора: не корректные данные ' ) return try: cur.execute('''INSERT INTO directors VALUES (NULL, NULL, ?)''', [user]) except Exception as e: await msg.answer(text='Такой директор уже существует') print( f'{msg.from_user.full_name} не смог зарегестрировать пользователя' f'\nОшибка: {e}') await state.finish() return cur.execute( '''UPDATE users set role = ?, school = ? WHERE user_name = ?''', [director_role, data.get('school_id'), text[1:]]) con.commit() director_id_list.append(user) print( f'{msg.from_user.full_name} зарегестрировал директора с user_name: {text}' ) await msg.answer('Пользователь добавлен', reply_markup=admin_panel) await bot.send_message(chat_id=user, text='Напишите или нажмите \nна команду: /start') await state.finish()
async def bot_start(message: types.Message): user_id = message.from_user.id user_name = message.from_user.username name = message.from_user.full_name cur.execute('''SELECT user_id FROM users WHERE user_id = ?''', [user_id]) if not cur.fetchone(): if not message.from_user.username: await message.answer(text='Укажите в настройках имя пользователя') await message.answer(text='Затем отправьте в чат командку /start') return await register_user(user_id, user_name, name, not_role) role = cur.execute('''SELECT role FROM users WHERE user_id = ?''', [user_id]).fetchone()[0] panel = not_role_panel if role == admin_role: panel = admin_panel elif role == director_role: panel = director_panel elif role == teacher_role: panel = teacher_panel() if await is_classroom_teacher(message): panel = teacher_panel(True) elif role == student_role: panel = student_panel # await bot.send_message( # chat_id='691537375', # text=f'Зареган новый пользователь' # f'Имя: {name}' # f'Телеграмм имя: {user_id}' # f'Роль: {role}') await message.answer(f'Привет, {name}' f'\nВаша роль: {role}', reply_markup=panel)
async def register(msg: Message, state: FSMContext): text = msg.text school_id = await check_school_id(msg.from_user.id) user = await correct_user(text, msg) if not user: print(f'{msg.from_user.full_name} не смог зарегестрировать ученика') return class_id = cur.execute('''SELECT id FROM classes WHERE bos = ?''', [msg.from_user.id]).fetchone()[0] try: cur.execute('''INSERT INTO students VALUES(NULL, ?, ?, 0)''', [class_id, user]) cur.execute( '''UPDATE users set role = ?, school = ? WHERE user_id = ?''', [student_role, school_id, user]) except Exception as e: await msg.answer(text='Такой ученик уже существует') print(f'{msg.from_user.full_name} не смог зарегестрировать ученика' f'\nОшибка: {e}') await state.finish() return con.commit() student_id_list.append(user) print(f'{msg.from_user.full_name} добавил ученика с user_name: {text}') await msg.answer('Ученик добавлен', reply_markup=teacher_panel(True)) await bot.send_message(chat_id=user, text='Напишите или нажмите \nна команду: /start') await state.finish()
def write(self): """Заносим выбранную пользователем дату в переменную data, и записываем дату и название заметки в главное окно""" data = self.calendarWidget.selectedDate() day = data.day() month = data.month() year = data.year() data = datetime(year=year, month=month, day=day) text = self.NoteText.text().strip() # Добавляем эту заметку в базу данных notes try: cur.execute("INSERT INTO notes VALUES(NULL, ?, ?, ?, ?)", ( data.strftime('%Y'), data.strftime('%m'), data.strftime('%d'), text, )).fetchall() con.commit() # Добавляем заметку в главное окно self.mainWindow.listWidget.addItem( data.strftime('%d.%m.%Y') + ' - ' + text + '\n') self.close() except Exception: create_message_window( self, 'Заметка под таким названием уже существует') self.close()
async def get_data_for_table(msg, month, school_id, class_id): days = cur.execute( '''SELECT day FROM days WHERE month = ? and class = ?''', [month, class_id]).fetchall() users = cur.execute( '''SELECT u.user_id, u.name FROM canteen_journal c LEFT JOIN days d ON c.day = d.id LEFT JOIN users u ON c.user = u.user_id WHERE d.month = ?''', [month]).fetchall() users = set(users) foods = await get_food(month, class_id) data = list() data.append(['День']) for day in days: data.append([day[0]]) for user_id, name in users: #name = give_emoji_free_text(name) data[0].append(name) choices = await get_choice(month, user_id) for i, day in enumerate(days): data[i + 1].append(choices.get(day[0], '-')) data[0].append('Еда') data[0].append('Цена') for i, info in enumerate(foods): food, price = info data[i + 1].append(food) data[i + 1].append(price) return data
async def register_teacher(text, msg, state): school_id = cur.execute('''SELECT school FROM users WHERE user_id = ?''', [msg.from_user.id]).fetchone()[0] user = await correct_user(text, msg) if not user: await state.finish() print( f'{msg.from_user.full_name} не смог зарегестрировать учителя: не корректные данные' ) return try: cur.execute('''INSERT INTO teachers VALUES(NULL, ?)''', [user]) cur.execute( '''UPDATE users set role = ?, school = ? WHERE user_id = ?''', [teacher_role, school_id, user]) except Exception as e: await msg.answer(text='Такой учитель уже существует') print(f'{msg.from_user.full_name} не смог зарегестрировать учителся' f'\nОшибка: {e}') await state.finish() return con.commit() teacher_id_list.append(user) print( f'{msg.from_user.full_name} зарегестрировал учителя с user_name: {text}' ) await msg.answer('♻️Учитель добавлен♻️') teacher_id_list.append(user) await bot.send_message(chat_id=user, text='Напишите или нажмите \nна команду: /start') await state.finish()
async def canteen_summ(msg, class_id, food): paid = 0 free = 0 price = food[1] await write_date_in_db(food, class_id) for people_id, choice in canteen_data[class_id]['who'].items(): if choice == '+': cur.execute( '''UPDATE students SET canteen = canteen + ? WHERE user = ?''', [price, people_id]) paid += 1 elif choice == '-': free += 1 await write_choice_in_db(people_id, choice) for people_id in canteen_data[class_id]['who'].keys(): await bot.send_message(chat_id=people_id, text='⬇️Получилось⬇️' '\n-----------------------------' f'\n💵Платно: {paid}' f'\n💸Бесплатно: {free}') class_id = await student_class_id(msg) for id in await stay_people_id(class_id): await write_choice_in_db(id, '-') con.commit() try: del canteen_data[class_id] print('блюдо удалено') except KeyError: pass
async def food(msg: Message, state: FSMContext): class_id = await student_class_id(msg) food = await take_food(msg, class_id) user_id = msg.from_user.id print( f'{msg.from_user.full_name} роль: ученик, id: {user_id} зашел в что дают' ) day = dt.datetime.now() new_day = cur.execute( '''SELECT * FROM days WHERE day = ? and month = ? and year = ?''', [day.day, day.month, day.year]).fetchone() if new_day: # если сегодня запись есть то отмечаться заного не надо await msg.answer(text='Вы сегодня отмечались') return if isinstance(food, FSMContext): try: canteen_bos_id = cur.execute( '''SELECT canteen FROM classes WHERE id = ?''', [class_id]).fetchone()[0] except Exception as e: print(e) canteen_bos_id = None await msg.answer(text='Данные заполняются другим пользователем', reply_markup=exit_from_food_panel if user_id == canteen_bos_id else None) return elif len(food) == 2: await msg.answer(text='Данные на сегодня внесены') return canteen_data[class_id]['food'] = state await msg.answer('Напишите количество учеников в классе или нажмите все', reply_markup=canteen_quantity_all_panel) await WriteFood.Quantity.set()
async def delete_school(msg: Message, state: FSMContext): data = await state.get_data() cur.execute('''DELETE FROM schools WHERE id = ?''', [data.get('school_id')]) await msg.answer(text='Школа удалена', reply_markup=admin_panel) con.commit() await state.finish() await msg.delete()
async def write_date_in_db(food, class_id): food, price = food try: cur.execute('''INSERT INTO days VALUES(NULL, ?, ?, ?, ?, ?, ?)''', [class_id, *get_date(), food, price]) except Exception as e: print(f'Ошибка при записи данных в таблицу с днями') print(e)
def load_data_in_list_widget(data, day_n): """Заносим данные в таблицу events""" for line in data: time = line[0].split(':') + line[1].split(':') name = line[2] event_text = line[-1].replace('\n\n', '\n') cur.execute('''INSERT INTO events VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)''', (day_n, *time, name, event_text)) con.commit()
async def classroom_teacher_class_id(msg): try: return cur.execute('''SELECT id FROM classes WHERE bos = ?''', [msg.from_user.id]).fetchone()[0] except Exception as e: print('Ошибка при взятии айди класса') print(e) print(cur.execute('''SELECT class FROM students WHERE user = ?''', [msg.from_user.id]).fetchone())
async def classroom_delete(class_name): students_id = cur.execute( '''SELECT user FROM students s LEFT JOIN classes c ON c.id = s.class WHERE c.name = ?''', [class_name]).fetchall() for student_id in students_id: await student_delete(student_id[0]) cur.execute('''DELETE FROM classes WHERE name = ?''', [class_name]) con.commit()
async def write_choice_in_db(people_id, choice): day = cur.execute( '''SELECT id FROM days WHERE day = ? and month = ? and year = ?''', [*get_date()]).fetchone()[0] try: cur.execute('''INSERT INTO canteen_journal VALUES (NULL, ?, ?, ?)''', [people_id, day, choice]) except Exception as e: print(f'Ошибка при записи данных в журнал столовой') print(e)
async def register_user(user_id, user_name, name, role): cur = con.cursor() try: cur.execute(f'''INSERT INTO users VALUES ({user_id}, '{user_name}', '{name}','{role}', NULL)''') print(f'Зарегестрировался: {name}' f'\nРоль: {role}') con.commit() except Exception as e: print('Ошибка при регистрации' f'\nОшибка: {e}')
async def reneme_class_handler(msg: Message, state: FSMContext): data = await state.get_data() class_name = data['class_name'] class_name_new = msg.text if not await chek_correct_classroom_name(msg, class_name_new): return cur.execute('''UPDATE classes SET name = ? WHERE name = ?''', [class_name_new, class_name]) await msg.answer( text=f'Класс переименован с {class_name} на {class_name_new}') data['class_name'] = class_name_new await state.update_data(data) await ShowClass.Class.set()
def clear_event(self): """Удаляет выбранный ивент""" try: start, end = get_start_and_end(self.EventView.currentItem().text()) except AttributeError: create_message_window(self, 'Событие не выбрано') return cur.execute('''DELETE FROM events WHERE start_hour = ? and start_minute = ? and end_hour = ? and end_minute = ? and day = ?''', (*start, *end, self.day_n)) con.commit() self.EventView.takeItem(self.EventView.currentRow()) self.event_description.setText('')
async def different_answer(call: CallbackQuery, callback_data: dict, state: FSMContext): await call.answer(cache_time=60) choice = callback_data['answer'] user_id = call.from_user.id await call.message.delete() if choice == 'Ученики': await call.message.answer('Напишите количество учеников в классе', reply_markup=canteen_quantity_all_panel) await WriteFood.Quantity.set() print( f'{call.from_user.full_name} роль: ученик, id: {user_id} редактирует учеников' ) elif choice == 'Название': await call.message.answer('Напишите название блюда', reply_markup=exit_from_food_panel) await WriteFood.Name.set() print( f'{call.from_user.full_name} роль: ученик, id: {user_id} редактирует название' ) elif choice == 'Цена': await call.message.answer('Напишите цену блюда') await WriteFood.Price.set() print( f'{call.from_user.full_name} роль: ученик, id: {user_id} редактирует цену' ) elif choice == 'save': print( f'{call.from_user.full_name} роль: ученик, id: {user_id} сохранил блюдо' ) class_id = cur.execute('''SELECT class FROM students WHERE user = ?''', [call.from_user.id]).fetchone()[0] data = await state.get_data() canteen_data[class_id]['food'] = [ data.get('Название'), data.get('Цена') ] canteen_data[class_id]['quantity'] = data.get('Ученики') people = cur.execute('''SELECT user FROM students WHERE class = ?''', [class_id]).fetchall() people = map(lambda id: id[0], people) for user_id in people: try: await bot.send_message(chat_id=user_id, text='Блюдо добавлено' '\n------------------------------' '\nИдите записаться😋') except Exception: pass await state.finish()
async def canteen_bos(msg: Message): print(f'{msg.from_user.full_name} нажал на кнопку: Главный по столовой') class_id = cur.execute('''SELECT id FROM classes WHERE bos = ?''', [msg.from_user.id]).fetchone()[0] students = cur.execute('''SELECT u.name, s.user FROM students s LEFT JOIN users u ON s.user = u.user_id WHERE class = ?''', [class_id]).fetchall() if not students: await msg.answer(text='Учеников нет') print(f'{msg.from_user.full_name} нажал на кнопку: Главный по столовой но учеников не было') return for student, user_id in students: await msg.answer(text=f'🧑🎓{student}🧑🎓', reply_markup=await register_canteen_boss_buttons(user_id))
async def delete_teacher_in_class(msg: Message, state: FSMContext): user_id = msg.from_user.id data = await state.get_data() class_name = data['class_name'] school_id = await check_school_id(user_id) user = cur.execute('''SELECT bos FROM classes WHERE name = ? and school = ?''', [class_name, school_id]).fetchone()[0] cur.execute('''UPDATE classes SET bos = NULL WHERE name = ? and school = ?''', [class_name, school_id]) print(f'{msg.from_user.full_name} убрал кл.рук. из {class_name} класса') con.commit() await msg.answer(text='♻️Кл.рук. убран♻️') await class_information(msg, school_id, class_name) del classroom_teacher_id_list[classroom_teacher_id_list.index(user)] await bot.send_message(chat_id=user, text='Напишите или нажмите \nна команду: /start')
async def register(msg: Message, state: FSMContext): answer1 = msg.text try: cur.execute('''INSERT INTO schools VALUES (NULL, ?)''', [answer1]) except Exception as e: await msg.answer(text='Такая школа уже существует') print( f'{msg.from_user.full_name} не смог зарегестрировать пользователя: ошибка при сохранении в бд' f'\nОшибка: {e}') await state.finish() return con.commit() print( f'{msg.from_user.full_name} зарегестрировал школу с именем: {answer1}') await msg.answer('Школа добавлена' f'\nНазвание: {answer1}') await state.finish()
async def mailing_func(msg: Message): print(f'{msg.from_user.full_name} нажал кнопку Рассылка') school_id = await check_school_id(msg.from_user.id) classes = cur.execute('''SELECT * FROM classes WHERE school = ?''', [school_id]).fetchall() await show_classes_buttons(msg, classes) await Mailing.Start.set()
def get_description(self, start, end): """Возвращает подробное описание ивента""" text = cur.execute('''SELECT description FROM events WHERE start_hour = ? and start_minute = ? and end_hour = ? and end_minute = ? and day = ?''', (*start, *end, self.day_n)).fetchone()[0] return text
async def register_canteen_boss(call: CallbackQuery): await call.answer(cache_time=60) print(call.data) student_id = call.data.split('_')[3] user_id = call.from_user.id cur.execute('''UPDATE classes set canteen = ? WHERE bos = ?''', [student_id, user_id]) try: await call.message.delete() except Exception as e: print(f'{call.from_user.full_name} не смог зарегестрировать главного по столовой' f'\nОшибка: {e}') print(f'{call.from_user.full_name} зарегестрировал главного по столовой в классе с user_id: {student_id} где кл.рук. с user_id: {user_id}') await call.message.answer(text='♻️Выполнено♻️') await bot.send_message(chat_id=student_id, text='Вы стали главным по столовой👨🍳') con.commit()
async def register_teacher(msg: Message, state: FSMContext): print(f'{msg.from_user.full_name} нажал кнопку Добавить кл.рук.') user_id = msg.from_user.id school_id = await check_school_id(user_id) teachers = cur.execute('''Select user_id, name from users where role = ? and school = ?''', [teacher_role, school_id]).fetchall() await register_taecher_in_class(msg, teachers)
async def get_choice(month, user_id): info = cur.execute( '''SELECT d.day, c.choice FROM days d LEFT JOIN canteen_journal c ON d.id = c.day WHERE d.month = ? and c.user = ?''', [month, user_id]).fetchall() info = {day: choice for day, choice in info} return info
def create_event(self, start, end, name, event_text): """Создает ивент в EventView""" time = [start.hour, start.minute, end.hour, end.minute] t = [str(i).rjust(2, '0') for i in time] text = 'c {}:{} по {}:{} - {}'.format(*t, name) # проверка что введенный интервал времение не пересекается с временем других ивентов if self.is_normal_events(start, end): try: cur.execute('''INSERT INTO events VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)''', (self.mainwindow.day_n, *time, name, event_text)) con.commit() except Exception as e: print(e) self.mainwindow.EventView.addItem(text) return True else: create_message_window(self, 'Введите другой инервал времни')
async def text(msg: Message, state: FSMContext): school_id = await check_school_id(msg.from_user.id) classes = cur.execute('''SELECT * FROM classes WHERE school = ?''', [school_id]).fetchall() print( f'{msg.from_user.full_name} директор из школы id: {school_id} нажал кнопку классы' ) await show_classes_buttons(msg, classes)
async def text(msg: Message, state: FSMContext): text = msg.text print(f'{msg.from_user.full_name} зашел в {text} школу') shool_id = cur.execute('''SELECT id FROM schools WHERE name = ?''', [text[9:]]).fetchone()[0] await school_information(msg) await state.update_data(school_id=shool_id, start_panel=admin_panel) await ShowSchool.School.set()
async def stay_people_id(class_id): people = canteen_data[class_id]['who'] all_people = cur.execute( '''SELECT u.user_id FROM users u LEFT JOIN students s ON u.user_id = s.user WHERE class = ?''', [class_id]).fetchall() return map(lambda x: str(x[0]), filter(lambda x: x[0] not in people, all_people))