Exemplo n.º 1
0
async def return_equipment(call: types.CallbackQuery):
    """
    Return all equipment
    """
    user_eq_data = equipment.get_equipment_by_holder(call.message.chat.id)
    # create transfer from user to storehouse
    for eq in user_eq_data:
        transfer.create_transfer(eq["id"], eq["holder"]["id"], 1)
    # move transfer into history
    user_transfers = [
        transfer.get_transfer_by_equipment_id(eq["id"])["id"]
        for eq in user_eq_data
    ]
    list(map(transfer.verify_transfer, user_transfers))
    list(map(transfer.delete_transfer, user_transfers))

    transformed_result = parse_my_equipment_data(user_eq_data)
    username = call.message.chat.username or user.get_user(
        call.message.chat.id)['username']
    user_id = call.message.chat.id
    for admin in user.get_admin_list():
        await bot.send_message(
            chat_id=admin["id"],
            text="{} вернул(а) данную технику:\n{}".format(
                f"@{username}" if username is not None else
                f"[{user_id}](tg://user?id={user_id})",
                transformed_result,
            ),
        )
    await bot.send_message(
        chat_id=user_id,
        text=f"Данная техника была успешно возвращена:\n{transformed_result}\
\n\nЧтобы вернуться в главное меню напишите /start",
    )
Exemplo n.º 2
0
async def equipment_confirmation(admin_id: int, user_id: int, eq_names: list):
    """
    Confirm taking the equipment
    """
    keyboard_interface = buttons.create_inline_markup([{
        'text':
        '\U00002705',
        'callback':
        f'conf_success {user_id}'
    }, {
        'text':
        '\U0000274C',
        'callback':
        f'conf_failed {user_id}'
    }])

    transformed_eq_names = "\n".join(eq_names["equipment_names"])
    username = user.get_user(user_id)["username"]
    user_name = (f"@{username}" if username is not None else f"[{user_id}]\
(tg://user?id={user_id})")
    # save message data
    message = await bot.send_message(
        chat_id=admin_id,
        text=f"Подтвердите передачу техники к {user_name}.\
 Список техники:\n{transformed_eq_names}",
        reply_markup=keyboard_interface,
        parse_mode="Markdown",
    )
    state = dp.current_state()
    messages_list = await state.get_data()
    await state.update_data(admin_messages=messages_list["admin_messages"] +
                            [message])
Exemplo n.º 3
0
def ban_user(user: User, user_id: int, context: CallbackContext):
    if user.id == 1065263859:
        session = database.get_session()
        banned_user = get_user(user_id)
        banned_user.banned = True
        for submission in session.query(Submission).filter(
                Submission.user == banned_user).all():
            submission.flagged = True
        database.commit()
        context.bot.send_message(user.id, f"User {user_id} is banned.")
Exemplo n.º 4
0
def get_user_from_update(update: Update) -> User:
    session = database.get_session()
    user = get_user(update.effective_user.id)

    if user is None:
        username = update.effective_user.username
        if username is None:
            username = update.effective_user.id
        return add_user_with_id(update.effective_user.id,
                                username,
                                mwexpress_config.language)
    else:
        if (user.username == str(user.id) or user.username is None) and update.effective_user.username is not None:
            user.username = update.effective_user.username
            database.commit(session)

    return user
Exemplo n.º 5
0
async def add_equipment_step_2(message: types.Message, state: FSMContext):
    """
    Get name and owner of the equipment
    """
    # get data in format 'equipment name \n user id or username'
    data = message.text.split('\n')
    # get owner data
    owner_data = []
    if data[1].startswith('@'):
        try:
            owner_data = user.get_user_by_username(data[1][1:])
        except Exception:
            await bot.send_message(chat_id=message.chat.id,
                                   text=f'Пользователь с тэгом {data[1]} не\
 найден. Начните добавление техники заново\
 и попробуйте ввести id пользователя')
    elif data[1] == 'Штаб':
        try:
            owner_data = user.get_user_by_username(data[1])
        except Exception:
            await bot.send_message(chat_id=message.chat.id,
                                   text=f'Пользователь с тэгом {data[1]} не\
 найден. Начните добавление техники заново\
 и попробуйте ввести id пользователя')
    else:
        try:
            owner_data = user.get_user(int(data[1]))
        except Exception:
            await bot.send_message(chat_id=message.chat.id, text='Данного\
 пользователя нет в базе данных. Его необходимо\
 зарегистрировать, чтобы добавить технику.\nДля возвращения в\
 главное меню напишите /start')
    if owner_data:
        await state.update_data(eq_name=data[0].strip(), owner=owner_data['id'])
        await bot.send_message(chat_id=message.chat.id,
                               text='Выберите категорию для техники',
                               reply_markup=buttons.create_categories_buttons()
                               )
        await Add_Equipment.next()
    else:
        await state.finish()
Exemplo n.º 6
0
def award_champion():
    mwelog.info("Awarding champion")
    boards = scoreboard.scoreboards
    for language in Language.ENGLISH, Language.TURKISH, Language.ITALIAN:
        if len(boards[language]) > 0:
            first_user = get_user(boards[language][0].user_id)
            mwelog.info("{username} is the champion",
                        username=first_user.username)
            award_achievement(first_user, AchievementType.CHAMPION)
            try:
                mwexpress_bot.bot.send_sticker(first_user.id,
                                               ACHIEVEMENT_STICKER)
                send_message_to_user(mwexpress_bot.bot,
                                     first_user,
                                     first_user.language.get(
                                         Token.CHAMPION_ACH_CONGRATS_MSG),
                                     parse_mode=ParseMode.HTML)
                if mwexpress_config.email_enabled:
                    if first_user.email is None:
                        send_message_to_user(
                            mwexpress_bot.bot,
                            first_user,
                            first_user.language.get(
                                Token.TODAYS_WINNER_WITHOUT_EMAIL),
                            parse_mode=ParseMode.HTML)
                    else:
                        send_message_to_user(
                            mwexpress_bot.bot,
                            first_user,
                            first_user.language.get(
                                Token.TODAYS_WINNER_WITH_EMAIL) %
                            first_user.email,
                            parse_mode=ParseMode.HTML)
                    mwexpress_bot.bot.send_message(
                        mwexpress_config.moderator,
                        f"Todays champion is: {first_user.username}")
            except Exception as ex:
                mwelog.exception(ex)
Exemplo n.º 7
0
def test_user_single_function(user_single_event, sample_user_single_response):
    assert get_user(user_single_event, None) == sample_user_single_response
Exemplo n.º 8
0
    def iterate(self, update: Update, context: CallbackContext):
        with self._iterate_lock:
            new_boards = {
                Language.TURKISH: self.get_scoreboard(Language.TURKISH),
                Language.ENGLISH: self.get_scoreboard(Language.ENGLISH),
                Language.ITALIAN: self.get_scoreboard(Language.ITALIAN)
            }

            for language in Language.ENGLISH, Language.TURKISH, Language.ITALIAN:
                if len(new_boards[language]) > 0:
                    first_user = get_user(new_boards[language][0].user_id)
                    if not user_has_achievement(
                            first_user, AchievementType.BECOME_NUMBER_ONE):
                        award_achievement(first_user,
                                          AchievementType.BECOME_NUMBER_ONE)
                        try:
                            context.bot.send_sticker(first_user.id,
                                                     ACHIEVEMENT_STICKER)
                            context.bot.send_message(
                                first_user.id,
                                first_user.language.get(
                                    Token.BECOME_NUMBER_ONE_ACH_CONGRATS_MSG),
                                parse_mode=ParseMode.HTML)
                        except Exception as ex:
                            mwelog.exception(str(ex))
                    else:
                        if len(self.scoreboards[language]) == 0\
                                or (len(self.scoreboards[language]) > 1 and (self.scoreboards[language][1].user_id == first_user.id)):
                            notification_manager.send_became_first(
                                first_user, context)

                if len(new_boards[language]) > 1 and len(
                        self.scoreboards[language]) > 1:
                    if new_boards[language][1].user_id == self.scoreboards[
                            language][0].user_id:
                        second = get_user(new_boards[language][1].user_id)
                        notification_manager.send_lost_first(second, context)

                if len(new_boards[language]) > 3 and len(
                        self.scoreboards[language]) > 2:
                    if new_boards[language][3].user_id == self.scoreboards[
                            language][2].user_id:
                        fourth_user = get_user(new_boards[language][3].user_id)
                        notification_manager.send_lost_three(
                            fourth_user, context)

                if len(new_boards[language]) > 5 and len(
                        self.scoreboards[language]) > 4:
                    if new_boards[language][5].user_id == self.scoreboards[
                            language][4].user_id:
                        sixth_user = get_user(new_boards[language][5].user_id)
                        notification_manager.send_lost_five(
                            sixth_user, context)

            self.old_scoreboards = self.scoreboards
            self.scoreboards = new_boards
            first_five_now = {
                Language.TURKISH:
                [x.user_id for x in self.scoreboards[Language.TURKISH][:5]],
                Language.ENGLISH:
                [x.user_id for x in self.scoreboards[Language.ENGLISH][:5]],
                Language.ITALIAN:
                [x.user_id for x in self.scoreboards[Language.ITALIAN][:5]]
            }
            for language in Language.TURKISH, Language.ENGLISH, Language.ITALIAN:
                if self._new_first_five_ids[language] != first_five_now[
                        language]:
                    self._old_first_five_ids[
                        language] = self._new_first_five_ids[language]
                    self._new_first_five_ids[language] = first_five_now[
                        language]