Пример #1
0
def __get_allowed_item_names(items_data: EntitiesData,
                             not_allowed_item_names: List[str]) -> List[str]:
    result = []
    for item_design_data in items_data.values():
        if ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME in item_design_data.keys():
            item_name = item_design_data[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME]
            if item_name:
                item_name = core.fix_allowed_value_candidate(item_name)
                if len(item_name) < settings.MIN_ENTITY_NAME_LENGTH:
                    result.append(item_name)
                else:
                    item_name_parts = item_name.split(' ')
                    for item_name_part in item_name_parts:
                        part_length = len(item_name_part)
                        length_matches = part_length > 1 and part_length < settings.MIN_ENTITY_NAME_LENGTH
                        is_proper_name = item_name_part == item_name_part.upper(
                        )
                        if length_matches and is_proper_name:
                            try:
                                int(item_name_part)
                                continue
                            except:
                                if item_name_part not in not_allowed_item_names:
                                    result.append(item_name_part)
    if result:
        result = list(set(result))
    return result
Пример #2
0
def __get_title_upgrades(upgrades_infos_count: int,
                         items_data: EntitiesData) -> str:
    items_names_list = utils.format.get_or_list(
        sorted(item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME]
               for item_info in items_data.values()))
    result = f'{upgrades_infos_count} crafting recipes requiring: {items_names_list}'
    return result
Пример #3
0
def __prepare_top_fleets(fleets_data: EntitiesData) -> List[Tuple]:
    result = [
        (position,
         escape_markdown(fleet_info[fleet.FLEET_DESCRIPTION_PROPERTY_NAME]),
         fleet_info['Trophy'], fleet_info['Score'])
        for position, fleet_info in enumerate(fleets_data.values(), start=1)
    ]
    return result
Пример #4
0
def __get_upgrades_for(item_id: str, items_data: EntitiesData) -> List[Optional[EntityInfo]]:
    # iterate through item_design_data and return every item_design containing the item id in question in property 'Ingredients'
    result = []
    for item_info in items_data.values():
        ingredient_item_ids = list(__get_ingredients_dict(item_info['Ingredients']).keys())
        if item_id in ingredient_item_ids:
            result.append(item_info)
    if not result:
        result = [None]
    return result
Пример #5
0
async def get_current_events_details(
        situations_data: EntitiesData, chars_data: EntitiesData,
        collections_data: EntitiesData, items_data: EntitiesData,
        missions_data: EntitiesData, rooms_data: EntitiesData,
        utc_now: datetime) -> List[entity.EntityDetails]:
    current_situations_infos = __get_current_situations_infos(
        situations_data.values(), utc_now)
    result = __create_situations_details_list_from_infos(
        current_situations_infos, situations_data, chars_data,
        collections_data, items_data, missions_data, rooms_data, utc_now)
    return result
Пример #6
0
def __get_trophies(fleet_info: EntityInfo, fleet_users_data: EntitiesData,
                   **kwargs) -> Optional[str]:
    result = None
    trophy = fleet_info.get('Trophy')
    if trophy is not None:
        result = trophy
    else:
        result = sum(
            int(user_info.get('Trophy', '0'))
            for user_info in fleet_users_data.values())
    return result
Пример #7
0
def __prepare_top_captains(users_data: EntitiesData, skip: int,
                           take: int) -> List[Tuple]:
    start = skip + 1
    end = skip + take
    result = [
        (position,
         escape_markdown(user_info[user.USER_DESCRIPTION_PROPERTY_NAME]),
         escape_markdown(user_info[fleet.FLEET_DESCRIPTION_PROPERTY_NAME]),
         user_info['Trophy'])
        for position, user_info in enumerate(users_data.values(), start=start)
        if position >= start and position <= end
    ]
    return result
Пример #8
0
def __get_stars(fleet_info: EntityInfo,
                fleet_users_data: EntitiesData,
                max_tourney_battle_attempts: int = None,
                retrieved_at: datetime = None,
                **kwargs) -> Optional[str]:
    result = None
    stars = fleet_info.get('Score')
    if stars is not None and stars != '0':
        result = stars
        if max_tourney_battle_attempts is not None and fleet_users_data and retrieved_at:
            try:
                attempts_left = sum([
                    max_tourney_battle_attempts -
                    user.__get_tourney_battle_attempts(user_info, retrieved_at)
                    for user_info in fleet_users_data.values()
                ])
                result += f' ({attempts_left} attempts left)'
            except TypeError:
                pass
    return result
Пример #9
0
def __prepare_top_fleets(
        fleets_data: EntitiesData) -> List[Tuple[int, str, str, str, str]]:
    """
    Returns:
    List[
        Tuple[
            fleet rank (int),
            fleet name (str),
            fleet trophies (str),
            fleet stars (str),
            number of approved members (str)
        ]
    ]
    """
    result = [
        (position,
         escape_markdown(fleet_info[fleet.FLEET_DESCRIPTION_PROPERTY_NAME]),
         fleet_info['Trophy'], fleet_info['Score'],
         fleet_info['NumberOfApprovedMembers'])
        for position, fleet_info in enumerate(fleets_data.values(), start=1)
    ]
    return result
Пример #10
0
async def get_fleet_users_stars_from_tournament_data(
        ctx,
        fleet_info: EntityInfo,
        fleet_data: EntitiesData,
        user_data: EntitiesData,
        retrieved_date: datetime,
        max_tourney_battle_attempts: Optional[int] = None,
        as_embed: bool = settings.USE_EMBEDS) -> Union[List[Embed], List[str]]:
    fleet_id = fleet_info[FLEET_KEY_NAME]
    fleet_users_infos = {}
    if fleet_id in fleet_data.keys():
        fleet_info[top.DIVISION_DESIGN_KEY_NAME] = fleet_data[fleet_id][
            top.DIVISION_DESIGN_KEY_NAME]
        fleet_users_infos = dict({
            user_info[USER_KEY_NAME]: user_info
            for user_info in user_data.values()
            if user_info[FLEET_KEY_NAME] == fleet_id
        })
    return await get_fleet_users_stars_from_info(ctx,
                                                 fleet_info,
                                                 fleet_users_infos,
                                                 max_tourney_battle_attempts,
                                                 retrieved_at=retrieved_date,
                                                 as_embed=as_embed)
Пример #11
0
def __get_fleet_sheet_lines(fleet_users_data: EntitiesData,
                            retrieved_at: datetime,
                            max_tourney_battle_attempts: int = None,
                            fleet_name: str = None,
                            include_player_id: bool = False,
                            include_fleet_id: bool = False,
                            include_division_name: bool = False,
                            include_pvp_stats: bool = False,
                            sort_lines: bool = True) -> List[Any]:
    titles = list(FLEET_SHEET_COLUMN_NAMES.keys())
    include_tourney_battle_attempts = max_tourney_battle_attempts is not None
    if include_tourney_battle_attempts:
        titles.append('Tournament attempts left')
        titles.append('Star value')
    if include_division_name:
        titles.append('Division')
    if include_player_id:
        titles.append('Player ID')
    if include_fleet_id:
        titles.append('Fleet ID')
    if include_pvp_stats:
        titles.extend((
            'PvP wins',
            'PvP losses',
            'PvP draws',
            'Defense wins',
            'Defense losses',
            'Defense draws',
        ))

    result = []
    for user_info in fleet_users_data.values():
        last_login_date = user_info.get('LastLoginDate')
        alliance_join_date = user_info.get('AllianceJoinDate')
        logged_in_ago = None
        joined_ago = None
        if last_login_date:
            logged_in_ago = retrieved_at - utils.parse.pss_datetime(
                last_login_date)
        if alliance_join_date:
            joined_ago = retrieved_at - utils.parse.pss_datetime(
                alliance_join_date)
        if fleet_name is None and FLEET_DESCRIPTION_PROPERTY_NAME in user_info.keys(
        ):
            fleet_name = user_info[FLEET_DESCRIPTION_PROPERTY_NAME]
        line = [
            utils.format.datetime_for_excel(retrieved_at),
            fleet_name or user_info.get(
                FLEET_DESCRIPTION_PROPERTY_NAME,
                user_info.get('Alliance', {}).get(
                    FLEET_DESCRIPTION_PROPERTY_NAME, '')),
            user_info.get(user.USER_DESCRIPTION_PROPERTY_NAME, ''),
            user_info.get('AllianceMembership', ''),
            utils.convert.pss_timestamp_to_excel(last_login_date),
            int(user_info['Trophy']) if 'Trophy' in user_info else '',
            int(user_info['HighestTrophy'])
            if 'HighestTrophy' in user_info else '',
            int(user_info['AllianceScore'] if 'AllianceScore' in
                user_info else ''),
            utils.convert.pss_timestamp_to_excel(alliance_join_date),
            int(user_info['CrewDonated'])
            if 'CrewDonated' in user_info else '',
            int(user_info['CrewReceived'])
            if 'CrewReceived' in user_info else '',
            utils.format.timedelta(logged_in_ago,
                                   include_relative_indicator=False),
            utils.format.timedelta(joined_ago,
                                   include_relative_indicator=False),
        ]
        if include_tourney_battle_attempts:
            attempts_left = None
            attempts = user.__get_tourney_battle_attempts(
                user_info, retrieved_at)
            if attempts is not None and max_tourney_battle_attempts:
                attempts_left = max_tourney_battle_attempts - attempts
            line.append('' if attempts_left is None else attempts_left)

            star_value = user_info.get('StarValue')
            if star_value is None:
                star_value, _ = user.get_star_value_from_user_info(user_info)
            line.append('' if star_value is None else star_value)
        if include_division_name:
            line.append(
                get_division_name(
                    user_info.get('Alliance',
                                  {}).get(top.DIVISION_DESIGN_KEY_NAME)))
        if include_player_id:
            line.append(user_info.get(USER_KEY_NAME, ''))
        if include_fleet_id:
            line.append(user_info.get(FLEET_KEY_NAME, ''))
        if include_pvp_stats:
            line.extend((
                user_info.get('PVPAttackWins', ''),
                user_info.get('PVPAttackLosses', ''),
                user_info.get('PVPAttackDraws', ''),
                user_info.get('PVPDefenceWins', ''),
                user_info.get('PVPDefenceLosses', ''),
                user_info.get('PVPDefenceDraws', ''),
            ))
        result.append(line)

    if sort_lines:
        result = sorted(result,
                        key=lambda x: (lookups.ALLIANCE_MEMBERSHIP_LOOKUP.
                                       index(x[3]), -x[7], -x[5], x[2]))
    result.insert(0, titles)
    return result
Пример #12
0
async def get_fleet_users_stars_from_info(
        ctx: Context,
        fleet_info: EntityInfo,
        fleet_users_infos: EntitiesData,
        max_tourney_battle_attempts: int,
        retrieved_at: datetime = None,
        as_embed: bool = settings.USE_EMBEDS) -> Union[List[Embed], List[str]]:
    utc_now = utils.get_utc_now()
    fleet_name = fleet_info[FLEET_DESCRIPTION_PROPERTY_NAME]
    division = lookups.DIVISION_DESIGN_ID_TO_CHAR[fleet_info[
        top.DIVISION_DESIGN_KEY_NAME]]

    fleet_users_infos = entity.sort_entities_by(
        list(fleet_users_infos.values()), [('AllianceScore', int, True),
                                           (USER_KEY_NAME, int, False)])
    fleet_users_infos_count = len(fleet_users_infos)

    title = f'{fleet_name} member stars (division {division})'
    display_attempts = False
    lines = []
    for i, user_info in enumerate(fleet_users_infos, 1):
        stars = user_info['AllianceScore']
        user_name = escape_markdown(
            user_info[user.USER_DESCRIPTION_PROPERTY_NAME])
        fleet_membership = user_info.get('AllianceMembership')
        if i < fleet_users_infos_count:
            difference = int(user_info['AllianceScore']) - int(
                fleet_users_infos[i]['AllianceScore'])
        else:
            difference = 0
        user_rank = lookups.get_lookup_value_or_default(
            lookups.ALLIANCE_MEMBERSHIP,
            fleet_membership,
            default=fleet_membership)
        attempts_left = ''
        attempts = user.__get_tourney_battle_attempts(user_info, retrieved_at
                                                      or utc_now)
        if attempts is not None and max_tourney_battle_attempts:
            display_attempts = True
            attempts_left = f'{max_tourney_battle_attempts - attempts}, '
        lines.append(
            f'**{i}.** {stars} (+{difference}) {emojis.star} {user_name} ({attempts_left}{user_rank})'
        )

    properties_attempts = 'Attempts left, ' if display_attempts else ''
    properties_text = f'Properties displayed: Rank. Stars (Difference to next) Player name ({properties_attempts}Fleet rank)'
    if retrieved_at is not None:
        footer_text = utils.datetime.get_historic_data_note(retrieved_at)
    else:
        footer_text = None

    if as_embed:
        if footer_text:
            footer_text = '\n'.join((properties_text, footer_text))
        else:
            footer_text = properties_text
        colour = utils.discord.get_bot_member_colour(ctx.bot, ctx.guild)
        icon_url = await sprites.get_download_sprite_link(
            fleet_info.get('AllianceSpriteId'))
        result = utils.discord.create_basic_embeds_from_description(
            title,
            description=lines,
            colour=colour,
            icon_url=icon_url,
            footer=footer_text)
        return result
    else:
        lines.insert(0, f'**{title}**')
        lines.append(f'_{properties_text}_')
        if footer_text:
            lines.append(f'```{footer_text}```')
        return lines
Пример #13
0
def __get_footer_upgrades(items_data: EntitiesData) -> str:
    items_names = utils.format.get_and_list(
        sorted(item_info[ITEM_DESIGN_DESCRIPTION_PROPERTY_NAME]
               for item_info in items_data.values()))
    result = f'Also found the following items that can\'t be upgraded: {items_names}'
    return result
Пример #14
0
def __flatten_raw_data(data: EntitiesData) -> List[EntityInfo]:
    flat_data = []
    for row in data.values():
        result_row = __flatten_raw_entity(row)
        flat_data.append(result_row)
    return flat_data