def show_schedule(update, context): week_day = datetime.datetime.weekday( datetime.datetime.now(pytz.timezone('Etc/GMT-3'))) session = Session() user = session.query(User).filter( User.tg_chat_id == update.message.chat_id).first() if len(context.args) == 1: group_query = context.args[0] message_id = update.message.message_id + 1 context.user_data['group_query' + str(message_id)] = group_query make_group_schedule(update, context, group_query, week_day) return ConversationHandler.END elif user: group = user.group make_group_schedule(update, context, group, week_day) return ConversationHandler.END elif len(context.args) == 0: find_group(update, context) return FIND_GROUP else: return ConversationHandler.END
def get_project_themes(project_table_class): session = Session() query_result = session.query(project_table_class.name).all() project_themes = [r.name for r in query_result] session.close() return project_themes
def make_project_info(project_table_class, project_number): session = Session() bot_message = str( session.query(project_table_class).filter( project_table_class.id == project_number).first()) session.close() return bot_message
def complete_alt_login(update, context): session = Session() role = context.user_data.get('role', '-') name = context.user_data.get('name', '-') patronymic = context.user_data.get('patronymic', '-') surname = context.user_data.get('surname', '-') group = '-' post = '-' directions = '-' if role == 'student': group = context.user_data.get('group', '-') elif role == 'mentor': post = context.user_data.get('post', '-') directions = context.user_data.get('directions', '-') user = User(tg_chat_id=update.message.chat_id, role=role, name=name, surname=surname, patronymic=patronymic, group=group, post=post, directions=directions) try: schedule_notifications_job(context, user) context.job_queue.run_daily(schedule_notifications_job, time=datetime.time( hour=1, minute=0, tzinfo=pytz.timezone('Etc/GMT-3')), days=(0, 1, 2, 3, 4, 5), context=user, name='Обновить расписание') user.is_notified = True except (NoEntriesException, WentWrongException, ChoicesException): context.bot.send_message(chat_id=user.tg_chat_id, text=alt_login_replicas['notification_error']) session.add(user) context.bot.send_message( chat_id=update.message.chat_id, text=f"Здравствуйте, {user.name} {user.patronymic}. Вы авторизованы.") context.user_data.pop('role', None) context.user_data.pop('name', None) context.user_data.pop('patronymic', None) context.user_data.pop('surname', None) context.user_data.pop('group', None) context.user_data.pop('post', None) context.user_data.pop('directions', None) session.commit() session.close() return user
def remove_admin(update, context): session = Session() new_admin_id = int(update.message.text) user = session.query(User).filter(User.tg_chat_id == new_admin_id).first() if user: if user.is_admin: user.is_admin = False bot_message = f"{user.surname} {user.name} больше не администратор чат-бота" context.bot.send_message(chat_id=update.message.chat_id, text=bot_message) session.commit() session.close() else: context.bot.send_message( chat_id=update.message.chat_id, text='Этот пользователь и так не является администратором') else: context.bot.send_message( chat_id=update.message.chat_id, text= 'Такого пользователя нет в нашей базе, он не может быть администратором' ) return ConversationHandler.END
def add_admin(update, context): session = Session() try: new_admin_id = int(update.message.text) user = session.query(User).filter( User.tg_chat_id == new_admin_id).first() if user: user.is_admin = True bot_message = f"{user.surname} {user.name} теперь администратор чат-бота проектного офиса ИКТИБ" context.bot.send_message(chat_id=update.message.chat_id, text=bot_message) session.commit() session.close() else: bot_message = 'Такого пользователя нет в нашей базе. Либо введенные данные неверны, либо этот пользователь'\ ' не авторизован. Во втором случае, попросите этого человека авторизоваться через /login' context.bot.send_message(chat_id=update.message.chat_id, text=bot_message) return ConversationHandler.END except ValueError: bot_message = 'Пользовательский chat_id недействителен или неверен. Попробуйте ввести команду заново' context.bot.send_message(chat_id=update.message.chat_id, text=bot_message)
def restore_notifications(): session = Session() users = session.query(User).all() for user in users: if user.is_notified: schedule_notifications_job(dp, user) dp.job_queue.run_daily(schedule_notifications_job, time=datetime.time( hour=1, minute=0, tzinfo=pytz.timezone('Etc/GMT-3')), days=(0, 1, 2, 3, 4, 5), context=user, name='Обновить расписание') session.close()
def make_project_info_with_keyboard(project_table_class, project_number): session = Session() reply_keyboard = [] query_result = session.query(project_table_class).filter( project_table_class.id == project_number).first() bot_message = f"<b><i>{query_result.name}</i></b>\n\n" \ f"<b>Наставник</b>: {query_result.mentor}\n\n" \ f"Дополнительная информация: {query_result.additional_info or '-'}\n" \ f"Описание проекта: <a href='{query_result.description or ''}'>ссылка на документ</a>" if query_result.team_1 or query_result.team_2 or query_result.team_3: bot_message += f"\n\n<b>Команды</b>:" if query_result.team_1: reply_keyboard.append([ InlineKeyboardButton( text=str(query_result.team_1), callback_data= f'{project_buttons["first"]["team_info"]}: {project_number} {str(query_result.team_1)}' ) ]) if query_result.team_2: reply_keyboard.append([ InlineKeyboardButton( text=str(query_result.team_2), callback_data= f'{project_buttons["first"]["team_info"]}: {project_number} {str(query_result.team_2)}' ) ]) if query_result.team_3: reply_keyboard.append([ InlineKeyboardButton( text=str(query_result.team_3), callback_data= f'{project_buttons["first"]["team_info"]}: {project_number} {str(query_result.team_3)}' ) ]) session.close() return bot_message, reply_keyboard
def do_login(update, context): try: session = Session() user = session.query(User).filter( User.tg_chat_id == update.message.chat_id).first() context.bot.send_message( chat_id=update.message.chat_id, text=f"Вы уже авторизованы, {user.name} {user.patronymic}") session.close() except: if len(context.args) > 2: context.bot.delete_message(chat_id=update.message.chat_id, message_id=update.message.message_id) context.bot.send_message(chat_id=update.message.chat_id, text=auth_replicas['too_much_args']) return ConversationHandler.END elif len(context.args) >= 1: context.user_data['email'] = context.args[0] if len(context.args) == 2: context.user_data['password'] = context.args[1] context.bot.delete_message( chat_id=update.message.chat_id, message_id=update.message.message_id) return do_login_auth(update, context) context.bot.send_message(chat_id=update.message.chat_id, text=auth_replicas['enter_pass']) return LOGIN_PASSWORD else: context.bot.send_message(chat_id=update.message.chat_id, text=auth_replicas['enter_email']) return LOGIN_EMAIL
def write_team(update, context): session = Session() current_user = get_user_info(update) message = update.message.text message = f'{current_user.name} {current_user.patronymic} {current_user.surname} пишет всей вашей команде:\n' \ f'"{message}"' team_ids = map(int, context.user_data['team_id'].split(';')) for team_id in team_ids: necessary_team = session.query(Team).filter(Team.id == team_id).first() members = [ necessary_team.member_1, necessary_team.member_2, necessary_team.member_3, necessary_team.member_4, necessary_team.member_5, necessary_team.member_6, necessary_team.member_7, necessary_team.member_8 ] for member in members: if member: member = member.replace(',', '').split()[:3] surname = member[0] name = members[1] patronymic = member[2] member_account = session.query(User).filter( User.surname == surname and User.name == name and User.patronymic == patronymic).first() if member_account is not None: context.bot.send_message(chat_id=member_account.tg_chat_id, text=message) session.close() return ConversationHandler.END
def add_write_team_button(update, project_number, team, keyboard): user = get_user_info(update) if is_mentor(user=user) or user.is_admin: session = Session() mentor_projects = [] if project_number == 'fp': mentor_projects = session.query(FirstProject).filter( FirstProject.mentor == f"{user.surname} {user.name} {user.patronymic}") elif project_number == 'sp': mentor_projects = session.query(SecondProject).filter( SecondProject.mentor == f"{user.surname} {user.name} {user.patronymic}") for project in mentor_projects: if team.name in (project.team_1, project.team_2, project.team_3): keyboard.append([ InlineKeyboardButton( text='Написать команде', callback_data= f"{communication_buttons['write']['team']} {team.id}") ]) session.close() return keyboard
def do_logout(update, context): session = Session() user = session.query(User).filter( User.tg_chat_id == update.message.chat_id).first() if user: session.delete(user) session.commit() context.bot.send_message(chat_id=update.message.chat_id, text=auth_replicas['logout']) else: context.bot.send_message(chat_id=update.message.chat_id, text=auth_replicas['not_logged']) session.close()
def find_team_info(team_name='', team_id=None): session = Session() if team_id is None: query_result = session.query(Team).filter( team_name == Team.name).first() else: query_result = session.query(Team).filter(team_id == Team.id).first() session.close() return query_result
def send_students(update, context): session = Session() bot_message = update.message.text students = session.query(User).filter(User.role == 'student') admin = session.query(User).filter( User.tg_chat_id == update.message.chat_id).first() bot_message = f'{admin.name} {admin.surname} пишет:\n' \ f'"{bot_message}"' for student in students: context.bot.send_message(chat_id=student.tg_chat_id, text=bot_message) session.close() return ConversationHandler.END
def show_student_info(update, context): session = Session() query = update.callback_query student = query.data.replace(f"{project_buttons['student']}: ", "").split() surname = student[0] name = student[1] team_id = int(student[2]) project = student[-2] project_number = student[-1] user = session.query(User).filter(User.surname == surname, User.name == name, User.role == 'student').first() keyboard = [] if project == 'f': keyboard.append([ InlineKeyboardButton( text='Назад', callback_data= f'{project_buttons["first"]["team_info"]}: {project_number} {team_id}' ) ]) elif project == 's': keyboard.append([ InlineKeyboardButton( text='Назад', callback_data= f'{project_buttons["first"]["team_info"]}: {project_number} {team_id}' ) ]) keyboard = InlineKeyboardMarkup(keyboard) if user: bot_message = f"<b><i>{user.surname} {user.name} {user.patronymic}</i></b>\n\n" \ f"<u>Роль</u>: студент\n" \ f"<u>Группа</u>: {user.group}\n" \ f"<u>Почта</u>: *конфиденциально*\n" \ f"<u>Телефон</u>: *конфиденциально*" context.bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=bot_message, reply_markup=keyboard) else: student = ' '.join(student[0:2]) bot_message = f"Имя - <b>{student}</b>\n\n" \ f"У нас нет информации об этом студенте" context.bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=bot_message, reply_markup=keyboard) session.close()
def do_login_auth(update, context): login_data = { 'email': context.user_data['email'], 'password': context.user_data['password'] } login_result = requests.post(url=LOGIN_URL, data=login_data).json() if login_result['auth']: session = Session() user_info = login_result['user'] if user_info['role'] == 'student': user = User(tg_chat_id=update.message.chat_id, role=user_info['role'], surname=user_info['surname'], name=user_info['name'], patronymic=user_info['patronymic'], group=user_info['group'], email=user_info['email'], phone=user_info['phone'], post='', directions='', is_notified=True, is_admin=False) elif user_info['role'] == 'mentor': user = User(tg_chat_id=update.message.chat_id, role=user_info['role'], surname=user_info['surname'], name=user_info['name'], patronymic=user_info['patronymic'], group='', email=user_info['email'], phone=user_info['phone'], post=user_info['post'], directions=user_info['directions']) else: context.bot.send_message( chat_id=update.message.chat_id, text=auth_replicas['something_gone_wrong']) return ConversationHandler.END try: schedule_notifications_job(context, user) context.job_queue.run_daily(schedule_notifications_job, time=datetime.time( hour=1, minute=0, tzinfo=pytz.timezone('Etc/GMT-3')), days=(0, 1, 2, 3, 4, 5), context=user, name='Обновить расписание') user.is_notified = True except (NoEntriesException, WentWrongException, ChoicesException): context.bot.send_message(chat_id=user.tg_chat_id, text=auth_replicas['notification_error']) session.add(user) session.commit() context.bot.send_message( chat_id=update.message.chat_id, text= f"Здравствуйте, { user.name } { user.patronymic }. Вы авторизованы." ) session.close() else: if 'message' in context.user_data.keys(): if 'message' == "User didn't activated account.": context.bot.sendMessage( chat_id=update.message.chat_id, text=auth_replicas['not_activated_account']) else: context.bot.sendMessage(chat_id=update.message.chat_id, text=auth_replicas['something_gone_wrong']) del context.user_data['email'] del context.user_data['password'] return ConversationHandler.END
def get_user_info(update): session = Session() user = session.query(User).filter( User.tg_chat_id == update.message.chat_id).first() session.close() return user