Example #1
0
def handle_completed_habits(bot, update):
    habit_ids = execute_database_command(
        f'SELECT id FROM habits WHERE user_id = {update.user_id}')
    completed_habits_report = {}
    for habit_id in habit_ids:
        habit_id = habit_id[0]
        habit = Habit.get(habit_id)
        if not habit.get_remaining_checks():
            check_statuses = execute_database_command(
                f'SELECT status FROM checks WHERE habit_id = {habit_id} ORDER BY datetime_utc;'
            )

            for check_status in check_statuses:
                check_status = check_status[0]
                if habit_id in completed_habits_report:
                    completed_habits_report[habit_id]['checks'].append(
                        status_icons[check_status])
                else:
                    completed_habits_report[habit_id] = \
                        {'label': habit.label, 'checks': [status_icons[check_status]]}

    if completed_habits_report:
        report = ''
        for habit in completed_habits_report.values():
            report += f'*{habit["label"]}*\n{" ".join(habit["checks"])}\n\n'
    else:
        user = User.get(update.user_id)
        ru_report = 'Нет ни одной завершённой привычки'
        en_report = 'There are no completed habits'
        report = ru_report if user.language_code == 'ru' else en_report

    bot.send_message(update.user_id, report)
Example #2
0
def handle_habit_report(bot, update):
    check = Check.get(update.cmd_args['check_id'])
    check.status = update.cmd_args['status']
    check.save()

    habit = Habit.get(check.habit_id)

    user = User.get(update.user_id)

    if update.cmd_args['status'] == CheckStatus.SUCCESS.name:
        bot.send_sticker(update.user_id, random.choice(success_stickers))
        bot.send_message(
            update.user_id,
            '+1 очко' if user.language_code == 'ru' else '+1 point')
        user.score += 1  # TODO Заменить на последовательность
        user.save()
    else:
        bot.send_sticker(update.user_id, random.choice(fail_stickers))
        bot.send_message(
            update.user_id,
            '-1 очко' if user.language_code == 'ru' else '-1 point')
        user.score -= 1  # TODO Заменить на последовательность
        user.save()

    if not habit.get_remaining_checks():
        suggest_new_habit(bot, user, habit)
Example #3
0
 def populate_db(self):
     habits = ['Do this', 'Do that', 'Clean up todo comments']
     for habit in habits:
         h = Habit(title=habit)
         db.session.add(h)
         db.session.commit()
     pass
Example #4
0
def handle_active_habits(bot, update):
    user = User.get(update.user_id)
    habit_ids = execute_database_command(
        f'SELECT id FROM habits WHERE user_id = {user.id}')

    active_habits_ids = []
    for habit_id in habit_ids:
        habit_id = habit_id[0]
        habit = Habit.get(habit_id)
        if habit.get_remaining_checks():
            active_habits_ids.append(habit_id)
            check_statuses = execute_database_command(
                f'SELECT status FROM checks WHERE habit_id = {habit_id} ORDER BY datetime_utc;'
            )

            check_report = ''
            for check_status in check_statuses:
                check_report += status_icons[check_status[0]]

            # TODO убрать дублирование кода с Intro
            ru_days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
            en_days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
            days = ru_days if user.language_code == 'ru' else en_days

            days_of_week = list(
                map(lambda x: int(x), habit.days_of_week[1:-1].split(',')))
            time_array = list(
                map(lambda x: x.strip(), habit.time_array[1:-1].split(',')))
            check_days = re.sub(
                r'\s+', ' ', ' '.join([
                    day if day_of_week in days_of_week else ''
                    for day_of_week, day in enumerate(days)
                ])).strip()
            check_time = ' '.join(time_array)

            ru_text = f'Привычка: *{habit.label}*\n' \
                      f'Дни недели: *{check_days}*\n' \
                      f'Время проверки: *{check_time}*\n' \
                      f'Длительность: *3 недели*\n\n' \
                      f'Прогресс\n'
            en_text = f'Habit: *{habit.label}*\n' \
                      f'Days of week: *{check_days}*\n' \
                      f'Checks time: *{check_time}*\n' \
                      f'Duration: *3 weeks*\n\n' \
                      f'Progress\n'
            text = ru_text if user.language_code == 'ru' else en_text

            text += check_report

            bot.send_message(update.user_id,
                             text,
                             keyboard=keyboards.get_delete_habit_keyboard(
                                 user, habit_id))

    if not active_habits_ids:
        ru_text = 'Нет ни одной активной привычки'
        en_text = 'There are no active habits'
        text = ru_text if user.language_code == 'ru' else en_text
        bot.send_message(update.user_id, text)
Example #5
0
def create_habit():
    if request.json:
        habit = Habit(title=request.json['title'])
        db.session.add(habit)
        # TODO try except
        db.session.commit()

        return HTTPStatus.OK.phrase, HTTPStatus.OK.value
    else:
        return HTTPStatus.INTERNAL_SERVER_ERROR.phrase, HTTPStatus.INTERNAL_SERVER_ERROR.value
Example #6
0
def create_habit(request, pk):
    """creates a new habit for the owner at pk"""
    owner = User.objects.get(pk=pk)

    if request.method == "POST":
        form = CreateHabit(request.POST)
        # breakpoint()
        if form.is_valid():
            verb = form.cleaned_data['verb']
            over = form.cleaned_data['over']
            quantity = form.cleaned_data['quantity']
            unit = form.cleaned_data['unit']
            new_habit = Habit(owner=owner, verb=verb, over=over, quantity=quantity, unit=unit)
            new_habit.save()
        return redirect(to='habit-manager', pk=request.user.pk)
    else:
        form = CreateHabit()
        return render(request, "create_habit.html", {
            'owner' : owner,
            'form' : form
        })
Example #7
0
def habit_assign(bot, update):
    user = User.get(update.user_id)

    # Назначаем привычку
    habit = Habit(update.user_id, preparing_habits[update.user_id]['label'],
                  preparing_habits[update.user_id]['days_of_week'],
                  preparing_habits[update.user_id]['time_array']).save()

    # Назначаем проверки
    schedule_native, schedule_utc = get_schedule(
        preparing_habits[update.user_id]['days_of_week'],
        preparing_habits[update.user_id]['time_array'],
        User.get(update.user_id).timezone,
    )

    for check_native, check_utc in zip(
            schedule_native, schedule_utc):  # TODO нужно оптимизировать
        Check(habit.id, check_native, check_utc).save()

    ru_days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
    en_days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
    days = ru_days if user.language_code == 'ru' else en_days

    check_days = re.sub(
        r'\s+', ' ', ' '.join([
            day if day_of_week
            in preparing_habits[update.user_id]['days_of_week'] else ''
            for day_of_week, day in enumerate(days)
        ])).strip()
    check_time = ' '.join(preparing_habits[update.user_id]['time_array'])

    ru_text = f'Привычка *{habit.label}* сформирована.\n\n' \
              f'Дни недели: *{check_days}*\n' \
              f'Время проверки: *{check_time}*\n' \
              f'Длительность: *3 недели*\n\n' \
              f'Начинаем завтра!'
    en_text = f'The habit *{habit.label}* is formed.\n\n' \
              f'Days of week: *{check_days}*\n' \
              f'Checks time: *{check_time}*\n' \
              f'Duration: *3 weeks*\n\n' \
              f'We will start tomorrow!'
    text = ru_text if user.language_code == 'ru' else en_text

    del preparing_habits[update.user_id]

    bot.send_message(update.user_id, text)
    bot.send_sticker(update.user_id, 'ca3fe24b53')

    bot.send_message(update.user_id,
                     'Меню' if user.language_code == 'ru' else 'Menu',
                     keyboard=get_menu_keyboard(user))
Example #8
0
def handle_delete_habit(bot, update):
    user = User.get(update.user_id)
    habit = Habit.get(update.cmd_args['habit_id'])
    if habit:
        execute_database_command(f'DELETE FROM habits WHERE id = {habit.id};')
        ru_text = f'Привычка *{habit.label}* удалена'
        en_text = f'The habit *{habit.label}* has been deleted'
        text = ru_text if user.language_code == 'ru' else en_text
    else:
        ru_text = f'Такой привычки не существует'
        en_text = f'This habit does not exists'
        text = ru_text if user.language_code == 'ru' else en_text

    bot.send_message(update.user_id, text)
def handle_kick_lazy_ass_query(call):
    habit_id = int(call.data.split('/')[1])
    habit = Habit.get(habit_id)
    user = User.get(habit.user_id)

    judge = User.get(call.message.chat.id)
    ru_text = f'{get_user_naming(judge, "Твой друг")} ' \
              f'напоминает тебе, что ты обещал "*{habit.label}*"'
    en_text = f'{get_user_naming(judge, "Your friend")} ' \
              f'reminds you that you promised "*{habit.label}*"'
    text = ru_text if user.language_code == 'ru' else en_text
    try:
        bot.send_message(user.id, text, parse_mode='Markdown')
        bot.send_sticker(user.id, random.choice(remind_stickers))
    except Exception:
        pass

    try:
        bot.send_message(judge.id,
                         'Сделано!' if user.language_code == 'ru' else 'Done!')
    except:
        pass
Example #10
0
def promise_receive(message):
    user = User.get(message.chat.id)

    # Назначаем привычку
    habit = Habit(message.chat.id, preparing_habits[message.chat.id]['label'],
                  preparing_habits[message.chat.id]['days_of_week'],
                  preparing_habits[message.chat.id]['time_array'],
                  preparing_habits[message.chat.id]['fine']).save()

    # Снимаем штрафы с пригласившего
    if user.referrer:
        referrer = User.get(user.referrer)
        referrer.satisfy_fines(CheckStatus.WORKED.name)

        ru_text_ref = f'{get_user_naming(user, "Твой друг")} ' \
                      f'назначил свою первую привычку. ' \
                      f'За успешно проведённые социальные работы ' \
                      f'с тебя снимаются все обвинения и твои штрафы аннулируются.'
        en_text_ref = f'{get_user_naming(user, "Your friend")} ' \
                      f'has assigned his first habit. ' \
                      f'For successful social work all charges ' \
                      f'against you and your fines are canceled.'
        text_ref = ru_text_ref if referrer.language_code == 'ru' else en_text_ref

        bot.send_message(referrer.id, text_ref)

    if preparing_habits[message.chat.id]['with_judge']:
        ru_text = 'Осталось назначить судью. Просто отправь другу сообщение ниже👇'
        en_text = 'It remains to assign the judge. Just send the message below to a friend👇'
        text = ru_text if user.language_code == 'ru' else en_text

        bot.send_message(message.chat.id,
                         text,
                         reply_markup=types.ReplyKeyboardRemove())

        ru_days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
        en_days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
        days = ru_days if user.language_code == 'ru' else en_days

        check_days = re.sub(
            r'\s+', ' ', ' '.join([
                day if day_of_week
                in preparing_habits[message.chat.id]['days_of_week'] else ''
                for day_of_week, day in enumerate(days)
            ]))
        check_time = ' '.join(preparing_habits[message.chat.id]['time_array'])

        ru_text = f'{get_user_naming(user, "Твой друг")} хочет, ' \
                  f'чтобы ты стал его судьёй на привычке *{habit.label}*.\n\n' \
                  f'Дни недели: *{check_days}*\n' \
                  f'Время проверки: *{check_time}*\n' \
                  f'Длительность: *3 недели*\n\n' \
                  f'За каждый провал {get_user_naming(user, "твой друг")} обязуется заплатить тебе *${habit.fine}*'
        en_text = f'{get_user_naming(user, "Your friend")} wants you ' \
                  f'to be the judge on the habit *{habit.label}*.\n\n' \
                  f'Days of week: *{check_days}*\n' \
                  f'Checks time: *{check_time}*\n' \
                  f'Duration: *3 weeks*\n\n' \
                  f'For each fail {get_user_naming(user, "your friend")} agrees to pay you *${habit.fine}*'
        text = ru_text if user.language_code == 'ru' else en_text

        bot.send_message(message.chat.id,
                         text,
                         reply_markup=markups.get_judge_markup(
                             user.id, habit.id),
                         parse_mode='Markdown')
    else:
        schedule_native, schedule_utc = get_schedule(
            preparing_habits[message.chat.id]['days_of_week'],
            preparing_habits[message.chat.id]['time_array'],
            User.get(message.chat.id).timezone,
        )

        for check_native, check_utc in zip(
                schedule_native, schedule_utc):  # нужно оптимизировать
            Check(habit.id, check_native, check_utc).save()
        del preparing_habits[message.chat.id]

        ru_text = 'Ну что ж, посмотрим, какой ты крутой. Удачи!'
        en_text = "Well, let's see how cool you are. Good luck!"
        text = ru_text if user.language_code == 'ru' else en_text

        bot.send_message(message.chat.id,
                         text,
                         reply_markup=markups.get_main_menu_markup(
                             message.chat.id))
        bot.send_sticker(message.chat.id, 'CAADAgADWQIAAsY4fgsQX6OJTX_IOgI')
Example #11
0
def handle_check_query(call):
    data = ast.literal_eval(call.data.split('/')[1])

    check = Check.get(data['check_id'])
    check.status = data['status']
    check.save()

    habit = Habit.get(check.habit_id)

    user = User.get(call.message.chat.id)

    called_button_label = call.message.json['reply_markup']['inline_keyboard'][0][0]['text'] if \
        data['status'] == CheckStatus.SUCCESS.name else \
        call.message.json['reply_markup']['inline_keyboard'][0][1]['text']

    try:
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            text=call.message.text,
            message_id=call.message.message_id,
            reply_markup=markups.get_check_result_inline_markup(
                called_button_label),
            parse_mode='HTML')
    except:
        pass

    if data['status'] == CheckStatus.SUCCESS.name:
        user.score += habit.fine
        user.save()

        ru_text = f'{random.choice(ru_success_phrases)}\n\n*+{habit.fine} очков*'
        en_text = f'{random.choice(en_success_phrases)}\n\n*+{habit.fine} points*'
        text = ru_text if user.language_code == 'ru' else en_text

        try:
            bot.send_message(call.message.chat.id, text, parse_mode='Markdown')
            bot.send_sticker(call.message.chat.id,
                             random.choice(success_stickers))
        except:
            pass

        if habit.judge:
            judge = User.get(habit.judge)

            ru_text_judge = f'{get_user_naming(user, "Твой друг")} выполнил обещание *{habit.label}*'
            en_text_judge = f'{get_user_naming(user, "Your friend")} fulfilled the promise *{habit.label}*'
            text_judge = ru_text_judge if judge.language_code == 'ru' else en_text_judge

            try:
                bot.send_message(judge.id, text_judge, parse_mode='Markdown')
            except Exception:
                pass
    else:
        if habit.judge:
            user_violations_with_judge(user.id, habit.judge)
        else:
            try:
                bot.send_sticker(call.message.chat.id,
                                 random.choice(fail_stickers))
            except:
                pass
            user_violations(call.message)

    suggest_new_habit(user, habit)
Example #12
0
def promise_receive(message):
    user = User.get(message.chat.id)

    habit = Habit(message.chat.id, preparing_habits[message.chat.id]['label'],
                  preparing_habits[message.chat.id]['days_of_week'],
                  preparing_habits[message.chat.id]['time_array'],
                  preparing_habits[message.chat.id]['fine']).save()

    if preparing_habits[message.chat.id]['with_judge']:
        ru_text = 'Осталось назначить судью. Просто отправь другу сообщение ниже👇'
        en_text = 'It remains to assign the judge. Just send the message below to a friend👇'
        text = ru_text if user.language_code == 'ru' else en_text

        bot.send_message(message.chat.id,
                         text,
                         reply_markup=types.ReplyKeyboardRemove())

        ru_days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
        en_days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
        days = ru_days if user.language_code == 'ru' else en_days

        check_days = re.sub(
            r'\s+', ' ', ' '.join([
                day if day_of_week
                in preparing_habits[message.chat.id]['days_of_week'] else ''
                for day_of_week, day in enumerate(days)
            ]))
        check_time = ' '.join(preparing_habits[message.chat.id]['time_array'])

        ru_text = f'{get_user_naming(user, "Твой друг")} хочет, ' \
                  f'чтобы ты стал его судьёй на привычке *{habit.label}*.\n\n' \
                  f'Дни недели: *{check_days}*\n' \
                  f'Время проверки: *{check_time}*\n' \
                  f'Длительность: *3 недели*\n\n' \
                  f'За каждый провал {get_user_naming(user, "твой друг")} обязуется заплатить тебе *${habit.fine}*'
        en_text = f'{get_user_naming(user, "Your friend")} wants you ' \
                  f'to be the judge on the habit *{habit.label}*.\n\n' \
                  f'Days of week: *{check_days}*\n' \
                  f'Checks time: *{check_time}*\n' \
                  f'Duration: *3 weeks*\n\n' \
                  f'For each fail {get_user_naming(user, "your friend")} agrees to pay you *${habit.fine}*'
        text = ru_text if user.language_code == 'ru' else en_text

        bot.send_message(message.chat.id,
                         text,
                         reply_markup=markups.get_judge_markup(
                             user.id, habit.id),
                         parse_mode='Markdown')
    else:
        ru_text = 'Ну что ж, посмотрим, какой ты крутой. Удачи!'
        en_text = "Well, let's see how cool you are. Good luck!"
        text = ru_text if user.language_code == 'ru' else en_text

        schedule_native, schedule_utc = get_schedule(
            preparing_habits[message.chat.id]['days_of_week'],
            preparing_habits[message.chat.id]['time_array'],
            User.get(message.chat.id).timezone,
        )

        for check_native, check_utc in zip(
                schedule_native, schedule_utc):  # нужно оптимизировать
            Check(habit.id, check_native, check_utc).save()

        bot.send_message(message.chat.id,
                         text,
                         reply_markup=markups.get_main_menu_markup(
                             message.chat.id))
        bot.send_sticker(message.chat.id, 'CAADAgADWQIAAsY4fgsQX6OJTX_IOgI')

    del preparing_habits[message.chat.id]