def post(self, request, *args, **kwargs):
     email = request.POST.get("email", None)
     if email is not None:
         url = request.build_absolute_uri(
             reverse("signup",
                     kwargs={"token": self.generate_signup_token(email)}))
         html = get_template("registration/email.html")
         content = html.render({"url": url})
         msg = "Kindly visit %s to create an account" % url
         send_mail(
             "Computer Science & I.T Department Timetable Registration",
             msg,
             "*****@*****.**",
             [email],
             fail_silently=False,
             html_message=content,
         )
         Registration(email=email).save()
         messages.success(request,
                          "Registration email sent successfully",
                          extra_tags="alert")
         return super().get(request)
     else:
         messages.warning(request, "An error occured while sending email")
     return render(request, self.template_name, {})
Ejemplo n.º 2
0
    def continue_scenario(self, text, state, user_id):
        """Продолжить сценарий для пользователя.

        :param user_id: id пользователя
        :param text: сообщение пользователя
        :param state: состояние, в котором находится пользователь
        :param user_id: id пользователя
        :return: сообщение, которое необходимо отправить пользователю.
        """
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)

            if next_step['next_step']:
                state.step_name = step['next_step']
            else:
                log.info(
                    'Зарестрирован: {name} {email}'.format(**state.context))
                Registration(name=state.context['name'],
                             email=state.context['email'])
                state.delete()
        else:
            # повторить шаг текущего сценария
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send, user_id)
Ejemplo n.º 3
0
 def continue_scenario(self, text, state, user_id):
     steps = settings.SCENARIOS[state.scenario_name]["steps"]
     step = steps[state.step_name]
     handler = getattr(handlers, step["handler"])
     if handler(text=text, context=state.context):
         # next step
         next_step = steps[step["next_step"]]
         self.send_step(next_step, user_id, text, state.context)
         if next_step["next_step"]:
             # switch to next step
             state.step_name = step["next_step"]
         else:
             # finish scenario
             log.info(state.context)
             Registration(departure=state.context['departure'],
                          arrival=state.context['arrival'],
                          chosen_date=state.context['chosen_date'],
                          places=state.context['places'],
                          phone_number=state.context['number'],
                          email=state.context['email'],
                          confirmed=state.context['confirmed'],
                          comment=state.context['comment'])
             state.delete()
     else:
         # retry current step
         text_to_send = step["failure_text"].format(**state.context)
         self.send_text(text_to_send, user_id)
Ejemplo n.º 4
0
 def continue_scenario(self, text, state, user_id):
     steps = settings.SCENARIOS[state.scenario_name]['steps']
     step = steps[state.step_name]
     handler = getattr(handlers, step['handler'])
     if handler(text=text, context=state.context, user_date=self.user_time):
         # next step
         next_step = steps[step['next_step']]
         self.send_step(next_step, user_id, text, state.context)
         if next_step['next_step']:
             # switch next step
             state.step_name = step['next_step']
         else:
             # finish scenario
             state.delete()
             log.info('Город отправления - {departure_city}\n'
                      'Город назначения - {destination_city}\n'
                      'Дата отправления - {departure_date}\n'
                      'Выбранный рейс - {num_flight}\n'
                      'Количество мест - {num_seats}\n'
                      'Комментарий к заказу:\n'
                      '{comment}\n'.format(**state.context))
             Registration(
                 name=self.name,
                 departure_city=state.context['departure_city'],
                 destination_city=state.context['destination_city'],
                 departure_date=state.context['departure_date'],
                 num_flight=state.context['num_flight'],
                 num_seats=state.context['num_seats'],
                 comment=state.context['comment'],
                 phone_number=state.context['phone_number'],
             )
     else:
         # retry current step
         text_to_send = step['failure_text'].format(**state.context)
         self.send_text(text_to_send, user_id)
Ejemplo n.º 5
0
    def continue_scenario(self, text, state, user_id):
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            # next step
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)

            if next_step['next_step']:
                # switch to next step
                state.step_name = step['next_step']
            else:
                # finish scenario
                log.info('Куплен билет на номер {phone_number}'.format(
                    **state.context))
                Registration(phone_number=state.context['phone_number'],
                             user_info=state.context['user_info'])
                state.delete()
        else:
            # retry current step
            if step['action'] is not None:
                action_func = getattr(actions, step['action'])
                text_to_send, kwargs = action_func(state.context)

                reset_scenario_flag = kwargs.get('reset_scenario', False)
                if reset_scenario_flag:
                    state.delete()
            else:
                text_to_send = step['failure_text'].format(**state.context)

            self.send_text(text_to_send, user_id)
Ejemplo n.º 6
0
    def continue_scenario(self, text, state, user_id):
        """
        Continues user scenario

        :param text: parameter for handler
        :param state: current state
        :param user_id: vk user id
        :return: None
        """
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            # next step
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)
            if next_step['next_step']:
                # switch to next_step
                state.step_name = step['next_step']
            else:
                # finish scenario
                log.info(
                    'Зарегистрирован: {name} {email}'.format(**state.context))
                Registration(name=state.context['name'],
                             email=state.context['email'])
                state.delete()
        else:
            # retry current step
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send, user_id)
Ejemplo n.º 7
0
    def continue_scenario(self, text, state, user_id):
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]
        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context, settings_dict=self.cities):
            # next step
            start_over = state.context.get('start_over')
            if start_over:
                self.send_text(text_to_send='К сожалению, нам придется завершить сценарий', user_id=user_id)
                state.delete()
                return
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)

            if next_step['next_step']:
                # switch to next step
                state.step_name = step['next_step']
            else:
                # finish scenario
                log.info(
                    'Билет из {dep_city}, в {dest_city}, на дату {flight}, {number_of_tickets} билетов, комментарий: {commentary}, телефон: {telephone}, имя: {fio}'.format(
                        **state.context))
                Registration(dep_city=state.context['dep_city'], dest_city=state.context['dest_city'],
                             date=state.context['flight'], tickets=state.context['number_of_tickets'],
                             commentary=state.context['commentary'],
                             telephone=state.context['telephone'])
                state.delete()
        else:
            # retry current step
            print(state.context)
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send, user_id)
Ejemplo n.º 8
0
    def continue_scenario(self, text, state, user_id):
        steps = SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            # next step
            next_step = steps[step['next_step']]
            self.send_step(step=next_step,
                           user_id=user_id,
                           text=text,
                           context=state.context)
            if next_step['next_step']:
                # switch to next step
                state.step_name = step['next_step']
            else:
                # finish scenario
                self.bot_log.info(
                    'Зарегистрирован: {name}  {email}'.format(**state.context))
                Registration(name=state.context['name'],
                             email=state.context['email'])
                state.delete()
        else:
            # retry current step
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send=text_to_send, user_id=user_id)
Ejemplo n.º 9
0
def check_phone_number(update, context):
    """
    Проверка номера телефона пользователя и занесение данных в БД
    """
    if update.message.text == "да":
        log.info(f"получен верный номер телефона")
        update.message.reply_text(f"Спасибо, {context.user_data['name']}! Ожидайте звонка. Ваш билет.")
        image_ticket = make_ticket(
            fio=context.user_data['name'], from_=context.user_data["city_of_departure"],
            to=context.user_data["arrival_city"], date=context.user_data["date_of_departure"],
            person=context.user_data["name_avatar"]
        )
        context.bot.send_photo(chat_id=update.message.chat.id, photo=open(image_ticket, 'rb'))
        Registration(
            name=context.user_data['name'],
            date_of_departure=context.user_data["date_of_departure"],
            city_of_departure=context.user_data["city_of_departure"],
            arrival_city=context.user_data["arrival_city"],
            flight=context.user_data["flight"],
            number_of_seats=context.user_data["number_of_seats"],
            comment=context.user_data["comment"],
            phone_number=context.user_data["phone_number"],
            name_avatar=context.user_data["name_avatar"]
        )
        return ConversationHandler.END
    else:
        log.info(f"получен неверный номер телефона")
        update.message.reply_text("Введите номер телефона.")
        return PHONE_NUMBER
Ejemplo n.º 10
0
 def finish_scenario(self, state):
     """
     Завершение текущего сценария
     :param state: состояние текущей процедуры
     :type state: models.UserState
     :return: None
     """
     if state.scenario_name == 'coffee':
         log.info('Выдан кофе')
         self.pay.get_empty_keyboard()
         state.delete()
     elif state.scenario_name == 'registration':
         log.info('Зарегистрирован: {name} {email}'.format(**state.context))
         Registration(name=state.context['name'], email=state.context['email'])
         BonusCardCoffee(email_card=state.context['email'], count=0)
         state.delete()
     elif state.scenario_name == 'airplane':
         log.info('Зарегистрирован на полёт: {name} {connect}. Рейс: {landing}-{direction}, {date_reg}'
                  .format(**state.context))
         RegistrationAirline(name=state.context['name'], connect=state.context['connect'],
                             landing=state.context['landing'], direction=state.context['direction'],
                             date_reg=state.context['date_reg'], date_landing=state.context['date_landing'],
                             date_direction=state.context["date_direction"])
         state.delete()
     else:
         state.delete()
Ejemplo n.º 11
0
    def continue_scenario(self, text, state, user_id):
        """Переход на следующий шаг сценария бота"""
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)
            if next_step['next_step']:
                state.step_name = step['next_step']
            else:
                log.info(
                    'Зарегистрирован: {name} {city_from} - {city_to} {flight} {seats} seats "{comment}" {phone} {email}'
                    .format(**state.context))
                Registration(
                    city_from=state.context['city_from'],
                    city_to=state.context['city_to'],
                    flight=state.context['flight'],
                    seats=state.context['seats'],
                    comment=state.context['comment'],
                    name=state.context['name'],
                    email=state.context['email'],
                    phone=state.context['phone'],
                )
                state.delete()

        else:
            if 'stop' in state.context:
                text_to_send = step['stop_scenario'].format(**state.context)
                self.send_text(text_to_send, user_id)
                state.delete()
            else:
                text_to_send = step['failure_text'].format(**state.context)
                self.send_text(text_to_send, user_id)
Ejemplo n.º 12
0
def charge():

    def str2date(date_string):
        """ Returns a datetime date given a valid date_string """
        return datetime.datetime.strptime(date_string, "%Y-%m-%d").date()

    if request.method == 'POST':
        try:
            # Amount in pence
            
            customer = stripe.Customer.create(
                email=request.form['stripeEmail'],
                card=request.form['stripeToken']
            )
            charge = stripe.Charge.create(
                customer=customer.id,
                amount=Decimal(session['registration_price']),
                currency='gbp',
                description='Registration'
            )

            sob_date = None
            if session['sobriety_date'] != u'None':
               sob_date = str2date(session['sobriety_date'])

            registration = Registration(
                  first_name     = session['first_name']
                , last_name      = session['last_name']
                , mobile         = session['mobile']
                , email          = session['email']
                , sobriety_date  = sob_date
                , ypaa_committee = session['ypaa_committee']
                , fellowship     = session['fellowship']
                , special_needs  = session['special_needs']
                , of_service     = session['of_service']
                , country        = session['country']
                )
            registration.put()
            email_admin(session)
            email_user(session)
            flash("You are now registered!")

            if sob_date is not None:
                num_twins = num_sobriety_twins(str2date(session['sobriety_date']))
                if num_twins > 1:
                    if num_twins == 2:
                        flash("By the way, you have a sobriety twin coming to the convention!")
                    else:
                        flash("By the way, you have %d sobriety twins coming to the convention!" % (num_twins-1))

            return redirect(url_for('homepage'))

        except Exception, e:
            # TODO: Roll back transaction, registration
            #print "Payment not processed: %s" % e
            flash("Payment not processed. %s" % e)
            return redirect(url_for('new_registration_1'))
Ejemplo n.º 13
0
 def finish_scenario(self, state):
     Registration(name=state.context['name'],
                  email=state.context['email'],
                  date=state.context['date'],
                  departure=state.context['departure'],
                  destination=state.context['destination'],
                  passengers=state.context['passengers'],
                  comment=state.context['comment'],
                  mobile=state.context['mobile'])
     log.info(
         "Выполнена бронь! Отправление {departure}, прибытие {destination}, дата {date}"
         .format(**state.context))
Ejemplo n.º 14
0
def add_registration():
    if request.method == 'POST':
        fullname = request.form.get('fullname')
        event_id = request.form.get('event_id')
        if fullname and event_id:
            manage_code = generate_code(8)
            db.session.add(Registration(event_id, fullname, manage_code))
            db.session.commit()
            flash(
                'You have been successfully registered to the event! Here is your manage code: {}'
                .format(manage_code))

    return redirect('/')
Ejemplo n.º 15
0
 def end_scenario(self, state):
     if self.check_state(state):
         Registration(departure_city_to_print=state.context['departure_city_to_print'],
                      arrival_city_to_print=state.context['arrival_city_to_print'],
                      departure_date=state.context['date_flight_to_print'],
                      departure_time=state.context['time_flight_to_print'],
                      first_name=state.context['first_name'],
                      last_name=state.context['last_name'],
                      phone=state.context['phone'],
                      flight=state.context['flight_to_print'],
                      email=state.context['email'],
                      number_of_seats=state.context['seats'],
                      comment=state.context['comment'])
     state.delete()
     self.first_event = True
Ejemplo n.º 16
0
    def continue_scenario(self, user_id, text, state):
        """продолжает сценарий"""
        steps = settings.SCENARIO[state.scenario_name]['steps']
        step = steps[state.step_name]
        handler = getattr(handlers, step['handler'])
        if handler(text=text,
                   context=state.context,
                   flight_schedule=self.FLIGHT_SCHEDULE
                   ):  # если хэндлер выернул True
            next_step = steps[step['next_step']]
            text_to_send = next_step['text'].format(**state.context)
            if next_step['next_step']:
                state.step_name = step['next_step']
            else:
                print(state)
                print(state.context['email'])
                print(type(state.context['email']))
                Registration(name=state.context['name'],
                             email=state.context['email'],
                             date_flight=state.context['date_flight'],
                             time_flight=state.context['time_flight'],
                             city_out=state.context['city_out'],
                             city_in=state.context['city_in'],
                             sits=state.context['sits'],
                             comment=state.context['comment'],
                             phone=state.context['phone'])

                state.delete()
            if 'action' in step:  # если в описании шага есть 'action'
                if step['action'] == 'check_flights_action':
                    if not self.FLIGHT_SCHEDULE[state.context['city_out']][
                            state.context['city_in']]:
                        self.check_flights_action(user_id, state)
                        text_to_send = 'Введите город отправения: '
                elif step['action'] == 'send_image':
                    self.send_image(state, user_id)

        else:  # если хэндлер вернул False
            text_to_send = step['failure_text'].format(**state.context)
            if 'fail_action' in step:
                if step['fail_action'] == 'fail_city_out_action':
                    self.fail_city_out_action(user_id)
                elif step['fail_action'] == 'fail_city_in_action':
                    self.fail_city_in_action(user_id, state)
        return text_to_send
Ejemplo n.º 17
0
def register(request, slug):

    e = Event.objects.get(slug=slug)
    u = request.user

    # if there are no non-cancelled registrations for this user/event and
    # registration is possible
    if (is_registered(u, e) == False and is_waitlisted(u, e) == False
            and e.is_registration_open() == True):
        # Since the event object will become aware of this registration
        # as soon as it saves, we need to cache the value. This might bite us?
        #
        # Check it:
        #
        # There's a class with a size of one with waitlist enabled. If
        # we save now the check to send the email will happen after the
        # class number gets counted and the waitlist email will be sent.
        waitlist_status = e.add_to_waitlist()
        t = Registration(student=u,
                         event=e,
                         date_registered=datetime.now(),
                         waitlist=waitlist_status)
        t.save()

        # Email us with the needs of the student.
        if request.POST["student_needs"] != "":
            send_mail("(KCDC accommodation form) " + e.title,
                      request.user.email + " requested the following: " +
                      request.POST["student_needs"],
                      "*****@*****.**",
                      ["*****@*****.**"],
                      fail_silently=False)

        if waitlist_status == False:
            send_registration_mail(e, 'registered', request.user.email)
            return HttpResponseRedirect("/classes/response/registered")
        else:
            send_registration_mail(e, 'waitlisted', request.user.email)
            return HttpResponseRedirect("/classes/response/waitlisted")

    else:
        return HttpResponseRedirect("/classes/response/error")
Ejemplo n.º 18
0
def registration():

    if request.form:
        try:
            person = Registration(firstname=request.form.get("firstname"),
                                  lastname=request.form.get("lastname"),
                                  address=request.form.get("Address"),
                                  email=request.form.get("Email"),
                                  password=request.form.get("Password"),
                                  phonenumber=request.form.get("Phone Number"),
                                  dateofbirth=request.form.get("dateofBirth"),
                                  description=request.form.get("message"))
            db.session.add(person)
            db.session.commit()
            return redirect("home-page")
        except Exception as e:
            print("Failed to add person")
            print(e)

    return render_template('registerPage.html')
Ejemplo n.º 19
0
    def check_flights_action(
        self, user_id, state
    ):  # проверка есть ли между городами рейсы, если нет то выдает текст
        print(state.context)
        if not self.FLIGHT_SCHEDULE[state.context['city_out']][
                state.context['city_in']]:
            text = 'Между данными городами нет рейсов, попробуйте заново'
            self.send_text(text, user_id)
            print(type(state.context['email']))
            Registration(name=state.context['name'],
                         email=state.context['email'],
                         date_flight=state.context['date_flight'],
                         time_flight=state.context['time_flight'],
                         city_out=state.context['city_out'],
                         city_in=state.context['city_in'],
                         sits=state.context['sits'],
                         comment=state.context['comment'],
                         phone=state.context['phone'])

            state.delete()
            self.start_scenario(scenario_name='ticket', user_id=user_id)
Ejemplo n.º 20
0
    def on_id_selection(self, section_id):

        try:
            reg = Registration(section_id=section_id,
                               student_id=self.__student_id)

            if reg.save():

                section_name = get_section_name(section_id)

                if section_name:
                    self.__view.print_message(
                        f'Successfully registered {self.__student_name} for {section_name}.'
                    )
                else:
                    self.__view.print_message(
                        'Successfully registered for section.')
            else:
                self.__view.print_message(f'Failed to register for section.')
        except IntegrityError:
            self.__view.print_message('Unable to register for section.')
Ejemplo n.º 21
0
 def continue_scenario(self, text, state, user_id):
     steps = settings.SCENARIOS[state.scenario_name][
         'steps']  # в данном случае 'registration'
     step = steps[state.step_name]
     handler = getattr(
         _handlers, step['handler']
     )  # из модуля _handlers возвращается соответствующая ф-я
     if handler(text=text, context=state.context):
         next_step = steps[step['next_step']]
         self.sent_step(next_step, user_id, text, state.context)
         if next_step['next_step']:
             # switch next step
             state.step_name = step['next_step']
         else:
             # finish scenario
             Registration(name=state.context['name'],
                          email=state.context['email'])
             state.delete()
     else:
         text_to_send = step['failure_text'].format(**state.context)
         self.send_to_text(user_id, text_to_send)
Ejemplo n.º 22
0
def csv2db(csv_filename):
    def boolify(s):
        return {'True':True,'False':False}[s]
    def dateify(s):
        return d.strptime(s, "%d/%m/%Y").date() if s != 'none' else None
    with open(csv_filename) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print row
            r = Registration(
                      first_name = row['first_name']
                    , last_name = row['last_name']
                    , mobile = row['mobile']
                    , email = row['email']
                    , sobriety_date = dateify(row['sobriety_date'])
                    , ypaa_committee = row['ypaa_committee']
                    , fellowship = row['member_of']
                    , special_needs = row['special_needs']
                    , country = row['country']
                    , of_service = boolify(row['of_service'])
                    )
            r.put()
Ejemplo n.º 23
0
    def continue_scenario(self, text, state, user_id):
        # продолжаем сценарий
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            # next step
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)

            if next_step['next_step']:
                # switch to next step
                state.step_name = step['next_step']
            else:
                # finish scenario
                log.info('Пользователь {name} {email} прошел сценарий.'.format(**state.context))
                Registration(name=state.context['name'], email=state.context['email'])
                state.delete()
        else:
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send, user_id)
Ejemplo n.º 24
0
    def continue_scenario(self, text, state, user_id):
        steps = settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]

        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)
            if next_step['next_step']:
                state.step_name = step['next_step']
            else:
                log.info('Получен запрос от ')
                Registration(departure_city=state.context['from'],
                             arrival_city=state.context['to'],
                             date=state.context['date'],
                             chosen_flight=state.context['chosen_flight'],
                             quantity=state.context['ticket_quantity'],
                             number=state.context['number'])
                state.delete()
        else:
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send, user_id)
Ejemplo n.º 25
0
    def continue_scenario(self, text, state, user_id):
        steps = Settings.SCENARIOS[state.scenario_name]['steps']
        step = steps[state.step_name]
        handler = getattr(handlers, step['handler'])
        if handler(text=text, context=state.context):
            # next step
            next_step = steps[step['next_step']]
            self.send_step(next_step, user_id, text, state.context)

            if next_step['next_step']:
                # swith to next steps
                state.step_name = step['next_step']
            else:
                # finish scenario
                Registration(name=str(user_id),
                             city_from=state.context['city_from'],
                             city_to=state.context['city_to'],
                             date=state.context['date'])
                # del from psql
                state.delete()
        else:
            text_to_send = step['failure_text'].format(**state.context)
            self.send_text(text_to_send, user_id)
Ejemplo n.º 26
0
 def continue_scenario(self, text, state):
     steps = settings.SCENARIOS[state.scenario_name]["steps"]
     step = steps[state.step_name]
     handler = getattr(handlers, step["handler"])
     if handler(text=text, state=state):
         next_step = steps[step["next_step"]]
         self.sent_step(step=next_step, user_id=state.user_id, text=text, state=state)
         if next_step["next_step"]:
             state.step_name = step["next_step"]
         else:
             Registration(
                 user_id=state.user_id,
                 first_name=state.first_name,
                 last_name=state.last_name,
                 user_flight=state.context['user_flight_of_write'],
                 user_flight_data=state.context["data_flights"],
                 user_number_seats=state.context['user_number_seats'],
                 comment=state.context['comment'],
                 number_phone=state.context["phone"]
             )
             state.delete()
     else:
         self.sent_text(text_to_sent=step["failure_text"].format(**state.context), user_id=state.user_id)
Ejemplo n.º 27
0
 def continue_scenario(self, text, state, user_id):
     steps = settings.SCENARIOS[state.scenario_name]['steps']
     step = steps[state.step_name]
     handler = getattr(handlers, step['handler'])
     if handler(text=text, context=state.context):
         # next step
         next_step = steps[step['next_step']]
         self.send_step(next_step, user_id, state.context)
         if next_step['next_step']:
             # switch to next step
             state.step_name = step['next_step']
         else:
             # finish
             Registration(
                 user_id=user_id,
                 From=state.context['From'],
                 to=state.context['to'],
                 date=state.context['date'],
                 flight=state.context['flight'],
                 seats=state.context['seats'],
                 comment=state.context['comment'],
                 phone=state.context['phone'],
             )
             log.info(
                 'Забронированы билеты из города {From} в город {to} на {date}'
                 .format(**state.context))
             state.delete()
     elif 'continue' in state.context:
         # failure finish
         text_to_send = step['finish'].format(**state.context)
         self.send_text(text_to_send, user_id)
         state.delete()
         log.info('Пользователь завершил сценарий, не купив билет')
     else:
         # retry current step
         text_to_send = step['failure_text'].format(**state.context)
         self.send_text(text_to_send, user_id)
Ejemplo n.º 28
0
def python():
    errors = []
    if request.method == "POST":
        country = request.form["inputCountry"]
        city = request.form["inputCity"]
        index = request.form["inputZip"]
        address_actual = request.form["inputAddress"]
        address_legal = request.form["inputAddress2"]
        email = request.form["inputEmail"]
        password = request.form["inputPassword"]
        remember = request.form.get("checkRemember") == "on"

        try:
            result = Registration(
                country=country,
                city=city,
                index=index,
                address_actual=address_actual,
                address_legal=address_legal,
                email=email,
                password=password,
                remember=remember,
            )
            db.session.add(result)
            db.session.commit()

            return redirect(f"/python", code=301)

        except Exception:
            errors.append("Ошибка при добавлении записи в базу данных.")

    records = db.session.query(Registration).all()

    return render_template(f"python/index.html",
                           records=records,
                           errors=errors)
Ejemplo n.º 29
0
    def _normal_step(self, state, steps, step, user_id, text):
        """
        Функция "Обычный шаг", используется при обычном переходе из одного шага сценария на другой
        :param state: текущее состояние пользователя
        :param steps: все шаги сценария исполняемого в данный момент
        :param step: шаг, на котором сейчас находится пользователь
        :param user_id: id пользователя, от которого пришло сообщение боту
        :param text: текст сообщения пользователя
        :return: None
        """
        next_step = steps[step['next_step']]
        self.send_step(step=next_step, user_id=user_id, text=text, context=state.context)
        if next_step['next_step']:
            # switch to next step normal
            state.step_name = step['next_step']
        else:
            # finish scenario
            log.info('Оформлен билет:\n'
                     'Телефон покупателя - {phone}\n'
                     'Email покупателя - {email}\n'
                     'Имя - {name}\n'
                     'Город отправления - {departure}\n'
                     'Город прибытия - {arrival}\n'
                     '{flight_date_to_output}\n'
                     'Количество мест - {spaces}\n'
                     'Комментарий - {comment}'.format(**state.context))

            Registration(user_phone=state.context['phone'],
                         user_email=state.context['email'],
                         user_name=state.context['name'],
                         departure=state.context['departure'],
                         arrival=state.context['arrival'],
                         date=state.context['flight_date_to_database'],
                         spaces=state.context['spaces'],
                         comment=state.context['comment'])
            state.delete()
Ejemplo n.º 30
0
def finish_registration_handler(text, context):
    Registration(user_name=context['name'], email=context['email'])