예제 #1
0
async def format_profile(ctx, platform, p):
    ems = []
    top = {'solo': (10, 25), 'duo': (5, 12), 'squad': (3, 6)}

    if p['totals']['matchesplayed']:
        kdr = p['totals']['wins'] / p['totals']['matchesplayed'] * 100
    else:
        kdr = 0

    fields = [(_('Kills {}',
                 ctx).format(emoji(ctx, "fnskull")), p['totals']['kills']),
              (_('Victory Royale! {}',
                 ctx).format(emoji(ctx, "fnvictoryroyale")),
               f"{p['totals']['wins']} ({kdr:.2f})"),
              (_('Kill Death Ratio', ctx), p['totals']['kd']),
              (_('Time Played', ctx), timestamp(p['totals']['minutesplayed']))]

    ems.append(
        discord.Embed(description=_('Overall Statistics', ctx),
                      color=random_color()))
    ems[0].set_author(name=p['username'])
    for name, value in fields:
        ems[0].add_field(name=str(name), value=str(value))

    for n, mode in enumerate(('solo', 'duo', 'squad')):
        kdr = p[platform][f'winrate_{mode}']
        fields = [
            (_('Score', ctx), p[platform][f'score_{mode}']),
            (_('Kills {}',
               ctx).format(emoji(ctx,
                                 "fnskull")), p[platform][f'kills_{mode}']),
            (_('Total Battles', ctx), p[platform][f'matchesplayed_{mode}']),
            (_('Victory Royale! {}', ctx).format(emoji(ctx,
                                                       "fnvictoryroyale")),
             f"{p[platform][f'placetop1_{mode}']} ({kdr}%)"),
            (_('Top {}', ctx).format(emoji(ctx, "fnleague")),
             'Top {}: {}\nTop {}: {}'.format(
                 top[mode][0], p[platform][f'placetop{top[mode][0]}_{mode}'],
                 top[mode][1], p[platform][f'placetop{top[mode][1]}_{mode}'])),
            (_('Kill Death Ratio', ctx), p[platform][f'kd_{mode}']),
            (_('Time Played',
               ctx), timestamp(p[platform][f'minutesplayed_{mode}']))
        ]
        ems.append(
            discord.Embed(description=_('{} Statistics',
                                        ctx).format(mode.title()),
                          color=random_color()))
        ems[n + 1].set_author(name=p['username'])

        for name, value in fields:
            ems[n + 1].add_field(name=str(name), value=str(value))

    return ems
예제 #2
0
async def format_clan(ctx, c):
    page1 = discord.Embed(description=c.description, color=random_color())
    page1.set_author(name=f"{c.name} ({c.tag})")
    page1.set_footer(text=_('Statsy | Powered by the CR API', ctx))
    page2 = copy.deepcopy(page1)
    page2.description = _('Top Players/Donators/Contributors for this clan.',
                          ctx)
    page1.set_thumbnail(url=ctx.cog.cr.get_clan_image(c))

    _donators = list(reversed(sorted(c.member_list,
                                     key=lambda m: m.donations)))

    pushers = []
    donators = []

    for i in range(3):
        if len(c.member_list) < i + 1:
            break
        pushers.append(f"**{c.member_list[i].name}**"
                       f"\n{c.member_list[i].trophies} "
                       f"{emoji(ctx, 'trophy')}\n"
                       f"{c.member_list[i].tag}")
        donators.append(f"**{_donators[i].name}**"
                        f"\n{_donators[i].donations} "
                        f"{emoji(ctx, 'cards')}\n"
                        f"{_donators[i].tag}")

    fields1 = [
        (_('Type', ctx), camel_case(c.type) + ' 📩'),
        (_('Score', ctx),
         str(c.clan_score) + _(' Trophies ', ctx) + str(emoji(ctx, 'trophy'))),
        (_('Donations/Week', ctx), str(c.donations_per_week) +
         _(' Cards ', ctx) + str(emoji(ctx, 'cards'))),
        (_('Location', ctx), c.location.name + ' 🌎'),
        (_('Members', ctx), f"{len(c.member_list)}/50 {emoji(ctx, 'clan')}"),
        (_('Required Trophies',
           ctx), f"{c.required_trophies} {emoji(ctx, 'trophy')}"),
    ]

    fields2 = [(_('Top Players', ctx), '\n\n'.join(pushers)),
               (_('Top Donators', ctx), '\n\n'.join(donators))]

    for f, v in fields1:
        page1.add_field(name=f, value=v)

    for f, v in fields2:
        if v:
            page2.add_field(name=f, value=v)

    return [page1, page2]
예제 #3
0
def e(name):
    """Wrapper to the default emoji function to support brawler names"""
    cog = getattr(get_stack_variable('ctx'), 'cog',
                  None) or get_stack_variable('self')
    name = str(name).lower()
    try:
        brawler = next(
            i for i in cog.constants.characters
            if i.name.lower() == name or (i.tID or '').lower() == name)
    except StopIteration:
        return emoji(name)
    else:
        return emoji(
            next(i for i in cog.constants.player_thumbnails
                 if i.required_hero == brawler.name).sc_id)
예제 #4
0
    async def _card(self, ctx, *, card):
        """Get information about a Clash Royale card."""
        aliases = {
            'log': 'the log',
            'pump': 'elixir collector',
            'skarmy': 'skeleton army',
            'pekka': 'p.e.k.k.a',
            'mini pekka': 'mini p.e.k.k.a',
            'xbow': 'x-bow'
        }
        card = card.lower()
        if card in aliases:
            card = aliases[card]
        constants = self.cr.constants

        found_card = None
        for c in constants.cards:
            if c.name.lower() == card.lower():
                found_card = c

        if found_card is None:
            return await ctx.send("That's not a card!")

        em = await cr.format_card(ctx, found_card)
        try:
            async with self.bot.session.get(utils.emoji(ctx,
                                                        card).url) as resp:
                c = io.BytesIO(await resp.read())
        except AttributeError:
            # new card, no emoji
            await ctx.send(embed=em)
        else:
            await ctx.send(embed=em, files=[discord.File(c, 'card.png')])
예제 #5
0
async def format_deck_link(ctx, d, link, default):
    deck = ''
    elixir = 0
    for n, i in enumerate(d):
        for c in ctx.cog.cr.constants.cards:
            if str(c.id) == i:
                deck += str(emoji(ctx, c.name))
                elixir += c.elixir
                if n == 3:
                    deck += '\n'
                break

    elixir = elixir / len(d)
    deck += f'\n{elixir:.1f}{emoji(ctx, "elixirdrop")} [Copy this deck!]({link}) {emoji(ctx, "copydeck")}'
    em = discord.Embed(title=f'Deck shared by {ctx.author.name}',
                       description=deck,
                       color=random_color())
    if not link.startswith('http'):
        link = 'https://' + link

    if default:
        prefix = (await ctx.bot.get_prefix(ctx.message))[2]
        em.set_footer(text=_('Run `{}link disable` to disable this feature',
                             ctx).format(prefix))
    else:
        em.set_footer(text=_('Statsy | Powered by the CR API', ctx))

    return em
예제 #6
0
def get_chests(ctx, cycle):
    chests = '| ' + str(
        emoji(ctx, 'chest' + cycle[0].name.replace(' Chest', ''))) + ' | '
    chests += ''.join([
        str(emoji(ctx, 'chest' + cycle[x].name.replace(' Chest', '')))
        for x in range(1, 8)
    ])
    special = ''

    for i in range(9, 15):
        try:
            e = emoji(ctx,
                      'chest' + cycle[i].name.replace(' Chest', '').lower())
            special += f"{e}+{cycle[i].index + 1} "
        except IndexError:
            break

    return (chests, special)
예제 #7
0
async def format_chests(ctx, p, c):
    av = ctx.cog.cr.get_clan_image(p)
    em = discord.Embed(color=random_color())
    em.set_author(name=f'{p.name} ({p.tag})', icon_url=av)
    if ctx.bot.psa_message:
        em.description = f'*{ctx.bot.psa_message}*'
    chests = get_chests(ctx, c)
    em.set_thumbnail(
        url=emoji(ctx, 'chest' + c[0].name.replace(' Chest', '').lower()).url)
    em.add_field(name=_('Chests', ctx), value=chests[0])
    em.add_field(name=_('Chests Until', ctx), value=chests[1])
    em.set_footer(text=_('Statsy | Powered by the CR API', ctx))
    return em
예제 #8
0
async def format_stats(ctx, p):
    av = ctx.cog.cr.get_clan_image(p)
    em = discord.Embed(color=random_color())
    if ctx.bot.psa_message:
        em.description = f'*{ctx.bot.psa_message}*'
    em.set_author(name=f'{p.name} ({p.tag})', icon_url=av)
    em.set_thumbnail(url=ctx.cog.cr.get_arena_image(p))

    trophies = f"{p.trophies}/{p.best_trophies} PB {emoji(ctx, 'trophy')}"
    deck = get_deck(ctx, p)

    try:
        clan_name = p.clan.name
        clan_tag = p.clan.tag
        clan_role = camel_case(p.role)
    except AttributeError:
        clan_name = clan_tag = clan_role = None

    try:
        favourite_card = f"{p.current_favourite_card.name} {emoji(ctx, p.current_favourite_card.name)}"
    except AttributeError:
        favourite_card = _('No favourite card :(', ctx)

    embed_fields = [
        (_('Trophies', ctx), trophies, True),
        (_('Level', ctx), f"{p.exp_level} {emoji(ctx, 'experience')}", True),
        (_('Clan Name', ctx),
         f"{clan_name} {emoji(ctx, 'clan')}" if clan_name else None, True),
        (_('Clan Tag', ctx),
         f"{clan_tag} {emoji(ctx, 'clan')}" if clan_tag else None, True),
        (_('Clan Role', ctx),
         f"{clan_role} {emoji(ctx, 'clan')}" if clan_role else None, True),
        (_('War Day Wins',
           ctx), f"{p.war_day_wins} {emoji(ctx, 'clanwar')}", True),
        (_('Favourite Card', ctx), favourite_card, True),
        (_('Battle Deck', ctx), deck, True)
    ]

    for n, v, i in embed_fields:
        if v:
            em.add_field(name=n, value=v, inline=i)
        else:
            if n == _('Clan Name', ctx):
                em.add_field(name=_('Clan', ctx),
                             value=_('None {}',
                                     ctx).format(emoji(ctx, 'noclan')))

    em.set_footer(text=_('Statsy | Powered by the CR API', ctx))

    return em
예제 #9
0
async def format_clan_link(ctx, c, link, default):
    av = ctx.cog.cr.get_clan_image(c)
    if not link.startswith('http'):
        link = 'https://' + link

    em = discord.Embed(
        description=
        f"[Join]({link}) {ctx.author.mention}['s clan! {emoji(ctx, 'clan')}]({link})",
        color=random_color())

    if default:
        prefix = (await ctx.bot.get_prefix(ctx.message))[2]
        em.set_footer(text=_('Run `{}link disable` to disable this feature',
                             ctx).format(prefix))
    else:
        em.set_footer(text=_('Statsy | Powered by the CR API', ctx))

    em.set_author(name=f'{c.name} ({c.tag})')
    em.set_thumbnail(url=ctx.cog.cr.get_arena_image(av))

    embed_fields = [
        (_('Type', ctx), camel_case(c.type) + ' 📩'),
        (_('Score', ctx),
         str(c.clan_score) + _(' Trophies ', ctx) + str(emoji(ctx, 'trophy'))),
        (_('Donations/Week', ctx), str(c.donations_per_week) +
         _(' Cards ', ctx) + str(emoji(ctx, 'cards'))),
        (_('Location', ctx), c.location.name + ' 🌎'),
        (_('Members', ctx), f"{len(c.member_list)}/50 {emoji(ctx, 'clan')}"),
        (_('Required Trophies',
           ctx), f"{c.required_trophies} {emoji(ctx, 'trophy')}"),
    ]

    for n, v, i in embed_fields:
        em.add_field(name=n, value=v, inline=i)

    return em
예제 #10
0
async def format_seasons(ctx, p):
    av = ctx.cog.cr.get_clan_image(p)
    embeds = []
    if p.league_statistics:
        for season in p.league_statistics.to_dict().keys():
            s = p.league_statistics[season]
            em = discord.Embed(color=random_color())
            if ctx.bot.psa_message:
                em.description = f'*{ctx.bot.psa_message}*'
            em.set_author(name=f'{p.name} ({p.tag})', icon_url=av)
            em.set_thumbnail(url=emoji(ctx, 'legendarytrophy').url)
            try:
                em.add_field(name=_('{} Season', ctx).format(
                    season.strip('Season').title()),
                             value=s.id)
            except:
                if p.league_statistics.get('previous_season'):
                    prev = p.league_statistics.previous_season
                    old_time = prev.id.split('-')
                    time = [int(old_time[0]), int(old_time[1]) + 1]
                    if time[1] > 12:  # check month
                        time[0] += 1
                        time[1] = 1
                    em.add_field(name=_('{} Season', ctx).format(
                        season.strip('Season').title()),
                                 value=f'{time[0]}-{time[1]}')
            try:
                em.add_field(name=_('Season Highest', ctx),
                             value=f"{s.best_trophies} {emoji(ctx, 'trophy')}")
            except:
                pass
            try:
                em.add_field(name=_('Season Finish', ctx),
                             value=f"{s.trophies} {emoji(ctx, 'trophy')}")
            except:
                pass
            try:
                em.add_field(name=_('Global Rank', ctx),
                             value=f"{s.rank} {emoji(ctx, 'rank')}")
            except:
                pass

            embeds.append(em)

    return embeds
예제 #11
0
async def format_clan_war(ctx, w):
    page1 = discord.Embed(color=random_color())
    page1.set_footer(text=_('Statsy | Powered by the CR API', ctx))

    if ctx.bot.psa_message:
        page1.description = ctx.bot.psa_message

    if w.state == 'notInWar':
        page1.add_field(name=_('Day', ctx),
                        value=f'{camel_case(w.state)} {emoji(ctx, "clanwar")}')
        return [page1]

    page1.set_author(name=f"{w.clan.name} ({w.clan.tag})",
                     icon_url=ctx.cog.cr.get_clan_image(w))

    page2 = copy.deepcopy(page1)
    return_vals = [page1, page2]

    fields1 = [(_('Day',
                  ctx), f'{camel_case(w.state)} {emoji(ctx, "clanwar")}'),
               (_('War Trophies', ctx),
                f"{w.clan.clan_score} Trophies {emoji(ctx, 'wartrophy')}"),
               (_('Participants',
                  ctx), f"{w.clan.participants} {emoji(ctx, 'clan')}"),
               (_('Battles Played',
                  ctx), f"{w.clan.battles_played} {emoji(ctx, 'battle')}"),
               (_('Wins', ctx), f"{w.clan.wins} {emoji(ctx, 'crownblue')}")]

    if w.state in ('matchmaking', 'collectionDay'):
        pass
    elif w.state == 'warDay':
        fields1.append(('Crowns', f'{w.clan.crowns} {emoji(ctx, "3crown")}'))
        page3 = copy.deepcopy(page1)

        standings = []

        for i in w.clans:
            standings.append(''.join(
                (f"**{i.name}**", _('\n{} Batles Played {}',
                                    ctx).format(i.battles_played,
                                                emoji(ctx, 'battle')),
                 _('\n{} Wins', ctx).format(i.wins, emoji(ctx, 'crownblue')),
                 _('\n{} Crowns {}',
                   ctx).format(i.crowns, emoji(ctx, '3crown')), f"\n{i.tag}")))

        page3.add_field(name=_('Clans Participating', ctx),
                        value='\n\n'.join(standings))
        return_vals.append(page3)

    else:
        raise NotImplementedError(
            f'{w.state} not implemented in format_clan_war (L632, ext/embeds_cr_crapi)'
        )

    members = []

    for i in range(3):
        if len(w.participants) < i + 1:
            break
        members.append(''.join((f"**{w.participants[i].name}**",
                                _('\n{} Batles Played {}',
                                  ctx).format(w.participants[i].battles_played,
                                              emoji(ctx, 'battle')),
                                _('\n{} Wins',
                                  ctx).format(w.participants[i].wins,
                                              emoji(ctx, 'crownblue')),
                                _('\n{} Cards Earned {}',
                                  ctx).format(w.participants[i].cards_earned,
                                              emoji(ctx, 'cards')),
                                f"\n{w.participants[i].tag}")))

    for f, v in fields1:
        page1.add_field(name=f, value=v)

    page2.add_field(name=_('Top Fighters', ctx), value='\n\n'.join(members))

    return return_vals
예제 #12
0
async def format_profile(ctx, p, c):

    av = ctx.cog.cr.get_clan_image(p)
    em = discord.Embed(color=random_color())
    if ctx.bot.psa_message:
        em.description = f'*{ctx.bot.psa_message}*'
    em.set_author(name=f'{p.name} ({p.tag})', icon_url=av)
    em.set_thumbnail(url=ctx.cog.cr.get_arena_image(p))

    deck = get_deck(ctx, p)

    chests = get_chests(ctx, c)[0]

    trophies = f"{p.trophies}/{p.best_trophies} PB {emoji(ctx, 'trophy')}"

    s = None
    if p.league_statistics:
        current_rank = p.league_statistics.current_season.get('rank')
        if p.league_statistics.get('previous_season'):
            s = p.league_statistics.previous_season
            global_r = s.get('rank')
            season = (_('Highest: {} {} \n',
                        ctx).format(s.best_trophies, emoji(ctx, 'crownblue')),
                      _('Finish: {} {} \n',
                        ctx).format(s.trophies, emoji(ctx, 'trophy')),
                      _('Global Rank: {} {}',
                        ctx).format(global_r, emoji(ctx, 'rank')))
        else:
            season = None
    else:
        current_rank = None
        season = None

    try:
        clan_name = p.clan.name
        clan_tag = p.clan.tag
        clan_role = camel_case(p.role)
    except AttributeError:
        clan_name = clan_tag = clan_role = None

    special = get_chests(ctx, c)[1]

    try:
        favourite_card = f"{p.current_favourite_card.name} {emoji(ctx, p.current_favourite_card.name)}"
    except AttributeError:
        favourite_card = _('No favourite card :(', ctx)

    embed_fields = [
        (_('Trophies', ctx), trophies, True),
        (_('Level', ctx), f"{p.exp_level} {emoji(ctx, 'experience')}", True),
        (_('Clan Name', ctx),
         f"{clan_name} {emoji(ctx, 'clan')}" if clan_name else None, True),
        (_('Clan Tag', ctx),
         f"{clan_tag} {emoji(ctx, 'clan')}" if clan_tag else None, True),
        (_('Clan Role', ctx),
         f"{clan_role} {emoji(ctx, 'clan')}" if clan_role else None, True),
        (_('Clans Joined',
           ctx), f"{p.achievements[0].value} {emoji(ctx, 'clan')}", True),
        (_('Games Played',
           ctx), f"{p.battle_count} {emoji(ctx, 'battle')}", True),
        (_('Friendly Battles Won',
           ctx), f"{p.achievements[9].value} {emoji(ctx, 'battle')}", True),
        (_('Wins/Losses',
           ctx), f"{p.wins}/{p.losses} {emoji(ctx, 'battle')}", True),
        (_('Three Crown Wins',
           ctx), f"{p.three_crown_wins} {emoji(ctx, '3crown')}", True),
        (_('War Day Wins',
           ctx), f"{p.war_day_wins} {emoji(ctx, 'clanwar')}", True),
        (_('Favourite Card', ctx), favourite_card, True),
        (_('Tournaments Played', ctx),
         f"{p.achievements[7].value} {emoji(ctx, 'tournament')}", True),
        (_('Tournament Cards Won',
           ctx), f"{p.tournament_cards_won} {emoji(ctx, 'cards')}", True),
        (_('Challenge Cards Won',
           ctx), f"{p.challenge_cards_won} {emoji(ctx, 'cards')}", True),
        (_('Challenge Max Wins',
           ctx), f"{p.challenge_max_wins} {emoji(ctx, 'tournament')}", True),
        (_('Total Donations',
           ctx), f"{p.total_donations} {emoji(ctx, 'cards')}", True),
        (_('Global Rank', ctx),
         f"{current_rank} {emoji(ctx, 'crownred')}" if current_rank else None,
         True),
        (_('Battle Deck', ctx), deck, True),
        (_('Chests', ctx), chests, False),
        (_('Chests Until', ctx), special, True),
        (_('Previous Season Results ({}, ctx)').format(s.id) if s else None,
         season, False),
    ]

    for n, v, i in embed_fields:
        if v:
            em.add_field(name=n, value=v, inline=i)
        else:
            if n == _('Clan Name', ctx):
                em.add_field(name=_('Clan', ctx),
                             value=_('None {}',
                                     ctx).format(emoji(ctx, 'noclan')))

    em.set_footer(text=_('Statsy | Powered by the CR API', ctx))

    return em
예제 #13
0
def get_deck(ctx, p):
    deck = ''
    for card in p.current_deck:
        deck += str(emoji(ctx, card.name)) + str(
            get_card_level(card.level, card.max_level)) + ' '
    return deck
예제 #14
0
async def format_cards(ctx, p):
    constants = ctx.cog.cr.constants

    name = p.name
    tag = p.tag

    rarity = {'Common': 1, 'Rare': 2, 'Epic': 3, 'Legendary': 4}

    found_cards = p.cards
    notfound_cards = [
        i for i in constants.cards
        if i.name not in [k.name for k in found_cards]
    ]

    def get_rarity(card):
        for i in constants.cards:
            if i.name == card or i.key.replace('-', '') == card:
                return i.rarity

    found_cards = sorted(found_cards, key=lambda x: rarity[get_rarity(x.name)])
    notfound_cards = sorted(notfound_cards,
                            key=lambda x: rarity[get_rarity(x.name)])

    fmt = ''
    found_cards_pages = []
    oldcard = None
    for card in found_cards:
        if not card:
            continue
        card.rarity = get_rarity(card.name)

        if oldcard and oldcard.rarity != card.rarity:
            try:
                found_cards_pages.append((fmt, get_rarity(fmt.split(':')[1])))
            except IndexError:
                found_cards_pages.append((fmt, fmt.split(':')[0]))
            fmt = str(emoji(ctx, card.name))
        else:
            fmt += str(emoji(ctx, card.name))

            if len(fmt) > 1024:
                fmt = fmt.replace(str(emoji(ctx, card.name)), '')
                try:
                    found_cards_pages.append(
                        (fmt, get_rarity(fmt.split(':')[1])))
                except IndexError:
                    found_cards_pages.append((fmt, fmt.split(':')[0]))
                fmt = str(emoji(ctx, card.name))
        oldcard = card
    try:
        found_cards_pages.append((fmt, get_rarity(fmt.split(':')[1])))
    except IndexError:
        found_cards_pages.append((fmt, fmt.split(':')[0]))

    fmt = ''
    notfound_cards_pages = []
    for card in notfound_cards:
        if not card:
            continue

        fmt += str(emoji(ctx, card.name))
        if len(fmt) > 1024:
            fmt = fmt.replace(str(emoji(ctx, card.name)), '')
            notfound_cards_pages.append(fmt)
            fmt = str(emoji(ctx, card.name))
    notfound_cards_pages.append(fmt)

    em = discord.Embed(description=_('A list of cards this player has.', ctx),
                       color=random_color())
    em.set_author(name=f"{name} ({tag})")
    em.set_footer(text=_('Statsy | Powered by the CR API', ctx))
    if ctx.bot.psa_message:
        em.description = f'*{ctx.bot.psa_message}*'

    for i, r in found_cards_pages:
        if i:
            em.add_field(name=_('Found Cards ({})', ctx).format(r),
                         value=i,
                         inline=False)

    for item in notfound_cards_pages:
        if item:
            em.add_field(name=_('Missing Cards', ctx),
                         value=item,
                         inline=False)
    return em