def process_photo(message): user = User(message.from_user) # json.dump(str(message), open('tmp.json', 'w')) if message.content_type != 'photo': msg = bot.send_message( message.chat.id, f'Не, мне нужна фотография', ) bot.register_next_step_handler(msg, process_photo) return file_info = bot.get_file(message.photo[-1].file_id) print(file_info) downloaded_file = bot.download_file(file_info.file_path) tmp = file_info.file_path.split('/') file_path = tmp[0] + '/' + user.id + '_' + tmp[1] with open(file_path, 'wb') as out: out.write(downloaded_file) user.photos.append(file_path) user.save() bot.send_message( message.chat.id, f'{user.preferred_name}, спасибо, фотка сохранена под именем: {file_path}' ) bot.send_message( message.chat.id, f'\nНа этом пока всё! Можно начать заново \n/start\n или показать информацию о себе \n/self\n можно также удалить всю информацию о себе \n/purge' )
def process_greetings_step(message): try: user = User(message.from_user) if message.text == 'Ye, sure!': user.preferred_name = user.first_name user.save() msg = bot.send_message(message.chat.id, f'How old are you, {user.preferred_name}?', reply_markup=types.ReplyKeyboardRemove()) bot.register_next_step_handler(msg, process_age_step) elif message.text == 'No, with surname please': msg = bot.send_message(message.chat.id, f'How old are you, {user.preferred_name}?', reply_markup=types.ReplyKeyboardRemove()) bot.register_next_step_handler(msg, process_age_step) elif message.text == 'No, I\'ll tell you how': msg = bot.reply_to(message, 'Ok, I\'m listening...', reply_markup=types.ReplyKeyboardRemove()) bot.register_next_step_handler(msg, process_greetings_step_other) else: raise Exception() except Exception as e: print(e) bot.send_sticker(message.chat.id, 'CAADAgADKAMAAoZALgI8Cc13uyaJLhYE') bot.reply_to(message, 'oooops')
def purge(message): user = User(message.from_user) if user.existed: user.purge() bot.send_message(message.chat.id, 'You were deleted') else: bot.send_message(message.chat.id, 'Nothing to delete')
def test_reminfer_not_sent_if_registered_today(self): startdate = '2014-01-23' u = User(email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 0)
def process_sex_step(message): try: sex = message.text user = User(message.from_user) if (sex == u'Male') or (sex == u'Female'): user.sex = sex user.save() else: raise Exception() bot.send_message( message.chat.id, 'Nice to meet you, ' + user.preferred_name + '\n Age:' + str(user.age) + '\n Sex:' + user.sex) bot.send_sticker(message.chat.id, 'CAADAgADJgMAAoZALgIZC2GLq2N1rhYE') bot.send_message( message.chat.id, f'\nOk, {user.preferred_name}, Let\'s start a small survey now!\n') markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) button_geo = types.KeyboardButton(text='Отправить местоположение', request_location=True) markup.add(button_geo) msg = bot.send_message( message.chat.id, f'{user.preferred_name}, где ты находишься? (Нажми на кнопку, чтобы отправить геолокацию)', reply_markup=markup) bot.register_next_step_handler(msg, process_location) except Exception as e: print(e) bot.send_sticker(message.chat.id, 'CAADAgADKAMAAoZALgI8Cc13uyaJLhYE') bot.reply_to(message, 'oooops')
def test_displays_confirm_page(self): u = User(email='*****@*****.**') u.save() (rand, hash) = make_token_args(u) response = self.client.get(reverse('diary:confirm_withdraw', args=(rand, hash))) self.assertContains(response, 'Confirm withdrawl')
def test_sends_registration_email(self): u = User(email='*****@*****.**') u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1) self.assertRegexpMatches(mail.outbox[0].body, 'R/([0-9A-Za-z]+)-(.+)/')
def post_survey(self, values): u = User(email='*****@*****.**') u.save() (rand, hash) = make_token_args(u) self.client.get(reverse('survey:survey2', args=(rand, hash))) response = self.client.post(reverse('survey:record2'), values) return response
def test_registration_with_token_displays_page(self): u = User(email='*****@*****.**') u.save() (rand, hash) = make_token_args(u) response = self.client.get(reverse('diary:register', args=(rand, hash))) self.assertEqual(response.status_code, 200) self.assertContains(response, 'To register and create')
def process_q3(message): user = User(message.from_user) user.q3 = message.text user.save() msg = bot.send_message( message.chat.id, f'\n{user.preferred_name}, ты молодец!\nА теперь отправь мне красивую фотографию', reply_markup=types.ReplyKeyboardRemove()) bot.register_next_step_handler(msg, process_photo)
def test_does_not_send_email_twice(self): u = User(email='*****@*****.**',) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1) mail.outbox = [] self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 0)
def test_different_reminder_sent_if_registered_on_non_diary_day(self): startdate = '2014-01-21' u = User(email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1) self.assertRegexpMatches(mail.outbox[0].subject, 'your first entry') self.assertRegexpMatches(mail.outbox[0].body, 'first diary entry') self.assertRegexpMatches(mail.outbox[0].body, 'D/([0-9A-Za-z]+)-(.+)/')
def test_sends_reminder(self): startdate = '2014-01-16' u = User(email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1) self.assertRegexpMatches(mail.outbox[0].subject, 'your new weekly entry') self.assertRegexpMatches(mail.outbox[0].body, 'next diary entry') self.assertRegexpMatches(mail.outbox[0].body, 'D/([0-9A-Za-z]+)-(.+)/')
def test_confirmed_page_set_withdrawn(self): u = User(email='*****@*****.**') u.save() (rand, hash) = make_token_args(u) response = self.client.get(reverse('diary:withdraw', args=(rand, hash))) self.assertContains(response, 'Withdrawl confirmed') u = User.objects.latest('id') self.assertTrue(u.withdrawn)
def test_need_valid_link(self): response = self.client.get(reverse('survey:survey2', args=('foo', 'bar'))) self.assertEqual(response.status_code, 200) self.assertContains(response, 'try clicking the link in the email again') u = User(email='*****@*****.**') u.save() (rand, hash) = make_token_args(u) response = self.client.get(reverse('survey:survey2', args=(rand, hash))) self.assertEqual(response.status_code, 200) self.assertContains(response, 'University of Manchester')
def process_q1(message): user = User(message.from_user) user.q1 = message.text user.save() markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) markup.add('Да', 'Нет') msg = bot.send_message( message.chat.id, f'Круто, мой любимый отдел, кстати! ;)\nА выделяется ли стеллаж с безглютеновой продукцией от остальных стеллажей?', reply_markup=markup) bot.register_next_step_handler(msg, process_q2)
def test_startdate_over_12_weeks_ago_is_an_error(self): u = User(email='*****@*****.**', startdate=timezone.now()) u.save() (rand, hash) = make_token_args(u) with patch( 'diary.views.SurveyDate') as mock: patched_date = mock.return_value patched_date.get_week_from_startdate.return_value = 13 response = self.client.get(reverse('diary:questions', args=(rand, hash))) response = self.client.get(reverse('diary:questions', args=(rand, hash))) self.assertContains(response, 'There are no more diary entries')
def test_questions_page_displays_correct_week(self): u = User(email='*****@*****.**', startdate=timezone.now()) u.save() (rand, hash) = make_token_args(u) with patch( 'diary.views.SurveyDate') as mock: patched_date = mock.return_value patched_date.is_diary_day.return_value = True for i in range(1, 12): patched_date.get_week_from_startdate.return_value = i response = self.client.get(reverse('diary:questions', args=(rand, hash))) self.assertContains(response, 'Week %d' % ( i ))
def process_greetings_step_other(message): try: user = User(message.from_user) user.preferred_name = message.text user.save() bot.send_message( message.chat.id, f'Great! From now on you are {user.preferred_name} to me') msg = bot.reply_to(message, f'How old are you, {user.preferred_name}?') bot.register_next_step_handler(msg, process_age_step) except Exception as e: print(e) bot.send_sticker(message.chat.id, 'CAADAgADKAMAAoZALgI8Cc13uyaJLhYE') bot.reply_to(message, 'oooops')
def test_no_reminder_sent_before_startdate(self): startdate = '2014-01-23' u = User(email='*****@*****.**', startdate=startdate) u.save() with patch('diary.models.SurveyDate') as mock: patched_date = mock.return_value patched_date.now.return_value = dateparse.parse_date('2014-01-25') patched_date.get_start_date.return_value = dateparse.parse_date('2014-01-16') rm = ReminderManager() rm.send_second_reminder_email() self.assertEqual(len(mail.outbox), 0)
def test_cannot_complete_survey_twice(self): u = User(email='*****@*****.**') u.save() (rand, hash) = make_token_args(u) response = self.client.get(reverse('survey:survey2', args=(rand, hash))) self.assertEqual(response.status_code, 200) self.assertContains(response, "University of Manchester") self.client.post(reverse('survey:record2'), {} ) self.assertIsNotNone(self.client.cookies['surveydone2']) response = self.client.get(reverse('survey:survey2', args=(rand, hash))) self.assertEqual(response.status_code, 200) self.assertContains(response, "already completed")
def test_sends_first_reminder_if_first_week(self): startdate = '2014-01-23' u = User(email='*****@*****.**', startdate=startdate) u.save() with patch('diary.models.SurveyDate') as mock: patched_date = mock.return_value patched_date.now.return_value = dateparse.parse_date('2014-01-25') patched_date.get_start_date.return_value = dateparse.parse_date('2014-01-23') rm = ReminderManager() rm.send_second_reminder_email() self.assertEqual(len(mail.outbox), 1) self.assertRegexpMatches(mail.outbox[0].body, 'You recently registered to complete an online diary');
def create_user(message, session=None): if not session: session = Session() user = User( tg_id=message.from_user.id, first_name=message.from_user.first_name, last_name=message.from_user.last_name, # chat_id=message.chat.id, username=message.from_user.username, ) user.is_admin = user.tg_id in User.ADMIN_IDS session.add(user) session.commit() print('NEW USER ', user, user.id) warn_admins('New user joined: {}'.format(repr(user)), session) return user
def test_reminder_link_works(self): startdate = '2014-01-21' u = User(email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-23') self.assertRegexpMatches(mail.outbox[0].body, '(?P<url>D/([0-9A-Za-z]+)-(.+)/)') matches = re.search('(?P<url>/D/[0-9A-Za-z]+-.+/)', mail.outbox[0].body) print matches.group('url') with patch.object( SurveyDate, 'now') as mock: mock.return_value = dateparse.parse_datetime('2014-01-30 00:00:00+00:00') response = self.client.get(matches.group('url')) self.assertEqual(response.status_code, 200); self.assertContains(response, 'Week 2')
def test_sends_reminder(self): startdate = '2014-01-16' u = User(email='*****@*****.**', startdate=startdate) u.save() with patch('diary.models.SurveyDate') as mock: patched_date = mock.return_value patched_date.now.return_value = dateparse.parse_date('2014-01-25') patched_date.get_start_date.return_value = dateparse.parse_date('2014-01-23') rm = ReminderManager() rm.send_second_reminder_email() self.assertEqual(len(mail.outbox), 1) self.assertRegexpMatches(mail.outbox[0].body, 'On Thursday, we sent you a link to your new'); self.assertRegexpMatches(mail.outbox[0].body, 'D/([0-9A-Za-z]+)-(.+)/')
def show_info(message): user = User(message.from_user) if user.existed: bot.send_message(message.chat.id, repr(user)) else: bot.send_message(message.chat.id, 'No information about you, try /start')
def test_save_non_diary_day_registration_sends_email(self): u = User(email='*****@*****.**') u.save() # need to do this to set up session (rand, hash) = make_token_args(u) response = self.client.get(reverse('diary:register', args=(rand, hash))) with patch( 'diary.views.SurveyDate') as mock: patched_date = mock.return_value patched_date.is_diary_day.return_value = False patched_date.now.return_value = dateparse.parse_date('2014-01-24') patched_date.get_start_date.return_value = dateparse.parse_datetime('2014-01-23T00:00:00+00:00') response = self.client.post(reverse('diary:register', args=(rand, hash)), {'name': 'Test User', 'agree': 1}) self.assertContains(response, 'an email confirming your registration') self.assertEqual(len(mail.outbox), 1) self.assertRegexpMatches(mail.outbox[0].body, 'We will send you the link to your first')
def process_q2(message): user = User(message.from_user) if message.text == u'Да' or message.text == u'Нет': user.q2 = message.text user.save() else: bot.send_message(message.chat.id, 'Error - if u see this, text AD') return markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) markup.add('Верхние полки') markup.add('По середине - на уровне глаз') markup.add('Нижние полки') msg = bot.send_message( message.chat.id, 'Супер! И еще: На каком уровне размещены безглютеновые продукты?', reply_markup=markup) bot.register_next_step_handler(msg, process_q3)
def test_no_reminder_sent_if_diary_entry_for_week(self): startdate = '2014-01-23' u = User(email='*****@*****.**', startdate=startdate) u.save() w = Week.objects.get(week=1) e = Entries(user_id=u.id,week_id=w.id,question='q',answer='a') e.save() with patch('diary.models.SurveyDate') as mock: patched_date = mock.return_value patched_date.now.return_value = dateparse.parse_date('2014-01-25') patched_date.get_start_date.return_value = dateparse.parse_date('2014-01-23') rm = ReminderManager() rm.send_second_reminder_email() self.assertEqual(len(mail.outbox), 0)
def send_welcome(message): user = User(message.from_user) user.save() markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) markup.one_time_keyboard = True # types.ReplyKeyboardRemove markup.add('Ye, sure!') markup.add('No, with surname please') markup.add('No, I\'ll tell you how') msg = bot.send_message(message.chat.id, f"""\ Greetings {user.preferred_name}, I am polly, an example bot. May I call you {user.first_name}? """, reply_markup=markup) # bot.register_next_step_handler(msg, process_name_step) bot.register_next_step_handler(msg, process_greetings_step)
def test_save_registration_adds_start_date(self): u = User(email='*****@*****.**') u.save() # need to do this to set up session (rand, hash) = make_token_args(u) response = self.client.get(reverse('diary:register', args=(rand, hash))) with patch( 'diary.views.SurveyDate') as mock: patched_date = mock.return_value patched_date.now.return_value = dateparse.parse_date('2014-01-24') patched_date.get_start_date.return_value = dateparse.parse_datetime('2014-01-23T00:00:00+00:00') response = self.client.post(reverse('diary:register', args=(rand, hash)), {'name': 'Test User', 'agree': 1}) self.assertContains(response, 'Thank') u = User.objects.latest('id') self.assertIsNotNone(u.startdate) self.assertEqual(u.startdate.isoformat(), '2014-01-23T00:00:00+00:00') self.assertEqual(u.name, 'Test User')
def test_diary_details_are_recorded(self): u = User(email='*****@*****.**', startdate=timezone.now()) u.save() (rand, hash) = make_token_args(u) w = Week.objects.get(week=1) with patch( 'diary.views.SurveyDate') as mock: patched_date = mock.return_value patched_date.get_week_from_startdate.return_value = 1 # do this to set up the session response = self.client.get(reverse('diary:questions', args=(rand, hash))) response = self.client.post(reverse('diary:record_answers'), { 'media_diary': 'watched the news', 'week': 1 }) """ date of diary recording is also added so we have 2 answers """ answers = Entries.objects.filter(user_id=u.id).filter(week_id=w.id) self.assertEqual(len(answers), 2)
def submit(request): logger.info(request.POST) p = request.POST try: user = User.objects.get(email=p["email"]) except User.DoesNotExist: # 유져 정보 저장 user = User(email=p["email"], name=p["name"], exp=p["exp"]) user.save(); # 문항 최대 번호 검색 #max_seq_record = Question.objects.all().aggregate(Max('seq')) #max_seq = int(max_seq_record['seq__max']) + 1 questions = Question.objects.all() # 점수 계산, 답변 저장 score = 0 #for i in range(1, max_seq): for question in questions: #question = Question.objects.get(seq=i) value = '%s' % question.pk score += int(p[value]) logger.error(p[value]) answer = Answer(user=user, question=question, answer=p[value]) answer.save() d = dict(user=user, score=score) d.update(csrf(request)) #return render_to_response("submit.html", d) return HttpResponseRedirect(reverse("survey.views.user", args=[user.pk]))
def process_age_step(message): try: age = message.text if not age.isdigit(): msg = bot.reply_to(message, 'Age should be a number. How old are you?') bot.register_next_step_handler(msg, process_age_step) return user = User(message.from_user) user.age = age user.save() markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) markup.add('Male', 'Female') msg = bot.send_message(message.chat.id, 'What is your gender', reply_markup=markup) bot.register_next_step_handler(msg, process_sex_step) except Exception as e: print(e) bot.send_sticker(message.chat.id, 'CAADAgADKAMAAoZALgI8Cc13uyaJLhYE') bot.reply_to(message, 'oooops')
def test_questions_page_says_if_already_filled_in(self): u = User(email='*****@*****.**', startdate=timezone.now()) u.save() (rand, hash) = make_token_args(u) w = Week.objects.filter(week=1) e = Entries(question='recorded', answer=timezone.now(), user_id=u.id, week_id=w[0].id) e.save() with patch( 'diary.views.SurveyDate') as mock: patched_date = mock.return_value patched_date.is_diary_day.return_value = True patched_date.get_week_from_startdate.return_value = 2 response = self.client.get(reverse('diary:questions', args=(rand, hash))) self.assertContains(response, 'Week 2') w = Week.objects.filter(week=2) e = Entries(question='recorded', answer=timezone.now(), user_id=u.id, week_id=w[0].id) e.save() response = self.client.get(reverse('diary:questions', args=(rand, hash))) self.assertContains(response, 'already filled in this week')
def test_does_not_send_if_user_has_no_email(self): u = User(email='*****@*****.**',) u.save() u = User(withdrawn=True,) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1)
def test_reminder_not_send_to_withdrawn_users(self): startdate = '2014-01-16' u = User(email='*****@*****.**', startdate=startdate) u.save() u = User(withdrawn=True,email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-16') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
def test_does_not_send_if_user_has_startdate(self): u = User(email='*****@*****.**') u.save() startdate='2014-01-16' u = User(withdrawn=True,email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
def test_reminder_not_sent_to_finished_users(self): startdate = '2013-11-07' u = User(email='*****@*****.**', startdate=startdate) u.save() startdate = '2013-10-31' u = User(withdrawn=True,email='*****@*****.**', startdate=startdate) u.save() self.run_command('2014-01-23') self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
def get_logged_user_id(token): try: payload = jwt.decode(token, Config.SECRET_KEY, algorithms=['HS256']) except jwt.exceptions.InvalidTokenError: raise GraphQLError('auth.failed') user_id = payload.get('id', None) if not user_id: raise GraphQLError('auth.failed') user = User.get_by_id(user_id) if not user: raise GraphQLError('auth.failed') return user_id
def process_location(message): user = User(message.from_user) user.latitude = message.location.latitude user.longitude = message.location.longitude user.save() dist = round(get_distance(user.latitude, user.longitude), 1) bot.send_message(message.chat.id, f'Ого, ты в {dist}км от центра Москвы!') bot.send_message(message.chat.id, '\nТеперь к делу...') msg = bot.send_message( message.chat.id, f'{user.preferred_name}, в каком отделов магазина размещена безглютеновая продукция?', reply_markup=types.ReplyKeyboardRemove()) bot.register_next_step_handler(msg, process_q1)
def add_user(): users = User.query.all() categories = Category.query.all() polls = Poll.query.all() responses = Response.query.all() user_form = RegistrationForm() category_form = NewCategoryForm() poll_form = NewPollForm() poll_form.category_poll.choices = [(str(category.id), category.name) for category in Category.query.all()] # Check Form input and encrypt the password before store them if user_form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( user_form.password.data).decode('utf-8') user = User(firstname=user_form.firstname.data, lastname=user_form.lastname.data, email=user_form.email.data, gender=user_form.gender.data, password=hashed_password, is_admin=user_form.is_admin.data) db.session.add(user) db.session.commit() flash('New user account has been created!', 'success') return redirect(url_for('user_admin.user_index')) flash( u'New user account has not been created! Please try again, or look the log error', 'danger') return render_template('user-admin/user_admin.html', users=users, categories=categories, polls=polls, responses=responses, user_form=user_form, category_form=category_form, poll_form=poll_form, title="Admin", data={ 'form': 'user_form', 'form_checking': True }, client=get_client())
def register(): form = RegistrationForm() # Check Form input and encrypt the password before store them if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(firstname=form.firstname.data, lastname=form.lastname.data, email=form.email.data, gender=form.gender.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to login', 'success') return redirect(url_for('users.login')) return render_template('user/register.html', title='Register', form=form, client=get_client())
def reset_token(token): if current_user.is_authenticated: return redirect(url_for('main.index')) user = User.verify_reset_token(token) if user is None: flash('That is an invalid or expired token', 'warning') return redirect(url_for('users.reset_request')) form = ResetPasswordFrom() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() flash('Your password has been updated! You are now able to login', 'success') return redirect(url_for('users.login')) return render_template('user/reset_token.html', title='Reset Password', form=form, token=token, client=get_client())
def resolve_owner(self, info, *args): owner = UserORM.get_by_id(self.owner_id) return User(id=owner.id, name=owner.name)
def mutate(self, info, name): new_user = UserORM.create(name=name) user = User(id=new_user.id, name=name) token = Auth.create_token(new_user.id) return Authorize(user=user, token=token, message="ok")
from settings import MY_TG from survey.models import recreate_all, Session, User from survey.result_table import create_result_table recreate_all() me = User(tg_id=MY_TG, first_name='A', last_name='D', is_admin=True) s = Session() s.add(me) s.commit() import gluten_shops.survey_script as script create_result_table(script.questionnaire) # print('READ THIS', 'https://docs.sqlalchemy.org/en/13/orm/extensions/automap.html')