def sports_group_desc(message): ctx.push() cid = message.chat.id text=message.text.replace('/','') bot.send_message(cid, sports_gr[text]['sport_in'], reply_markup=keyboard_commands) ctx.pop() return 0
def create_sport_group(): if current_user.get_role() != 'admin': return redirect(url_for('index.html')) form = NewSportGroupForm() if form.validate_on_submit(): sportgroup = SportsGroup(name=form.name.data, rus_name=form.rus_name.data, rank=form.rank.data) db.session.add(sportgroup) db.session.commit() ctx.push() telegrambot.sports_gr, telegrambot.sports_gr_commands = telegrambot.create_sports_group_description( ) ctx.pop() flash('New sport group \"{}\" have been saved.'.format(form.name.data)) return redirect(url_for('create_sport_group')) elif request.method == 'GET': pass return render_template('create_sport_group.html', title='Create Sport Group', form=form)
def command_start(message): ctx.push() cid = message.chat.id usname = message.from_user.username text = message.text.replace('/','') if usname is None: bot.send_message(cid, "Наш бот работает c использованием Telegram username. \n Пожалуйста, заполни это поле в настройках Telegram и повторно вызови команду /start .") return 0 if not User.query.filter_by(name=usname).first(): # if user hasn't used the "/start" command yet: cdo(User(name=usname, id_originsystem=gi(OriginSystem, messenger))) cdo(OriginSystemUsers(system_username=usname, system_userid=cid, id_users=gi(User, usname), id_originsystem=gi(OriginSystem, messenger))) #bot.send_message(cid, "Привет! Теперь мы познакомились ) \n Выбери команду внизу или нажми /help для вызова списка доступных команд", reply_markup=keyboard_commands) bot.send_message(cid, "Привет! Пришли имя для отображения в рейтинге (не более 30 символов)") ctx.pop() return 0 else: user_info = User.query.filter_by(name=usname).first() if user_info.display_name == 'bot_anonymous': cur_session = check_user_seesion(user_info.id) if cur_session is not None: session_disabled(user_info.id) cdo(UserSession(id_users=user_info.id, id_botcommand=botCommands[text]['id'])) bot.send_message(cid, "Привет! Пришли имя для отображения в рейтинге (не более 30 символов)") ctx.pop() return 0 bot.send_message(cid, "Привет, {}! \n Выбери команду внизу или нажми /help для вызова списка доступных команд.".format(user_info.display_name), reply_markup=keyboard_commands) ctx.pop() return 0
def command_delete(message): ctx.push() day_deep = 7 # определяет глубину записей за 7 дней от сегодня cid = message.chat.id text=message.text.replace('/','') user_id = OriginSystemUsers.query.filter_by(system_userid=str(cid)).first().id_users cur_session = check_user_seesion(user_id) if cur_session is not None: session_disabled(user_id) cdo(UserSession(id_users=user_id, id_botcommand=botCommands[text]['id'])) current_date = date.today() begin_date = current_date + timedelta(days = ((-1)*day_deep)) result = user_records_format(user_records(user_id, begin_date, current_date)) if result is None: bot.send_message(cid, 'За последние {} дней не было внесено новых данных'.format(day_deep), reply_markup=keyboard_commands) ctx.pop() return 0 message_text = 'В системе за 7 дней есть записи: \n '+result + '\n для удаления записи пришли ее ID. например, 5' bot.send_message(cid, message_text, reply_markup=keyboard_commands) ctx.pop() return 0
def command_top50(message): ctx.push() cid = message.chat.id current_date = date.today() begin_date = current_date + timedelta(days = ( 1-current_date.day)) message_text = top_users(users_total_score(current_date,begin_date,'all', number=50)) bot.send_message(cid, message_text, reply_markup=keyboard_commands) ctx.pop() return 0
def command_add(message): ctx.push() cid = message.chat.id text=message.text.replace('/','') user_id = OriginSystemUsers.query.filter_by(system_userid=str(cid)).first().id_users cur_session = check_user_seesion(user_id) if cur_session is not None: session_disabled(user_id) cdo(UserSession(id_users=user_id, id_botcommand=botCommands[text]['id'])) bot.send_message(cid, sports_gr_commands, reply_markup=keyboard_commands) ctx.pop() return 0
def sport_edit(sport): categories_sp = [(str(c.id), str(c.name)) for c in SportsGroup.query.all()] categories_place = [(str(c.id), str(c.name)) for c in Place.query.all()] form = SportEdit(request.form) form.sport_group.choices = categories_sp form.place.choices = categories_place if form.validate_on_submit(): sport = Sports.query.filter_by(name=sport).first() sport.name = form.name.data sport.rus_name = form.rus_name.data sport.rank = form.rank.data survey = Surveys.query.filter_by(sports=sport).first() survey.name = form.name.data sport_coeff = SportsCoeff.query.filter_by(sport=sport).first_or_404() sport_coeff.coeff1 = form.coeff1.data sport_coeff.coeff2 = form.coeff2.data sport_coeff.criteria = form.criteria.data sport_coeff.criteria_description = form.criteria_desc.data sport_coeff.bottom = form.bottom.data sport_coeff.upper = form.upper.data sport.sportsplace.append( Place.query.filter_by(id=form.place.data).first()) db.session.commit() try: sport.sportsplace.append( Place.query.filter_by(id=form.place.data).first()) db.session.commit() except: pass ctx.push() telegrambot.sports, telegrambot.sport_text, telegrambot.sport_commands = telegrambot.create_sport_description( ) telegrambot.sports_gr, telegrambot.sports_gr_commands = telegrambot.create_sports_group_description( ) telegrambot.sport_coef = telegrambot.create_sport_coeff() ctx.pop() flash('Sport \"{}\" has been updated.'.format(form.name.data)) return redirect(url_for('sports_all')) return render_template('sport_edit.html', title='Sport Edit', form=form)
def command_myresult(message): ctx.push() cid = message.chat.id user_id = OriginSystemUsers.query.filter_by(system_userid=str(cid)).first().id_users current_date = date.today() begin_date = current_date + timedelta(days = ( 1-current_date.day)) message_text = users_total_score_format(users_total_score(current_date,begin_date,user_id)) message_text_bysport = user_analysis_format_all_sports( user_analysis_for_period( current_date, begin_date,user_id)) message_text +=message_text_bysport bot.send_message(cid, message_text, reply_markup=keyboard_commands) ctx.pop() return 0
def group_coeff_up(): group_coeff = GroupCoeff.query.first() form = GroupCoeffForm(request.form) if form.validate_on_submit(): group_coeff = GroupCoeff.query.first() group_coeff.description = form.description.data group_coeff.coeff = form.value.data db.session.commit() ctx.push() telegrambot.group_coef = GroupCoeff.query.first().coeff ctx.pop() flash('Coefficient for group has been saved.') return redirect(url_for('sports_all')) return render_template('group_coeff.html', title='Group Coefficient', form=form)
def place_edit(place): form = PlaceForm(request.form) if form.validate_on_submit(): place = Place.query.filter_by(name=place).first() place.name = form.name.data place.url = form.url.data db.session.commit() ctx.push() telegrambot.places, telegrambot.keyboard_places = telegrambot.place() ctx.pop() flash('Place \"{}\" has been updated.'.format(form.name.data)) return redirect(url_for('places')) return render_template('sport_edit.html', title='Place Edit', form=form)
def places(): result = Place.query.filter_by(is_active=True).all() form = PlaceForm() if form.validate_on_submit(): place = Place(name=form.name.data, url=form.url.data) db.session.add(place) db.session.commit() ctx.push() telegrambot.places, telegrambot.keyboard_places = telegrambot.place() telegrambot.sports, telegrambot.sport_text, telegrambot.sport_commands = telegrambot.create_sport_description( ) ctx.pop() flash('New place was added') return render_template('places.html', title='Place', form=form, result=result) return render_template('places.html', title='Places', form=form, result=result)
def command_sport(message): ctx.push() cid=message.chat.id user_id = OriginSystemUsers.query.filter_by(system_userid=str(cid)).first().id_users cur_session = check_user_seesion(user_id) if cur_session is None: bot.send_message(cid, "Тебе для начала нужно выбрать команду. \n Для вызова списка доступных команд воспользуйся командой /help", reply_markup=keyboard_commands) ctx.pop() return 0 surveys_id = Surveys.query.filter_by(name=message.text.replace('/','')).first().id if current_survey_for_user(user_id) is not None: current_survey_all_obj_disable(user_id) cdo(CurrentSurvey( id_surveys=surveys_id, id_users=user_id, user_time=datetime.fromtimestamp((int(message.date))).strftime('%Y-%m-%d'), question_quantity=qn(Surveys.query.filter_by(name=message.text.replace('/','')).first().id) )) if cur_session.id_botcommand == botCommands['add']['id']: cdo(CurrentQuestion( id_currentsurvey=CurrentSurvey.query.filter_by(id_users=user_id).order_by(CurrentSurvey.timestamp.desc()).first().id, id_surveyquestion=SurveysQuestion.query.filter_by(id_surveys=surveys_id, question_index=1).first().id )) if cur_session.id_botcommand == botCommands['add_to_date']['id']: cdo(CurrentQuestion( id_currentsurvey=CurrentSurvey.query.filter_by(id_users=user_id).order_by(CurrentSurvey.timestamp.desc()).first().id, id_surveyquestion=SurveysQuestion.query.filter_by(id_surveys=surveys_id, question_index=0).first().id )) bot.send_message(cid, cq(user_id), reply_markup=keyboard_commands) current_question_flag_update(user_id, 'questionsend', 1) ctx.pop() return 0
def correct_analytical_result(user_id, user_name, date): ctx.push() base_path = Path(__file__).parent file_path = (base_path / "../file_name.json").resolve() #credentials path scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name(file_path, scope) gs = gspread.authorize(credentials) book = gs.open(GoogleConfig.GOOGLE_BOOK) #date=datetime.utcnow().strftime('%Y-%m-%d') filter_query = ('select u.name as Usern, sr.date as TrDate, SUM(sr.score) as tsum '+ ' from surveyresult as sr join users as u on sr.id_users=u.id '+ ' join surveys as sur on sr.id_surveys=sur.id where sr.date=\'{}\' and u.id = {} '+ ' group by(u.name, sr.date) order by 1,2;').format(date, user_id) final = db.engine.execute(filter_query) date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S' ) wks=book.worksheet(GoogleConfig.GOOGLE_LIST) gs_user =wks.find(user_name) gs_date = wks.find(date.strftime('%Y-%m-%d')) if final.rowcount == 0: wks.update_cell(gs_user.row, gs_date.col, 0) ctx.pop() return 0 else: for item in final: wks.update_cell(gs_user.row, gs_date.col, item.tsum) ctx.pop() return 0
def validate_sport_form(): categories_sp = [(str(c.id), str(c.name)) for c in SportsGroup.query.all()] categories_place = [(str(c.id), str(c.name)) for c in Place.query.all()] form = NewSportForm(request.form) form.sport_group.choices = categories_sp form.place.choices = categories_place if form.validate_on_submit(): print(form.place.data) sport = Sports(name=form.name.data, rus_name=form.rus_name.data, rank=form.rank.data, id_sportsgroup=int(form.sport_group.data)) survey = Surveys(name=form.name.data, sports=sport) question_0 = SurveysQuestion( survey_question= 'Введите дату тренировки в формате мм.дд. Пример, 08.17', question_index=0, parameter='date', surveys=survey, id_questiontypes=1) question_1 = SurveysQuestion(survey_question=form.question_1.data, question_index=1, parameter=form.parameter_1.data, surveys=survey, id_questiontypes=1) question_2 = SurveysQuestion(survey_question=form.question_2.data, question_index=2, parameter=form.parameter_2.data, surveys=survey, id_questiontypes=1) if form.criteria.data is None: coeffs = SportsCoeff(criteria_description=form.criteria_desc.data, criteria=1, coeff1=form.coeff1.data, coeff2=form.coeff1.data, sport=sport, bottom=form.bottom.data, upper=form.bottom.data) else: coeffs = SportsCoeff(criteria_description=form.criteria_desc.data, criteria=form.criteria.data, coeff1=form.coeff1.data, coeff2=form.coeff2.data, sport=sport, bottom=form.bottom.data, upper=form.bottom.data) db.session.add(sport) sport.sportsplace.append( Place.query.filter_by(id=form.place.data).first()) db.session.add(survey) db.session.add(question_0) db.session.add(question_1) db.session.add(question_2) db.session.add(coeffs) db.session.commit() flash('New sport \"{}\" has been saved.'.format(form.name.data)) ctx.push() telegrambot.survey_questions = telegrambot.create_survey_questions() telegrambot.sports, telegrambot.sport_text, telegrambot.sport_commands = telegrambot.create_sport_description( ) telegrambot.sport_coef = telegrambot.create_sport_coeff() ctx.pop() return redirect(url_for('create_sport')) return render_template('sport_create.html', title='Sport Create', form=form)
def command_sport_desc(message): ctx.push() cid=message.chat.id bot.send_message(cid, sport_text, reply_markup=keyboard_commands) ctx.pop() return 0
def command_help(message): ctx.push() cid = message.chat.id bot.send_message(cid, help_text) ctx.pop() return 0
def analytical_result(): ctx.push() base_path = Path(__file__).parent file_path = (base_path / "../file_name.json").resolve() #credentials path scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name(file_path, scope) gs = gspread.authorize(credentials) book = gs.open(GoogleConfig.GOOGLE_BOOK) date=datetime.utcnow().strftime('%Y-%m-%d') filter_query = 'select u.name as Usern, sr.date as TrDate, SUM(sr.score) as tsum from surveyresult as sr join users as u on sr.id_users=u.id join surveys as sur on sr.id_surveys=sur.id where sr.date=\'{}\' group by(u.name, sr.date) order by 1,2;'.format(date) cross_query = 'select * from crosstab ($${}$$) as final_pivot (usern character varying(120), score double precision);'.format(filter_query) final = db.engine.execute(cross_query) if final.rowcount == 0: Timer(300.0, analytical_result).start() return 0 wks=book.worksheet(GoogleConfig.GOOGLE_LIST) gs_users =list(wks.col_values(1)) last_row = len(gs_users) extract ={} for item in final: if item.usern not in gs_users: wks.update_cell(last_row+1,1, item.usern) last_row +=1 extract[item.usern]=float(item.score) gs_users =list(wks.col_values(1)) last_col = len(list(wks.row_values(1))) if wks.cell(1, last_col).value==date: last_col -=1 range_label_letter = rowcol_to_a1(1,int(last_col+1))[1] user_objects = wks.range(range_label_letter+'1:'+range_label_letter+str(last_row)) for j in range(len(gs_users)): if gs_users[j] in extract.keys(): user_objects[j].value=extract[gs_users[j]] else: user_objects[j].value =0 user_objects[0].value=date wks.update_cells(user_objects) Timer(300.0, analytical_result).start() ctx.pop()
def get_text_messages(message): ctx.push() cid = message.chat.id user_id = OriginSystemUsers.query.filter_by(system_userid=str(cid)).first().id_users cur_session = check_user_seesion(user_id) if cur_session is None: bot.send_message(cid, "Тебе для начала нужно выбрать команду. \n Для вызова списка доступных команд воспользуйся командой /help", reply_markup=keyboard_commands) ctx.pop() return 0 if message.text[0] == '/': bot.send_message(cid, "Тебе необходимо выбрать сначала команду из доступных. \n Для списка доступных команд воспользуйся \n /help", reply_markup=keyboard_commands) ctx.pop() return 0 if cur_session.id_botcommand == botCommands['add']['id']: cur_survey = CurrentSurvey.query.filter_by( id_users=user_id, state=0 ).order_by(CurrentSurvey.timestamp.desc()).first() current_question = CurrentQuestion.query.filter_by( id_currentsurvey=cur_survey.id, state=0, answerreceive=0).order_by( CurrentQuestion.id.desc()).first() question_base=SurveysQuestion.query.filter_by( id=current_question.id_surveyquestion).first() survey = Surveys.query.filter_by(id=cur_survey.id_surveys).first() users_number = User.query.filter_by(is_active=True).count() if question_base.question_index == 1: try: float(message.text) except: bot.send_message(cid, "Тебе необходимо прислать ответ в чиловом формате, например 5.4", reply_markup=keyboard_commands) ctx.pop() return 0 if question_base.question_index == 2: try: int(message.text) except: bot.send_message(cid, "Тебе необходимо прислать ответ в целочисленном формате, например 5", reply_markup=keyboard_commands) ctx.pop() return 0 if question_base.question_index == 3: if message.text in (places.values()): pass else: bot.send_message(cid, "Выбери из доступных (см. клавиатуру внизу)", reply_markup=keyboard_places) ctx.pop() return 0 if current_question.reply ==0 and question_base.question_index == 1: if float(message.text) < sport_coef[survey.name]['bottom'] or float(message.text) > sport_coef[survey.name]['upper']: bot.send_message(cid, 'Пожалуйстаб проверь, что значение введено правильно. \n Еще раз отправь ответ на вопрос', reply_markup=keyboard_commands) cur_question_reply_flag(current_question.id) ctx.pop() return 0 if current_question.reply ==0 and question_base.question_index == 2: if float(message.text) > users_number: bot.send_message(cid, 'Пожалуйстаб проверь, что значение введено правильно (Нас сейчас {} спортсменов). \n Еще раз отправь ответ на вопрос'.format(users_number), reply_markup=keyboard_commands) cur_question_reply_flag(current_question.id) ctx.pop() return 0 current_question_answer_proccess(user_id, message.text) current_question_flag_update(user_id, 'state', 1) current_survey_step_update(user_id) while cur_survey.step<(cur_survey.question_quantity-1): #костыль -1 cdo(CurrentQuestion( id_currentsurvey=cur_survey.id, id_surveyquestion=SurveysQuestion.query.filter_by( id_surveys=survey.id, question_index=question_base.question_index+1 ).first().id )) if (question_base.question_index+1)==3: bot.send_message(cid, cq(user_id), reply_markup=keyboard_places) else: bot.send_message(cid, cq(user_id), reply_markup=keyboard_commands) current_question_flag_update(user_id, 'questionsend', 1) ctx.pop() return 0 current_survey_state_update(user_id, cur_survey.id) current_user_session_upgrade(user_id) db.session.commit() question = CurrentQuestion.query.filter_by(id_currentsurvey=cur_survey.id).order_by(CurrentQuestion.id) sport_name = survey.name if float(question[0].result) < sport_coef[sport_name]['cr']: score=(1+group_coef*int(question[1].result))*(float(question[0].result)*sport_coef[sport_name]['c1']) else: score =(1+group_coef*int(question[1].result))*(float(question[0].result)*sport_coef[sport_name]['c2']) if cur_survey.question_quantity ==4: id_place = Place.query.filter_by(name=question[2].result).first().id else: id_place=1 cdo(SurveyResult( parameter_1=abs(float(question[0].result)), id_quest_1=question[0].id_surveyquestion, parameter_2=abs(int(question[1].result)), id_quest_2=question[1].id_surveyquestion, date=cur_survey.user_time, id_users=user_id, id_currentsurvey=cur_survey.id, id_surveys=cur_survey.id_surveys, score=round(score,1), id_place=id_place )) bot.send_message(cid, 'Твои данные внесены, получено {} баллов! \n Если ты хочешь добавить еще тренировку, нажми /add'.format(round(score,1)), reply_markup=keyboard_commands) ctx.pop() return 0 if cur_session.id_botcommand == botCommands['add_to_date']['id']: cur_survey = CurrentSurvey.query.filter_by( id_users=user_id, state=0 ).order_by(CurrentSurvey.timestamp.desc()).first() current_question = CurrentQuestion.query.filter_by( id_currentsurvey=cur_survey.id, state=0, answerreceive=0).order_by( CurrentQuestion.id.desc()).first() question_base=SurveysQuestion.query.filter_by( id=current_question.id_surveyquestion).first() survey = Surveys.query.filter_by(id=cur_survey.id_surveys).first() if question_base.question_index==0: new_date = findall(r'(\d+)', message.text) try: new_date = '{}-{}-{}'.format(date.today().year, new_date[0], new_date[1]) new_date=datetime.strptime(new_date, '%Y-%m-%d') except: bot.send_message(cid, ('Дата введена в неправильно формате! \n'+ 'Правильный формат месяц.день\n'+ 'Пример: 08.17'), reply_markup=keyboard_commands) ctx.pop() return 0 if new_date.date() < (date.today() + timedelta(days = (-10))) or new_date.date() > date.today(): bot.send_message(cid, ('Дата не может быть больше текущей даты: {} \n, или меньше, чем {} \n '.format((date.today()),(date.today() + timedelta(days = (-10))))+ 'Пришли дату повторно'), reply_markup=keyboard_commands) ctx.pop() return 0 current_question_answer_proccess(user_id, new_date) current_question_flag_update(user_id, 'state', 1) current_survey_step_update(user_id) cdo(CurrentQuestion( id_currentsurvey=cur_survey.id, id_surveyquestion=SurveysQuestion.query.filter_by( id_surveys=survey.id, question_index=question_base.question_index+1 ).first().id )) bot.send_message(cid, cq(user_id), reply_markup=keyboard_commands) current_question_flag_update(user_id, 'questionsend', 1) ctx.pop() return 0 if question_base.question_index==1: try: float(message.text) except: bot.send_message(cid, "Тебе необходимо прислать ответ в чиcловом формате, например 5.4", reply_markup=keyboard_commands) ctx.pop() return 0 if question_base.question_index==2: try: int(message.text) except: bot.send_message(cid, "Тебе необходимо прислать ответ в чиcловом формате, например 5", reply_markup=keyboard_commands) ctx.pop() return 0 if question_base.question_index == 3: if message.text in (places.values()): pass else: bot.send_message(cid, "Выбери из доступных (см. клавиатуру внизу)", reply_markup=keyboard_places) ctx.pop() return 0 users_number = User.query.filter_by(is_active=True).count() if current_question.reply ==0 and question_base.question_index == 1: if float(message.text) < sport_coef[survey.name]['bottom'] or float(message.text) > sport_coef[survey.name]['upper']: bot.send_message(cid, 'Пожалуйстаб проверь, что значение введено правильно. \n Еще раз отправь ответ на вопрос', reply_markup=keyboard_commands) cur_question_reply_flag(current_question.id) ctx.pop() return 0 if current_question.reply ==0 and question_base.question_index == 2: if float(message.text) > users_number: bot.send_message(cid, 'Пожалуйстаб проверь, что значение введено правильно (Нас сейчас {} спортсменов). \n Еще раз отправь ответ на вопрос'.format(users_number), reply_markup=keyboard_commands) cur_question_reply_flag(current_question.id) ctx.pop() return 0 current_question_answer_proccess(user_id, message.text) current_question_flag_update(user_id, 'state', 1) current_survey_step_update(user_id) while cur_survey.step<cur_survey.question_quantity: cdo(CurrentQuestion( id_currentsurvey=cur_survey.id, id_surveyquestion=SurveysQuestion.query.filter_by( id_surveys=survey.id, question_index=question_base.question_index+1 ).first().id )) if (question_base.question_index+1)==3: bot.send_message(cid, cq(user_id), reply_markup=keyboard_places) else: bot.send_message(cid, cq(user_id), reply_markup=keyboard_commands) current_question_flag_update(user_id, 'questionsend', 1) ctx.pop() return 0 current_survey_state_update(user_id, cur_survey.id) current_user_session_upgrade(user_id) db.session.commit() question = CurrentQuestion.query.filter_by(id_currentsurvey=cur_survey.id).order_by(CurrentQuestion.id) sport_name = survey.name if float(question[1].result) < sport_coef[sport_name]['cr']: score=(1+group_coef*int(question[2].result))*(float(question[1].result)*sport_coef[sport_name]['c1']) else: score =(1+group_coef*int(question[2].result))*(float(question[1].result)*sport_coef[sport_name]['c2']) if cur_survey.question_quantity ==4: id_place = Place.query.filter_by(name=question[3].result).first().id else: id_place=1 cdo(SurveyResult( parameter_1=abs(float(question[1].result)), id_quest_1=question[1].id_surveyquestion, parameter_2=abs(int(question[2].result)), id_quest_2=question[2].id_surveyquestion, date=question[0].result, id_users=user_id, id_currentsurvey=cur_survey.id, id_surveys=cur_survey.id_surveys, score=round(score,1), id_place = id_place )) bot.send_message(cid, 'Твои данные внесены, получено {} баллов! \n Если ты хочешь добавить еще тренировку, нажми /add'.format(round(score,1)), reply_markup=keyboard_commands) try: correct_analytical_result(user_id,User.query.filter_by(id=user_id).first().name,question[0].result) except: print('Google not update, CurrentSurvey ID={}'.format(cur_survey.id)) ctx.pop() return 0 if cur_session.id_botcommand == botCommands['delete']['id']: try: int(message.text) except: bot.send_message(cid, "Тебе необходимо прислать ответ в целочисленном формате, например, 5", reply_markup=keyboard_commands) ctx.pop() return 0 current_date = date.today() begin_date = current_date + timedelta(days = (-5)) #result = user_records(user_id, begin_date, current_date) if int(message.text) in [item[0] for item in user_records(user_id,begin_date, current_date)]: record_date = datetime.strftime(SurveyResult.query.filter_by(id=int(message.text)).first().date, '%Y-%m-%d %H:%M:%S') user_record_delete(int(message.text), user_id) current_user_session_upgrade(user_id) db.session.commit() bot.send_message(cid, ("ID {} удалена").format(message.text), reply_markup=keyboard_commands) try: correct_analytical_result(user_id, User.query.filter_by(id=user_id).first().name,record_date) except: print('Google not update, CurrentSurvey ID={}'.format(cur_survey.id)) ctx.pop() return 0 else: bot.send_message(cid, "Тебе необходимо прислать ID из присланного списка", reply_markup=keyboard_commands) ctx.pop() return 0 ctx.pop() return 0 if cur_session.id_botcommand == botCommands['start']['id']: user_display_name_update(user_id, message.text) current_user_session_upgrade(user_id) db.session.commit() bot.send_message(cid, "Привет, {}! \n Выбери команду внизу или нажми /help для вызова списка доступных команд." .format(message.text), reply_markup=keyboard_commands) ctx.pop() return 0