def registration_subscriber(chat_id: int, text: str) -> Answer: """Логика сохранения подписчика""" try: pk = get_primary_key_from_start_message(text) members_group = MembersGroup.objects.get(pk=pk) except ValueError: return Answer("Получите ссылку-приглашение для вашей команды") subscriber, created = Subscriber.objects.get_or_create( tg_chat_id=chat_id, members_group=members_group) if created: text = AdminMessage.objects.get(key='start').text keyboard = get_acquaintance_next_keyboard(1) return Answer(text, keyboard=keyboard) return Answer("Вы уже зарегистрированы")
def get_next_question(question_pk): """Возвращает следующий вопрос с клавиатурой""" survey_question = BeginSurveyQuestion.objects.get(pk=question_pk + 1) keyboard = get_keyboard_for_question(survey_question.pk) text = f"{survey_question.get_type_display()}\n\n{survey_question.text}" answer = Answer(text, keyboard=keyboard) return answer
def start_survey(chat_id): """Функция начинает опрос""" survey_question = BeginSurveyQuestion.objects.filter(type="body")[0] keyboard = get_keyboard_for_question(survey_question.pk) text = f"{survey_question.get_type_display()}\n\n{survey_question.text}" answer = Answer(text, keyboard=keyboard, chat_id=chat_id) return answer
def ask_about_task(): """Функция рассылает вопросы о выполнении заданий""" # TODO сделать функцию вызываемой для одного человека # TODO текст можно засунуть в БД log.info("Starting to collect the report of selected tasks") for subscriber in Subscriber.objects.filter(is_active=True): log.info(f"send report blank to {subscriber.tg_chat_id}") today = timezone.now().date() if subscriber.day == 1: text = "Ну что, по основным моментам мы с тобой прошлись. Если остались вопросы, " \ "то задавай их в нашем Telegam чате tg://join?invite=AAAAAEaDF5qIQRwLVR59cQ " \ "или на странице в Инстаграм @iman.club На этом все, ты выполняй задания, " \ "я буду их анализировать и через месяц покажу на сколько ты прибавил в " \ "каждом пункте своего развития. Алга, брат! Бисмиллях!\n\n" else: text = "И снова, Ас-саляму ‘алейкум, брат! Как прошел день? Что из запланированного получилось сделать? " \ "Поделись со мной и я внесу твой результат в наш отчет.\n\n" tasks = [ x.pk for x in RecordDailyTask.objects.filter( subscriber=subscriber, date=today, is_selected=True) ] if len(tasks) < 1: log.info(f"{subscriber.tg_chat_id} no select task") continue task_text, keyboard = ask_single_task(tasks) Answer(text + task_text, keyboard=keyboard, chat_id=subscriber.tg_chat_id, message_key="ask_about_tasks").send()
def set_task_to_done(task_id, task_status, next_tasks_list, chat_id, message_id): if task_status: task = RecordDailyTask.objects.get(pk=task_id) task.set_done() if len(next_tasks_list) == 0: subscriber = Subscriber.objects.get(tg_chat_id=chat_id) text = AdminMessage.objects.get(key="other_day_survey").text if subscriber.day == 1: subscriber.day = 2 subscriber.save() else: ... tg_delete_message(chat_id=chat_id, message_id=message_id) Answer(text, keyboard=get_default_keyboard(), chat_id=chat_id).send() return text, keyboard = ask_single_task(next_tasks_list) return Answer(text, keyboard=keyboard, chat_id=chat_id)
def text_message_service(chat_id: int, text: str): """Обработка текстовых сообщений""" if text == '📈Статистика': ... elif Subscriber.objects.get(tg_chat_id=chat_id).step == "ask_sub_purpose": admin_message = AdminMessage.objects.get(pk=4) text = admin_message.text keyboard = get_acquaintance_next_keyboard(4) return Answer(text, keyboard=keyboard, chat_id=chat_id)
def get_task_keyboard(chat_id, task_type, group_pk): task_group = RecordDailyTaskGroup.objects.get(pk=group_pk) tasks = [ x for x in task_group.daily_tasks_records.filter( task__task_type=task_type) ] text = f"{tasks[0].task.get_task_type_display()}\n\n" \ f"1) {tasks[0].task.text}\n" \ f"2) {tasks[1].task.text}\n" \ f"3) {tasks[2].task.text}\n" answer = Answer(text, keyboard=translate_tasks_in_keyboard(tasks), chat_id=chat_id) return answer
def acquaintance(chat_id, step_num): from bot_init.service import get_acquaintance_next_keyboard if step_num == 5: admin_message = AdminMessage.objects.get(pk=step_num + 1) Answer(admin_message.text, keyboard=get_default_keyboard(), chat_id=chat_id).send() subscriber = get_subscriber_by_chat_id(chat_id) subscriber.step = "" subscriber.save() text = 'Начальные данные:\n\n' \ f'Тело: {subscriber.points_body}\n' \ f'Душа: {subscriber.points_spirit}\n' \ f'Дух: {subscriber.points_soul}' Answer(text, keyboard=get_default_keyboard(), chat_id=chat_id).send() return elif step_num == 2: answer = start_survey(chat_id) return answer admin_message = AdminMessage.objects.get(pk=step_num + 1) text = admin_message.text keyboard = get_acquaintance_next_keyboard(step_num + 1) Answer(text, keyboard=keyboard, chat_id=chat_id).send()
def begin_survey(value, begin_question_pk, chat_id): from bot_init.service import get_acquaintance_next_keyboard set_points(chat_id, begin_question_pk, value) if begin_question_pk == 30: admin_message = AdminMessage.objects.get(pk=3) text = admin_message.text keyboard = get_acquaintance_next_keyboard(3) sub = Subscriber.objects.get(tg_chat_id=chat_id) sub.step = "ask_sub_purpose" sub.save() return Answer(text, keyboard=keyboard, chat_id=chat_id) answer = get_next_question(begin_question_pk) answer.chat_id = chat_id return answer
def send_list_with_selected_tasks(): for subscriber in Subscriber.objects.filter(is_active=True): text = "" try: today = timezone.now() tasks = RecordDailyTask.objects.filter(date__day=today.day, date__month=today.month, date__year=today.year, subscriber=subscriber, is_selected=True) for i, st in enumerate( tasks.filter(subscriber=subscriber, is_selected=True)): text += f"{i + 1}. {st.task.text} ({st.task.get_task_type_display()})\n" log.info(f"Send list of tasks ({text}) to {subscriber.tg_chat_id}") Answer(text=text).send(subscriber.tg_chat_id) except Exception as e: log.error(str(e))
def set_task_to_selected_or_unselected(record_daily_task_id, level, chat_id): record_daily_task = RecordDailyTask.objects.get(pk=record_daily_task_id) if not (TIME_LIMITS_FOR_SELECT_TASKS[0] <= (timezone.now().hour + 3) % 24 <= TIME_LIMITS_FOR_SELECT_TASKS[1]): log.info("This time is not suitable for selecting a task") return record_task_group = record_daily_task.group task_type = record_daily_task.task.task_type record_daily_task.switch(level) tasks = record_task_group.daily_tasks_records.filter( task__task_type=task_type).order_by("pk") # TODO выхардкодить индексы text = f"{tasks[0].task.get_task_type_display()}\n\n" \ f"1) {tasks[0].task.text}\n" \ f"2) {tasks[1].task.text}\n" \ f"3) {tasks[2].task.text}\n" return Answer(text, keyboard=translate_tasks_in_keyboard(tasks), chat_id=chat_id)
def send_daily_tasks(): """ Функция рассылает задания для пользователей в кнопках. Происходит отправка заданий категории body с клавиатурой для переключения на другие категории """ week_day = get_week_day() tasks = DailyTask.objects.filter(week_day=week_day) text = get_text(tasks.filter(task_type="body")) for subscriber in Subscriber.objects.filter( is_active=True ): # TODO вынести итерацию в отдельную функцию, чтобы пользователю можно было отправлять индивидуально group = create_daily_task_records(subscriber, tasks) body_tasks = group.daily_tasks_records.filter( task__task_type="body").order_by("pk") keyboard = translate_tasks_in_keyboard(body_tasks) Answer(text, keyboard=keyboard, chat_id=subscriber.tg_chat_id, message_key="ques_tasks").send()
def send_reminders(): for subscriber in Subscriber.objects.filter(is_active=True): reminder_text = Reminder.objects.all().order_by("?")[0].text Answer(reminder_text).send(subscriber.tg_chat_id) log.info(f"Send reminders {reminder_text} to {subscriber.tg_chat_id}")