示例#1
0
async def open_session(message: types.Message):
    """
    Переключает админа на этап заполнения
    """
    state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
    await state.set_state('fill_id')
    await message.reply('state changed to fill_id')
示例#2
0
async def add_participant(message: types.Message):
    """
    Добавляет участника или участников. При форварде сообщения участника -- приглашает ко вводу
    его имени и премии. При вводе нескольких участников -- парсит их и добавляет всех.
    """
    with dp.current_state(chat=message.chat.id,
                          user=message.from_user.id) as state:
        if message.text.lower() == 'ok':
            await state.set_state('')
            await start_vote((await state.get_data())['participants'])
            return
        forward = message.forward_from
        id = forward.id if forward else int(
            message.text) if message.text.isdigit() else None
        if id:
            await state.update_data({'participant_id': id})
            await state.set_state('fill_name')
            await message.reply('state changed to fill_name')
        else:
            exist_participants = (await state.get_data()).get('participants')
            participants = parse_participants(message.text)
            participants = {**(exist_participants or {}), **participants}
            await state.update_data({'participants': participants})
            await state.set_state('fill_id')
            await message.reply('Добавлены!')
示例#3
0
async def start_vote_for_one(participant_id: int, bonus: int,
                             all_participants: Dict):
    """
    Запускает голосование для пользователя. Генерирует ему структуру из кандидатов и
    инициализирует процесс голосования
    """
    participant_state = dp.current_state(chat=participant_id,
                                         user=participant_id)
    candidates = {
        id: [name, 0]
        for id, (name, _) in all_participants.items() if id != participant_id
    }
    await participant_state.update_data({
        'candidates': candidates,
        'vote_message_id': None,
        'bonus': bonus,
        'completed': False,
    })
    await bot.send_message(participant_id, (
        'Привет! Мы начинаем голосование за премии.\n'
        'Тебе выдано 10% зарплаты, которую на самом деле тебе не выплачивали, чтобы сегодня '
        'мы все могли немного повлиять друг на друга. Будь честен к себе и окружающим, '
        'отнесись к событию серьёзно.\n'
        'Выбери для себя несколько критериев, которые реально важны для тебя и команды и '
        'оцени кандидатов по этим критериям. Я бы хотел, чтобы ты учитывал также '
        'полную/неполную ставку и сколько человек отработал за последние два месяца, '
        'но решение только за тобой.\n'
        'У тебя будет достаточно времени, чтобы подумать, но не откладывай, начни прямо сейчас.'
    ))
    await send_vote_status(participant_state)
示例#4
0
async def drop_session(message: types.Message):
    """
    Обнуляет текущий набор сессии
    """
    with dp.current_state(chat=message.chat.id,
                          user=message.from_user.id) as state:
        await state.update_data({'participants': {}})
        await state.set_state('fill_id')
示例#5
0
async def add_participant(message: types.Message):
    """
    Заполняет имя участника
    """
    with dp.current_state(chat=message.chat.id,
                          user=message.from_user.id) as state:
        await state.update_data({'participant_name': message.text})
        await state.set_state('fill_bonus')
        await message.reply('state changed to fill_bonus')
示例#6
0
async def add_participant(message: types.Message):
    """
    Заполняет премию участника
    """
    with dp.current_state(chat=message.chat.id,
                          user=message.from_user.id) as state:
        data = await state.get_data()
        participants = data.get('participants', {})
        participants[data['participant_id']] = (data['participant_name'],
                                                int(message.text))
        await state.update_data({'participants': participants})
        await state.set_state('fill_id')
        await message.reply(str(participants))
示例#7
0
async def voting(callback_query: types.CallbackQuery):
    """
    Обрабатывает нажатие на клавиши выбора и меняет сообщение на приглашение к вводу
    """
    with dp.current_state(chat=callback_query.from_user.id, user=callback_query.from_user.id) as \
            state:
        data = await state.get_data()
        await bot.edit_message_text(
            f"Голосуй за {data['candidates'][callback_query.data][0]}. Вводи сколько готов отдать.",
            callback_query.from_user.id,
            data['vote_message_id'],
        )
        await state.update_data({'candidate': callback_query.data})
        await state.set_state('bonus_input')
        await bot.answer_callback_query(callback_query.id)
示例#8
0
async def start_session(message: types.Message):
    """
    Выводит список будущей сессии
    """
    with dp.current_state(chat=message.chat.id,
                          user=message.from_user.id) as state:
        data = await state.get_data()
        participants = data['participants']
        formatted_participants = format_participants(participants)
        if formatted_participants:
            await message.reply('Введи ОК, когда хватит')
            await message.reply(formatted_participants)
        else:
            await message.reply('Пусто')
        await state.set_state('fill_id')
示例#9
0
async def bonus_input(message: types.Message):
    """
    Обрабатывает ввод пользователя и присваивает голос выбранному кандидату
    """
    with dp.current_state(chat=message.chat.id,
                          user=message.from_user.id) as state:
        data = await state.get_data()
        try:
            bonus = int(message.text)
        except ValueError:
            await message.reply('Это не число даже')
            return
        if bonus < 0:
            await message.reply('Соси жопу, нельзя в минус')
            return

        candidate = data['candidate']
        candidates = data['candidates']
        candidates[candidate] = candidates[candidate][0], bonus
        await state.update_data({'candidates': candidates})
        await send_vote_status(state)
示例#10
0
async def voting(callback_query: types.CallbackQuery):
    """
    Обрабатывает нажатие на клавишу "готово" в сообщении голосовании
    """
    with dp.current_state(chat=callback_query.from_user.id, user=callback_query.from_user.id) as \
            state:
        data = await state.get_data()
        if calculate_rest(data['bonus'], data['candidates']) != 0:
            await bot.answer_callback_query(callback_query.id,
                                            'Остаток не равен 0')
        else:
            await state.update_data({'completed': True})
            logger.info(f"{state.user} закончил")
            await bot.edit_message_text(
                'Голосование закончено, ожидаем оставшихся',
                callback_query.from_user.id,
                data['vote_message_id'],
            )
            await check_voting_end()
            await state.set_state('end')
            await bot.answer_callback_query(callback_query.id)