def add_new_user(user_id, group_id, group_title=None): sql_con = get_connection() cursor = sql_con.cursor() if group_title is None: group_title = get_group_events(group_id)["StudentGroupDisplayName"][7:] try: cursor.execute( """INSERT INTO groups_data (id, title) VALUES (%s, %s)""", (group_id, group_title)) except pymysql.IntegrityError: sql_con.rollback() finally: sql_con.commit() try: cursor.execute( """INSERT INTO user_data (id, group_id) VALUES (%s, %s)""", (user_id, group_id)) except pymysql.IntegrityError: sql_con.rollback() cursor.execute( """UPDATE user_data SET group_id = %s WHERE id = %s""", (group_id, user_id)) finally: sql_con.commit() cursor.execute("""DELETE FROM user_choice WHERE user_id = %s""", (user_id, )) sql_con.commit() cursor.close() sql_con.close()
def get_json_attestation(user_id): sem_dates = get_semester_dates() group_id = get_current_group(user_id)[0] req = get_group_events(group_id=group_id, from_date=sem_dates[0], to_date=sem_dates[1], lessons_type="Attestation") return req
def get_events(self, from_date=None, to_date=None, lessons_type=None): """ Method to get raw data for group from SPBU :param from_date: from date :param to_date: to date :param lessons_type: type of lessons :return: raw data :rtype: dict """ return spbu.get_group_events(self.id, from_date, to_date, lessons_type)
def add_new_user(user_id, group_id, group_title=None): sql_con = sqlite3.connect("Bot.db") # установка соединения с БД cursor = sql_con.cursor() if group_title is None: # Ищем название группы group_title = spbu.get_group_events( group_id)["StudentGroupDisplayName"][7:] try: cursor.execute("""INSERT INTO groups_data (id, title) VALUES (?, ?)""", (group_id, group_title)) # Добавляем группу except sqlite3.IntegrityError: sql_con.rollback( ) # В случае ошибки - откатываем сделанные изменения в бд finally: json_week = json.dumps(spbu.get_group_events( group_id)) # собираем инфу о группе за целую неделю cursor.execute("""UPDATE groups_data SET json_week_data = ? WHERE id = ?""", (json_week, group_id)) # Исполняем запрос к бд sql_con.commit() # подтверждаем выполненный запрос try: cursor.execute( """INSERT INTO user_data (id, group_id) VALUES (?, ?)""", (user_id, group_id )) # Получаем из бд инфу о пользователе по его id и id его группы except sqlite3.IntegrityError: sql_con.rollback() cursor.execute( """UPDATE user_data SET group_id = ? WHERE id = ?""", (group_id, user_id)) finally: sql_con.commit() cursor.execute("""DELETE FROM user_choice WHERE user_id = ?""", (user_id, )) sql_con.commit() cursor.close() sql_con.close()
def get_json_interval_data(user_id, from_date, to_date): sql_con = get_connection() cursor = sql_con.cursor() cursor.execute( """SELECT group_id FROM user_data WHERE id= %s""", (user_id, )) group_id = cursor.fetchone()[0] cursor.close() sql_con.close() json_week_data = get_group_events(group_id=group_id, from_date=from_date, to_date=to_date) return delete_symbols(json_week_data)
def test_group_events(self): group_ids = (14887, 13722, 15158) params_list = [ dict(), dict(lessons_type=spbu.consts.LessonsTypes.PRIMARY), dict(from_date=date.today(), lessons_type=spbu.consts.LessonsTypes.FINAL), dict(from_date=date.today(), to_date=date.today() + timedelta(days=10), lessons_type=spbu.consts.LessonsTypes.ALL) ] for group_id in group_ids: for params in params_list: self.assertIsInstance( spbu.get_group_events(group_id, **params), spbu.types.GroupEvents)
def reg_user(o_id, is_edu, tg_id): """ Registers or updates user :param o_id: an object id (educator or group) :type o_id: int :param is_edu: if the user is an educator :type is_edu: bool :param tg_id: the user's telegram chat id :type tg_id: int :return: the new or updated user :rtype: User """ obj = (Educator if is_edu else Group).query.get(o_id) if not obj: if is_edu: obj = Educator( id=o_id, title=spbu.get_educator_events( educator_id=o_id)["EducatorLongDisplayText"]) else: obj = Group(id=o_id, title=spbu.get_group_events( group_id=o_id)["StudentGroupDisplayName"]) db.session.add(obj) user = User.query.filter_by(tg_id=tg_id).first() if not user: user = User(tg_id=tg_id, is_educator=is_edu, current_group_id=0 if is_edu else o_id, current_educator_id=o_id if is_edu else 0) else: user.current_group_id = 0 if is_edu else o_id user.current_educator_id = o_id if is_edu else 0 user.is_educator = is_edu db.session.add(user) db.session.commit() return user
def get_json_week_data(user_id, next_week=False, for_day=None): sql_con = get_connection() cursor = sql_con.cursor() cursor.execute( """SELECT group_id FROM user_data WHERE id= %s""", (user_id, )) group_id = cursor.fetchone()[0] cursor.close() sql_con.close() if for_day: monday_date = for_day elif next_week: monday_date = get_current_monday_date() monday_date += timedelta(days=7) else: monday_date = get_current_monday_date() json_week_data = get_group_events(group_id=group_id, from_date=monday_date) return delete_symbols(json_week_data)
def get_json_week_data_api(user_id, next_week=False, for_day=None): sql_con = sqlite3.connect("Bot.db") cursor = sql_con.cursor() cursor.execute( """SELECT group_id FROM user_data WHERE id= ?""", (user_id, )) group_id = cursor.fetchone()[0] cursor.close() sql_con.close() if for_day: monday_date = for_day elif next_week: monday_date = get_current_monday_date() monday_date += timedelta(days=7) else: monday_date = get_current_monday_date() json_week_data = spbu.get_group_events( group_id=group_id, from_date=monday_date) # обращение к методу получения инфы с оф сайта return delete_symbols(json_week_data)
def start_handler(message): answer = "" if bot_name != "Spbu4UBot" and message.chat.id not in ids.values(): answer = "Это тестовый бот. Используйте @Spbu4UBot" bot.send_message(message.chat.id, answer) return if message.text == "/start": answer = "Приветствую!\n" elif message.text.split()[1].isdecimal(): answer = "Приветствую!\nДобавляю тебя в группу..." bot_msg = bot.send_message(message.chat.id, answer) try: group_id = int(message.text.split()[1]) except ValueError: answer = "Ошибка в id группы." bot.edit_message_text(answer, message.chat.id, bot_msg.message_id) message.text = "/start" start_handler(message) return try: res = spbu.get_group_events(group_id) except spbu.ApiException: answer = "Ошибка в id группы." bot.edit_message_text(answer, message.chat.id, bot_msg.message_id) message.text = "/start" start_handler(message) return group_title = res["StudentGroupDisplayName"][7:] func.add_new_user(message.chat.id, group_id, group_title) answer = "Готово!\nГруппа <b>{0}</b>".format(group_title) bot.edit_message_text(answer, message.chat.id, bot_msg.message_id, parse_mode="HTML") answer = "Главное меню\n\n" \ "{0} - информация о боте\n" \ "{1} - оценить бота\n" \ "{2} - настройки\n" \ "{3} - электрички\n" \ "{4} - <b>редактор расписания</b>\n" \ "@Spbu4u_news - новости бота".format(emoji["info"], emoji["star"], emoji["settings"], emoji["suburban"], emoji["editor"]) bot.send_message(chat_id=message.chat.id, text=answer, reply_markup=main_keyboard, parse_mode="HTML") return answer += "Загружаю список направлений..." bot_msg = bot.send_message(message.chat.id, answer) bot.send_chat_action(message.chat.id, "typing") answer = "Укажи свое направление:" divisions = spbu.get_study_divisions() division_names = [division["Name"] for division in divisions] divisions_keyboard = ReplyKeyboardMarkup(True, False) for division_name in division_names: divisions_keyboard.row(division_name) divisions_keyboard.row("Поддержка", "Завершить") data = dumps(divisions) sql_con = func.get_connection() cursor = sql_con.cursor() cursor.execute("""DELETE FROM user_choice WHERE user_id = %s""", (message.chat.id, )) sql_con.commit() cursor.execute( """INSERT INTO user_choice (user_id, divisions_json) VALUES (%s, %s)""", (message.chat.id, data)) sql_con.commit() cursor.close() sql_con.close() bot.edit_message_text(text="Готово!", chat_id=message.chat.id, message_id=bot_msg.message_id) bot.send_message(message.chat.id, answer, reply_markup=divisions_keyboard) reg_func.set_next_step(message.chat.id, "select_division")
def test_groups_events_parsing(self, call_api): group_id = 19082 group_events = spbu.get_group_events(group_id=group_id) dataset_group_events = call_api() self.assertEqual(group_events.student_group_id, dataset_group_events['StudentGroupId']) self.assertEqual(group_events.student_group_display_name, dataset_group_events['StudentGroupDisplayName']) self.assertEqual(group_events.timetable_display_name, dataset_group_events['TimeTableDisplayName']) self.assertEqual(date_to_str(group_events.previous_week_monday), dataset_group_events['PreviousWeekMonday']) self.assertEqual(date_to_str(group_events.next_week_monday), dataset_group_events['NextWeekMonday']) self.assertEqual( group_events.is_previous_week_reference_available, dataset_group_events['IsPreviousWeekReferenceAvailable']) self.assertEqual(group_events.is_next_week_reference_available, dataset_group_events['IsNextWeekReferenceAvailable']) self.assertEqual( group_events.is_current_week_reference_available, dataset_group_events['IsCurrentWeekReferenceAvailable']) self.assertEqual(group_events.week_display_text, dataset_group_events['WeekDisplayText']) self.assertEqual(date_to_str(group_events.week_monday), dataset_group_events['WeekMonday']) days = group_events.days dataset_days = dataset_group_events['Days'] self.assertEqual(len(days), len(dataset_days)) for i in range(len(days)): self.assertEqual(date_to_dt_str(days[i].day), dataset_days[i]['Day']) self.assertEqual(days[i].day_string, dataset_days[i]['DayString']) events = days[i].day_study_events dataset_events = dataset_days[i]['DayStudyEvents'] self.assertEqual(len(events), len(dataset_events)) for j in range(len(events)): self.assertEqual( events[j].study_events_timetable_kind_code, dataset_events[j]['StudyEventsTimeTableKindCode']) self.assertEqual(datetime_to_str(events[j].start), dataset_events[j]['Start']) self.assertEqual(datetime_to_str(events[j].end), dataset_events[j]['End']) self.assertEqual(events[j].subject, dataset_events[j]['Subject']) self.assertEqual(events[j].time_interval_string, dataset_events[j]['TimeIntervalString']) self.assertEqual( events[j].date_with_time_interval_string, dataset_events[j]['DateWithTimeIntervalString']) self.assertEqual( events[j].display_date_and_time_interval_string, dataset_events[j]['DisplayDateAndTimeIntervalString']) self.assertEqual(events[j].locations_display_text, dataset_events[j]['LocationsDisplayText']) self.assertEqual(events[j].educators_display_text, dataset_events[j]['EducatorsDisplayText']) self.assertEqual(events[j].has_educators, dataset_events[j]['HasEducators']) self.assertEqual(events[j].is_cancelled, dataset_events[j]['IsCancelled']) self.assertEqual(events[j].contingent_unit_name, dataset_events[j]['ContingentUnitName']) self.assertEqual(events[j].division_and_course, dataset_events[j]['DivisionAndCourse']) self.assertEqual(events[j].is_assigned, dataset_events[j]['IsAssigned']) self.assertEqual(events[j].time_was_changed, dataset_events[j]['TimeWasChanged']) self.assertEqual(events[j].locations_were_changed, dataset_events[j]['LocationsWereChanged']) self.assertEqual(events[j].educators_were_reassigned, dataset_events[j]['EducatorsWereReassigned']) self.assertEqual(events[j].elective_disciplines_count, dataset_events[j]['ElectiveDisciplinesCount']) self.assertEqual(events[j].is_elective, dataset_events[j]['IsElective']) self.assertEqual( events[j].has_the_same_time_as_previous_item, dataset_events[j]['HasTheSameTimeAsPreviousItem']) self.assertEqual( events[j].contingent_units_display_test, dataset_events[j]['ContingentUnitsDisplayTest']) self.assertEqual(events[j].is_study, dataset_events[j]['IsStudy']) self.assertEqual(events[j].all_day, dataset_events[j]['AllDay']) self.assertEqual(events[j].within_the_same_day, dataset_events[j]['WithinTheSameDay']) self._assertLocations(events[j].event_locations, dataset_events[j]['EventLocations']) self._assertEducators(events[j].educator_ids, dataset_events[j]['EducatorIds'])
def start_handler(message): answer = "" if message.text == "/start": answer = "Приветствую!\n" elif "/start" in message.text: answer = "Приветствую!\nДобавляю тебя в группу..." bot_msg = bot.send_message(message.chat.id, answer) # просим бота отправить сообщение try: group_id = int(message.text.split()[1]) except ValueError: answer = "Ошибка в id группы." bot.edit_message_text(answer, message.chat.id, bot_msg.message_id) # просим бота изменить уже отправленное сообщение message.text = "/start" start_handler(message) return try: res = spbu.get_group_events(group_id) except spbu.ApiException: answer = "Ошибка в id группы." bot.edit_message_text(answer, message.chat.id, bot_msg.message_id) message.text = "/start" start_handler(message) return group_title = res["StudentGroupDisplayName"][7:] func.add_new_user(message.chat.id, group_id, group_title) answer = "Готово!\nГруппа <b>{0}</b>".format(group_title) bot.edit_message_text(answer, message.chat.id, bot_msg.message_id, parse_mode="HTML") answer = "Главное меню\n\n" \ "{0} - информация о боте\n" \ "{1} - настройки\n".format(emoji["info"], emoji["settings"]) bot.send_message(chat_id=message.chat.id, text=answer, reply_markup=main_keyboard, parse_mode="HTML") return answer += "Загружаю список направлений..." bot_msg = bot.send_message(message.chat.id, answer) bot.send_chat_action(message.chat.id, "typing") answer = "Укажи свое направление:" divisions = spbu.get_study_divisions() division_names = [division["Name"] for division in divisions] divisions_keyboard = telebot.types.ReplyKeyboardMarkup(True, False) for division_name in division_names: divisions_keyboard.row(division_name) divisions_keyboard.row("Завершить") data = json.dumps(divisions) sql_con = sqlite3.connect("Bot.db") cursor = sql_con.cursor() cursor.execute("""DELETE FROM user_choice WHERE user_id = ?""", (message.chat.id,)) sql_con.commit() cursor.execute("""INSERT INTO user_choice (user_id, divisions_json) VALUES (?, ?)""", (message.chat.id, data)) sql_con.commit() cursor.close() sql_con.close() bot.edit_message_text(text="Готово!", chat_id=message.chat.id, message_id=bot_msg.message_id) bot.send_message(message.chat.id, answer, reply_markup=divisions_keyboard) reg_func.set_next_step(message.chat.id, "select_division")
def get_events(self, from_date=None, to_date=None, lessons_type=None): # TODO change spbu method in future return spbu.get_group_events(self.id, from_date, to_date, lessons_type)