Beispiel #1
0
def disable(__cogs, server_ex, *cogs: 'Name of cogs to enable'):
    """Disable cogs for the current server.

    If called with no cogs, displays disabled cogs. Use `*` to disable all cogs."""
    if not cogs:
        if not server_ex.blacklist:
            return _('No cogs are disabled.')
        return _('Disabled cogs: {disabled_cogs}').format(
            disabled_cogs=gearbox.pretty(
                server_ex.blacklist, '`%s`', final=_('and')))
    if cogs == ('*', ):
        cogs = [
            c for c in __cogs.COGS
            if c != __name__.split('.')[-1] and c not in server_ex.blacklist
        ]
        if not cogs:
            return _('No cogs are enabled.')
    not_found = [c for c in cogs if c not in __cogs.COGS]
    if not_found:
        return ngettext("{cogs_not_found} doesn't exist", "{cogs_not_found} don't exist", len(not_found))\
            .format(cogs_not_found=gearbox.pretty(not_found, '`%s`', final=_('and')))
    if any([c == __name__.split('.')[-1] for c in cogs]):
        return _('Error: cannot disable self')
    already = [c for c in cogs if c in server_ex.blacklist]
    if already:
        return ngettext("{disabled_cogs} is already disabled", "{disabled_cogs} are already disabled", len(already))\
            .format(disabled_cogs=gearbox.pretty(already, '`%s`', final=_('and')))
    else:
        server_ex.blacklist.extend(cogs)
        server_ex.write()
        return _('Disabled {disabled_cogs}').format(
            disabled_cogs=gearbox.pretty(cogs, '`%s`', final=_('and')))
Beispiel #2
0
def disable(__cogs, server_ex, *cogs: 'Name of cogs to enable'):
    """Disable cogs for the current server.

    If called with no cogs, displays disabled cogs. Use `*` to disable all cogs."""
    if not cogs:
        if not server_ex.blacklist:
            return _('No cogs are disabled.')
        return _('Disabled cogs: {disabled_cogs}').format(disabled_cogs=gearbox.pretty(server_ex.blacklist, '`%s`',
                                                                                       final=_('and')))
    if cogs == ('*',):
        cogs = [c for c in __cogs.COGS if c != __name__.split('.')[-1] and c not in server_ex.blacklist]
        if not cogs:
            return _('No cogs are enabled.')
    not_found = [c for c in cogs if c not in __cogs.COGS]
    if not_found:
        return ngettext("{cogs_not_found} doesn't exist", "{cogs_not_found} don't exist", len(not_found))\
            .format(cogs_not_found=gearbox.pretty(not_found, '`%s`', final=_('and')))
    if any([c == __name__.split('.')[-1] for c in cogs]):
        return _('Error: cannot disable self')
    already = [c for c in cogs if c in server_ex.blacklist]
    if already:
        return ngettext("{disabled_cogs} is already disabled", "{disabled_cogs} are already disabled", len(already))\
            .format(disabled_cogs=gearbox.pretty(already, '`%s`', final=_('and')))
    else:
        server_ex.blacklist.extend(cogs)
        server_ex.write()
        return _('Disabled {disabled_cogs}').format(disabled_cogs=gearbox.pretty(cogs, '`%s`', final=_('and')))
Beispiel #3
0
def enable(__cogs, server_ex, *cogs: 'Name of cogs to enable'):
    """Enable cogs for the current server.

    If called with no cogs, displays enabled cogs. Use `*` to enable all cogs."""
    if not cogs:
        return _('Enabled cogs: {enabled_cogs}').format(
            enabled_cogs=gearbox.pretty(
                [c for c in __cogs.COGS if server_ex.is_allowed(c)],
                '`%s`',
                final=_('and')))
    if cogs == ('*', ):
        cogs = server_ex.blacklist[::]
        if not cogs:
            return _('No cogs are disabled.')
    not_found = [c for c in cogs if c not in __cogs.COGS]
    if not_found:
        return ngettext("{cogs_not_found} doesn't exist", "{cogs_not_found} don't exist", len(not_found))\
            .format(cogs_not_found=gearbox.pretty(not_found, '`%s`', final=_('and')))
    already = [c for c in cogs if c not in server_ex.blacklist]
    if already:
        return ngettext("{enabled_cogs} is already enabled", "{enabled_cogs} are already enabled", len(already))\
            .format(enabled_cogs=gearbox.pretty(already, '`%s`', final=_('and')))
    else:
        for c in cogs:
            server_ex.blacklist.remove(c)
        server_ex.write()
        return _('Enabled {enabled_cogs}').format(
            enabled_cogs=gearbox.pretty(cogs, '`%s`', _('and')))
Beispiel #4
0
def prefix(server_ex,
           command: {'get', 'set', 'add', 'del', 'reset'} = 'get',
           *args):
    """Display or change prefix settings for the current server.

    `get`: show prefixes, `set . ? !`: remove prefixes and set new ones, `add . ? !`: add prefixes, `del . ? !`: remove prefixes, `reset`: reset back to `;`"""
    command = command.lower()
    if command == 'get':
        if len(server_ex.prefixes) == 0:
            return _(
                'This server has no prefix. Use `prefix add` to add some!')
        return ngettext(
            "The prefix for this server is {prefixes}",
            "The prefixes for this server are {prefixes}",
            len(server_ex.prefixes)).format(prefixes=gearbox.pretty(
                server_ex.prefixes, '`%s`', final=_('and')))
    elif command == 'add' or command == 'set':
        if not args:
            return _('Please specify which prefix(es) should be added.')
        if command == 'set':
            for pref in server_ex.prefixes[::]:
                server_ex.prefixes.remove(pref)
        overlap = [pref for pref in args if pref in server_ex.prefixes]
        if overlap:
            return ngettext(
                "{prefixes} is already used", "{prefixes} are already used",
                len(overlap)).format(
                    prefixes=gearbox.pretty(overlap, '`%s`', final=_('and')))
        else:
            n = 0
            for pref in args:  # Not using .extend() in case of duplicates in args
                if pref not in server_ex.prefixes:
                    server_ex.prefixes.append(pref)
                    n += 1
            server_ex.write()
            return ngettext("Added {n} prefix.", "Added {n} prefixes.",
                            n).format(n=n)
    elif command == 'del':
        if not args:
            return _('Please specify which prefix(es) should be deleted.')
        unused = [pref for pref in args if pref not in server_ex.prefixes]
        if unused:
            return ngettext(
                "{prefixes} isn't used", "{prefixes} aren't used",
                len(unused)).format(
                    prefixes=gearbox.pretty(unused, '`%s`', final=_('and')))
        else:
            n = 0
            for pref in args:
                if pref in server_ex.prefixes:
                    server_ex.prefixes.remove(pref)
                    n += 1
            server_ex.write()
            return ngettext("Removed {n} prefix.", "Removed {n} prefixes.",
                            n).format(n=n)
    elif command == 'reset':
        server_ex.prefixes = [DEFAULT_PREFIX]
        server_ex.write()
        return _('Server prefix reset to `{default}`.').format(
            default=DEFAULT_PREFIX)
Beispiel #5
0
def lang(guild_ex, language=None):
    """Display or change server language."""
    available_languages = os.listdir(gearbox.CFG['path']['locale'])
    try:  # Hide the 'templates' directory containing .pot files
        available_languages.remove('templates')
    except ValueError:
        pass
    if language is None or language not in available_languages:
        output = ''
        if language is None:
            output = _("Current server language: {language}").format(
                language=guild_ex.config['language']) + "\n"
        output += (
            _('Available languages: {languages}').format(
                languages=gearbox.pretty(
                    available_languages, '`%s`', final=_('and'))) + '\n' +
            _('Please note that full support is not guaranteed at all.'))
        return output
    else:
        guild_ex.config['language'] = language
        guild_ex.write()
        output = _("Server language has been set to `{language}`!").format(
            language=language)
        if '_' in language:
            output += f' :flag_{language.split("_")[-1].lower()}:'
        return output
Beispiel #6
0
def enable(__cogs, server_ex, *cogs: 'Name of cogs to enable'):
    """Enable cogs for the current server.

    If called with no cogs, displays enabled cogs. Use `*` to enable all cogs."""
    if not cogs:
        return _('Enabled cogs: {enabled_cogs}').format(enabled_cogs=gearbox.pretty(
            [c for c in __cogs.COGS if server_ex.is_allowed(c)], '`%s`', final=_('and')))
    if cogs == ('*',):
        cogs = server_ex.blacklist[::]
        if not cogs:
            return _('No cogs are disabled.')
    not_found = [c for c in cogs if c not in __cogs.COGS]
    if not_found:
        return ngettext("{cogs_not_found} doesn't exist", "{cogs_not_found} don't exist", len(not_found))\
            .format(cogs_not_found=gearbox.pretty(not_found, '`%s`', final=_('and')))
    already = [c for c in cogs if c not in server_ex.blacklist]
    if already:
        return ngettext("{enabled_cogs} is already enabled", "{enabled_cogs} are already enabled", len(already))\
            .format(enabled_cogs=gearbox.pretty(already, '`%s`', final=_('and')))
    else:
        for c in cogs:
            server_ex.blacklist.remove(c)
        server_ex.write()
        return _('Enabled {enabled_cogs}').format(enabled_cogs=gearbox.pretty(cogs, '`%s`', _('and')))
Beispiel #7
0
def language(text):
    """Determine language of text (not all are supported)."""
    distances = analyze_frequency(text)
    upper = distances[0][0] + (distances[-1][0] - distances[0][0]) / 10
    langs = [lang for dist, lang in distances if dist <= upper]
    if len(langs) == 1:
        return _("This message is most likely in {language}").format(
            language=langs[0])
    elif len(langs) < 3:
        return _(
            "This message seems to be in {language}, or maybe in {language2}"
        ).format(language=langs[0], language2=langs[1])
    else:
        return _("Multiple languages have been detected: {languages}").format(
            gearbox.pretty(langs, final=_('and')))
Beispiel #8
0
def halp(__cogs,
         server_ex,
         flags,
         permissions,
         name: 'Cog or command name' = None):
    """Display information on a cog or command.

    Display general help when called without parameter, or list commands in a cog, or list command information.
    `<argument>` means an argument is mandatory, `[argument]` means you can omit it.
    Display special documentation pages when called with `-d [page]`"""
    if 'd' in flags:
        doc_path = cog.config['help']['doc_path']
        pages = [
            page[:-3] for page in os.listdir(doc_path) if page.endswith('.md')
        ]
        if name is None or name not in pages:
            return ngettext(
                "The following special documentation page is available:\n{pages}",
                "The following special documentation pages are available:\n{pages}",
                len(pages)).format(
                    pages=gearbox.pretty(pages, '`%s`', final=_('and')))
        else:
            return markdown_parser(open(f'{doc_path}/{name}.md').read())
    width = cog.config['help']['width']
    active_cogs = [cogg for cogg in __cogs.COGS if server_ex.is_allowed(cogg)]
    commands = __cogs.command(name, server_ex, permissions)
    if name is not None and '.' in name:
        cogg, temp_name = name.rsplit('.', 1)
        if cogg in active_cogs and __cogs.COGS[cogg].cog.get(
                temp_name, permissions):
            commands = [((cogg, temp_name),
                         __cogs.COGS[cogg].cog.get(temp_name, permissions))]
    if name is None:
        return _("Hi, I'm `;;` :no_mouth: I'm split into several cogs, type `;help <cog>` for more information\n") + \
               ngettext("The following cog is currently enabled: {active_cogs}",
                        "The following cogs are currently enabled: {active_cogs}", len(active_cogs)).format(
                   active_cogs=gearbox.pretty(active_cogs, '`%s`', final=_('and')))
    elif name in active_cogs:
        cogg = __cogs.COGS[name]
        output = f'`{name}` - ' + cogg.__doc__.replace('\n\n', '\n')
        for cname, command in cogg.cog.get_all(permissions).items():
            line = cname
            for i, arg in enumerate(command.arguments):
                line += (' <%s>' if i < command.min_arg else ' [%s]') % arg
            output += f'\n`{line:{width}.{width}}|` {command.func.__doc__.splitlines()[0]}'
        if cogg.cog.subcogs:
            output += '\n' + ngettext("The following subcog is available:",
                                      "The following subcogs are available:",
                                      len(cogg.cog.subcogs))
            for subname, subcog in cogg.cog.subcogs.items():
                output += f"\n`{subname:{width}.{width}}|` {subcog.__doc__}"
        if commands:
            output += '\n' + ngettext(
                "The following command also exists: {commands}",
                "The following commands also exist: {commands}",
                len(commands)).format(commands=gearbox.pretty([
                    f'{cogg}.{__cogs.COGS[cogg].cog.aliases[name]}'
                    for cogg, _ in commands
                ],
                                                              '`%s`',
                                                              final=_('and')))
        return output
    elif commands:
        if len(commands) > 1:
            return _('There are commands in multiple cogs with that name:') + '\n' +\
                   '\n'.join([f'`{cogg + "." + __cogs.COGS[cogg].cog.aliases[name]:{width}.{width}}|` ' +
                              command.func.__doc__.splitlines()[0] for cogg, command in commands])
        if type(commands[0][0]) is not tuple:
            cogg, command = commands[0]
            cname = name
        else:
            (cogg, cname), command = commands[0]
        cname = __cogs.COGS[cogg].cog.aliases[cname]
        complete_name = cogg + '.' + cname
        output = f'`{complete_name}` - **{command.func.__doc__.splitlines()[0]}**'
        aliases = [
            alias for alias, res in __cogs.COGS[cogg].cog.aliases.items()
            if res == cname
        ]
        aliases.remove(cname)
        if aliases:
            output += '\n' + _('Also known as: {alias}').format(
                alias=gearbox.pretty(aliases, '`%s`', final=_('and')))
        output += '\n**' + _('Usage') + '**: `' + complete_name + (
            ' -flags' if command.flags else '')
        for i, arg in enumerate(command.arguments):
            output += (' <%s>' if i < command.min_arg else ' [%s]') % arg
        output += '`'
        if command.flags:
            output += '\n**' + _('Flags') + '**: '
            keys = list(command.flags)
            keys.sort()
            output += gearbox.pretty([
                f'`-{flag}`' +
                (f' ({command.flags[flag]})' if command.flags[flag] else '')
                for flag in keys
            ])
        if any([
                arg[0] is not None or len(arg[1]) > 0
                for arg in command.annotations.values()
        ]):
            output += '\n**' + _('Arguments') + '**: '
            arguments = []
            for arg in command.arguments:
                anno = command.annotations[arg]
                temp = f'`{arg}`'
                if anno[0] is not None:
                    if type(anno[0]) is set:
                        temp += ' (' + _("must be {list}").format(
                            list=gearbox.pretty(anno[0], "`%s`", _(
                                "or"))) + ')'
                    elif type(anno[0]) is not type:
                        temp += ' (' + _("must match `{pattern}`").format(
                            pattern=anno[0].pattern) + ')'
                    else:
                        temp += f' ({anno[0].__name__})'
                if len(anno[1]) > 0:
                    temp += f' ({anno[1]})'
                arguments.append(temp)
            output += gearbox.pretty(arguments, final=_('and'))
        if '\n' in command.func.__doc__:
            output += '\n' + '\n'.join([
                line.strip()
                for line in command.func.__doc__.splitlines()[1:] if line
            ])
        return output
    return _('Unknown cog or command.')
Beispiel #9
0
def halp(__cogs, server_ex, flags, permissions, name: 'Cog or command name'=None):
    """Display information on a cog or command.

    Display general help when called without parameter, or list commands in a cog, or list command information.
    `<argument>` means an argument is mandatory, `[argument]` means you can omit it.
    Display special documentation pages when called with `-d [page]`"""
    if 'd' in flags:
        doc_path = cog.config['help']['doc_path']
        pages = [page[:-3] for page in os.listdir(doc_path) if page.endswith('.md')]
        if name is None or name not in pages:
            return ngettext("The following special documentation page is available:\n{pages}",
                            "The following special documentation pages are available:\n{pages}", len(pages)).format(
                pages=gearbox.pretty(pages, '`%s`', final=_('and')))
        else:
            return markdown_parser(open(f'{doc_path}/{name}.md').read())
    width = cog.config['help']['width']
    active_cogs = [cogg for cogg in __cogs.COGS if server_ex.is_allowed(cogg)]
    commands = __cogs.command(name, server_ex, permissions)
    if name is not None and '.' in name:
        cogg, temp_name = name.rsplit('.', 1)
        if cogg in active_cogs and __cogs.COGS[cogg].cog.get(temp_name, permissions):
            commands = [((cogg, temp_name), __cogs.COGS[cogg].cog.get(temp_name, permissions))]
    if name is None:
        return _("Hi, I'm `;;` :no_mouth: I'm split into several cogs, type `;help <cog>` for more information\n") + \
               ngettext("The following cog is currently enabled: {active_cogs}",
                        "The following cogs are currently enabled: {active_cogs}", len(active_cogs)).format(
                   active_cogs=gearbox.pretty(active_cogs, '`%s`', final=_('and')))
    elif name in active_cogs:
        cogg = __cogs.COGS[name]
        output = f'`{name}` - ' + cogg.__doc__.replace('\n\n', '\n')
        for cname, command in cogg.cog.get_all(permissions).items():
            line = cname
            for i, arg in enumerate(command.arguments):
                line += (' <%s>' if i < command.min_arg else ' [%s]') % arg
            output += f'\n`{line:{width}.{width}}|` {command.func.__doc__.splitlines()[0]}'
        if cogg.cog.subcogs:
            output += '\n' + ngettext("The following subcog is available:",
                                      "The following subcogs are available:", len(cogg.cog.subcogs))
            for subname, subcog in cogg.cog.subcogs.items():
                output += f"\n`{subname:{width}.{width}}|` {subcog.__doc__}"
        if commands:
            output += '\n' + ngettext("The following command also exists: {commands}",
                                      "The following commands also exist: {commands}", len(commands)).format(
                commands=gearbox.pretty([f'{cogg}.{__cogs.COGS[cogg].cog.aliases[name]}' for cogg, _ in commands],
                                        '`%s`', final=_('and')))
        return output
    elif commands:
        if len(commands) > 1:
            return _('There are commands in multiple cogs with that name:') + '\n' +\
                   '\n'.join([f'`{cogg + "." + __cogs.COGS[cogg].cog.aliases[name]:{width}.{width}}|` ' +
                              command.func.__doc__.splitlines()[0] for cogg, command in commands])
        if type(commands[0][0]) is not tuple:
            cogg, command = commands[0]
            cname = name
        else:
            (cogg, cname), command = commands[0]
        cname = __cogs.COGS[cogg].cog.aliases[cname]
        complete_name = cogg + '.' + cname
        output = f'`{complete_name}` - **{command.func.__doc__.splitlines()[0]}**'
        aliases = [alias for alias, res in __cogs.COGS[cogg].cog.aliases.items() if res == cname]
        aliases.remove(cname)
        if aliases:
            output += '\n' + _('Also known as: {alias}').format(alias=gearbox.pretty(aliases, '`%s`', final=_('and')))
        output += '\n**' + _('Usage') + '**: `' + complete_name + (' -flags' if command.flags else '')
        for i, arg in enumerate(command.arguments):
            output += (' <%s>' if i < command.min_arg else ' [%s]') % arg
        output += '`'
        if command.flags:
            output += '\n**' + _('Flags') + '**: '
            keys = list(command.flags)
            keys.sort()
            output += gearbox.pretty([f'`-{flag}`' + (f' ({command.flags[flag]})'if command.flags[flag] else '')
                                      for flag in keys])
        if any([arg[0] is not None or len(arg[1]) > 0 for arg in command.annotations.values()]):
            output += '\n**' + _('Arguments') + '**: '
            arguments = []
            for arg in command.arguments:
                anno = command.annotations[arg]
                temp = f'`{arg}`'
                if anno[0] is not None:
                    if type(anno[0]) is set:
                        temp += ' (' + _("must be {list}").format(list=gearbox.pretty(anno[0], "`%s`", _("or"))) + ')'
                    elif type(anno[0]) is not type:
                        temp += ' (' + _("must match `{pattern}`").format(pattern=anno[0].pattern) + ')'
                    else:
                        temp += f' ({anno[0].__name__})'
                if len(anno[1]) > 0:
                    temp += f' ({anno[1]})'
                arguments.append(temp)
            output += gearbox.pretty(arguments, final=_('and'))
        if '\n' in command.func.__doc__:
            output += '\n' + '\n'.join([line.strip() for line in command.func.__doc__.splitlines()[1:] if line])
        return output
    return _('Unknown cog or command.')