Example #1
0
def format_result_sentence(results, context_subject, context_predicate):
    if len(results) == 0:
        return 'No response'
    elif context_subject is not None and context_predicate is not None:
        if len(results) == 1:
            return 'The {} of {} is {}'.format(context_predicate, context_subject, results[1])
        else:
            return 'The {} of {} are {}'.format(context_predicate, context_subject, format_list(results, 'en'))
    else:
        return 'I have found: {}'.format(format_list(results, 'en'))
Example #2
0
    async def format_page(self, menu, entries):
        _ = await self.ctx.get_translate_function()
        language_code = await self.ctx.get_language_code()

        embed = discord.Embed(title=_("The beloved DuckHunt translators"))

        embed.color = discord.Color.green()
        embed.description = _("The bot itself is made by Eyesofcreeper, with contributions from people mentionned in "
                              "`{ctx.prefix}credits`. **You want to help translate this bot ?** "
                              "Contact Eyesofcreeper#0001 on the support server (`{ctx.prefix}invite`). Thanks!")

        offset = menu.current_page * self.per_page
        for i, item in enumerate(entries, start=offset):
            locale, translators = item

            parsed_translators = []

            for user in translators:
                parsed_translators.append(f"{user.name}#{user.discriminator}")

            try:
                locale_data = Locale.parse(locale)
                locale_display_name = locale_data.get_display_name(language_code)
            except ValueError:
                locale_display_name = locale

            embed.add_field(name=f"{locale_display_name}: `{locale}` - {get_pct_complete(locale)}%",
                            value=format_list(parsed_translators, locale=language_code),
                            inline=False)

        return embed
Example #3
0
    def format_list(self, elements: List[Text], style="standard"):
        """
        Join list elements
            [items, item2, item3] -> 'item1, item2 and item3'

        :param elements:
        :param style:
        :return:
        """
        return lists.format_list(elements, style=style, locale=self.lang)
Example #4
0
def test_format_list():
    for list, locale, expected in [
        ([], 'en', ''),
        ([u'string'], 'en', u'string'),
        (['string1', 'string2'], 'en', u'string1 and string2'),
        (['string1', 'string2', 'string3'], 'en', u'string1, string2, and string3'),
        (['string1', 'string2', 'string3'], 'zh', u'string1、string2和string3'),
        (['string1', 'string2', 'string3', 'string4'], 'ne', u'string1,string2, string3 र string4'),
    ]:
        assert lists.format_list(list, locale=locale) == expected
Example #5
0
def test_format_list():
    for list, locale, expected in [
        ([], 'en', ''),
        ([u'string'], 'en', u'string'),
        (['string1', 'string2'], 'en', u'string1 and string2'),
        (['string1', 'string2', 'string3'], 'en', u'string1, string2, and string3'),
        (['string1', 'string2', 'string3'], 'zh', u'string1、string2和string3'),
        (['string1', 'string2', 'string3', 'string4'], 'ne', u'string1 र string2, string3 र string4'),
    ]:
        assert lists.format_list(list, locale=locale) == expected
Example #6
0
    def format_list(self, lst, style='standard'):
        """Format the items in lst as a list.

        In:
          - `lst` -- the items
          - `style` -- 'standard-short', 'or', 'or-short', 'unit', 'unit-short' or
            'unit-narrow'

        Return:
          - the formatted list
        """
        return lists.format_list(lst, style, self)
Example #7
0
 async def convert(cls, ctx, argument: str):
     if argument.upper() == "RANDOM":
         return None
     try:
         return getattr(cls, argument.upper())
     except AttributeError:
         _ = await ctx.get_translate_function()
         raise commands.BadArgument(
             _(
                 "This is not a valid color. "
                 "You can choose between {colors}, or `random` for a random color.",
                 colors=format_list(list(cls.__members__),
                                    locale=await ctx.get_language_code())))
Example #8
0
    async def prefix(self, ctx: MyContext):
        """
        Get the bot prefixes
        """
        _ = await ctx.get_translate_function()
        language_code = await ctx.get_language_code()

        global_prefixes = self.bot.config['bot']['prefixes']
        local_prefix = (await get_from_db(ctx.guild)).prefix

        global_prefixes_list = format_list(global_prefixes, locale=language_code)

        if local_prefix:
            await ctx.send(_(
                "My prefix here is {local_prefix}. You can also call me with any of the global prefixes : {global_prefixes_list}",
                local_prefix=local_prefix,
                global_prefixes_list=global_prefixes_list))
        else:
            await ctx.send(_("You can call me with any of the global prefixes : {global_prefixes_list}",
                             global_prefixes_list=global_prefixes_list))
Example #9
0
def commify_list(items: Iterable[Any]):
    # Not sure why lang is sometimes ''
    lang = web.ctx.lang or 'en'
    # If the list item is a template/html element, we strip it
    # so that there is no space before the comma.
    return format_list([str(x).strip() for x in items], locale=lang)
Example #10
0
def test_format_list_error():
    with pytest.raises(ValueError):
        lists.format_list(['a', 'b', 'c'], style='orange', locale='en')
Example #11
0
def _sequence(seq, args, kwargs):
    # Sets aren't sequences, so we have to specifically cast them to lists.
    return format_list(list(seq), *args, **kwargs)
Example #12
0
    async def _user_info(self, ctx: commands.Context, member: Union[discord.Member, discord.User]):
        in_guild = isinstance(member, discord.Member)
        embed = discord.Embed(
            title=filter_invites(str(member)),
            colour=member.colour if member.colour.value != 0 else discord.Embed.Empty,
            description=await self.build_description(member),
        ).set_thumbnail(
            # discord.py 1.0.0 changes this to an Asset instance, which causes PyCharm to start
            # flipping the f**k out since it doesn't match the expected str type, despite
            # working perfectly fine.
            url=str(member.avatar_url_as(static_format="png"))
        )

        now = datetime.utcnow()
        member_n = (
            (sorted(member.guild.members, key=lambda m: m.joined_at or now).index(member) + 1)
            if in_guild
            else None
        )
        embed.set_footer(
            text=translate(
                "member_footer" if member_n is not None else "user_footer", n=member_n, id=member.id
            )
        )

        if in_guild:
            if member.joined_at is None:
                joined_guild = translate("unknown_join_date")
            else:
                joined_guild = translate(
                    "joined_server",
                    delta=Humanize(member.joined_at - ctx.message.created_at, add_direction=True),
                    absolute=Humanize(member.joined_at, DATETIME_FORMAT, tzinfo=get_localzone()),
                )
        else:
            joined_guild = None

        joined_discord = translate(
            "joined_discord",
            delta=Humanize(member.created_at - ctx.message.created_at, add_direction=True),
            absolute=Humanize(member.created_at, DATETIME_FORMAT, tzinfo=get_localzone()),
        )

        embed.add_field(
            name=translate("account_age"),
            value="\n".join(x for x in [joined_discord, joined_guild] if x is not None),
        )

        if in_guild:
            roles = list(reversed([mention(x) for x in member.roles if not x.is_default()]))
            cap = 40
            if len(roles) > cap:
                roles = [*roles[:cap], translate("more_roles", num=len(roles) - cap)]
            if roles:
                embed.add_field(
                    name=translate("server_roles"),
                    value=format_list(roles, locale=translate.locale.babel),
                    inline=False,
                )

        names, nicks = await self.get_names_and_nicks(member)
        if names:
            embed.add_field(name=translate("past_names"), value=", ".join(names), inline=False)
        if nicks:
            embed.add_field(name=translate("past_nicks"), value=", ".join(nicks), inline=False)

        await ctx.send(embed=embed)
def humanize_list(value: list):
    """
    Usage: {{ humanize_list(list) }}
    """
    return format_list(value, locale='en_US')