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)
def check_users(last_check_utc): now_utc = datetime.strptime(datetime.utcnow().strftime("%Y-%m-%d %H:%M"), "%Y-%m-%d %H:%M") # Нужно исправить checks = execute_database_command( '''SELECT c.id, c.habit_id, c.datetime_native, c.datetime_utc, h.label, h.user_id, h.judge FROM checks c JOIN habits h ON c.habit_id = h.id JOIN users u ON u.id = h.user_id WHERE c.datetime_utc <= %s AND c.datetime_utc > %s AND c.status=%s; ''', (now_utc, last_check_utc, CheckStatus.PENDING.name))[0] for check in checks: check_id, habit_id, datetime_native, datetime_utc, label, user_id, judge_id = check c = Check(habit_id, datetime_native, datetime_utc, CheckStatus.CHECKING.name, check_id) c.save() user = User.get(user_id) ru_text = f'Ты обещал "*{label}*". Ты держишь своё слово?\n\n' \ f'Учти, что за ответ "❌ Нет" нужно будет заплатить штраф' en_text = f'You promised "*{label}*". Are you keeping your promise?\n\n' \ f'Note that you will have to pay a fine for the answer "❌ No"' text = ru_text if user.language_code == 'ru' else en_text try: bot.send_message(user_id, text, reply_markup=markups.get_check_inline_markup( user_id, check_id), parse_mode='Markdown') except Exception: pass if judge_id: judge = User.get(judge_id) ru_text_judge = f'{get_user_naming(user, "Твой друг")} обещал "*{label}*"' en_text_judge = f'{get_user_naming(user, "Your friend")} promised "*{label}*"' text_judge = ru_text_judge if judge.language_code == 'ru' else en_text_judge try: bot.send_message(judge_id, text_judge, reply_markup=markups.get_kick_lazy_ass_markup( judge_id, habit_id), parse_mode='Markdown') except Exception as e: print(e) return now_utc
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))
def check_users(last_check_utc): now_utc = datetime.strptime(datetime.utcnow().strftime("%Y-%m-%d %H:%M"), "%Y-%m-%d %H:%M") # TODO Нужно исправить checks = execute_database_command( '''SELECT c.id, c.habit_id, c.datetime_native, c.datetime_utc, h.label, h.user_id FROM checks c JOIN habits h ON c.habit_id = h.id JOIN users u ON u.id = h.user_id WHERE c.datetime_utc <= %s AND c.datetime_utc > %s AND c.status=%s; ''', (now_utc, last_check_utc, CheckStatus.PENDING.name)) for check in checks: check_id, habit_id, datetime_native, datetime_utc, label, user_id = check c = Check(habit_id, datetime_native, datetime_utc, CheckStatus.CHECKING.name, check_id) c.save() user = User.get(user_id) ru_text = f'Ты обещал *{label}*. Ты держишь своё слово?' en_text = f'You promised *{label}*. Are you keeping your promise?' text = ru_text if user.language_code == 'ru' else en_text bot.send_message(user_id, text, keyboard=keyboards.get_check_keyboard(user, check_id)) return now_utc
def patch(self, request): from logs.models import AuditLog check = get_object_or_404(Check, pk=request.data["id"]) check.last_run = djangotime.now() check.save(update_fields=["last_run"]) status = check.handle_checkv2(request.data) # create audit entry AuditLog.objects.create( username=check.agent.hostname, agent=check.agent.hostname, object_type="agent", action="check_run", message=f"{check.readable_desc} was run on {check.agent.hostname}. Status: {status}", after_value=Check.serialize(check), ) return Response(status)
def default_services(request): return Response(Check.load_default_services())
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')
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)
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]