当前位置: 首页>>代码示例>>Python>>正文


Python commands.Command方法代码示例

本文整理汇总了Python中discord.ext.commands.Command方法的典型用法代码示例。如果您正苦于以下问题:Python commands.Command方法的具体用法?Python commands.Command怎么用?Python commands.Command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord.ext.commands的用法示例。


在下文中一共展示了commands.Command方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: assertHasPermissionsCheck

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def assertHasPermissionsCheck(  # noqa: N802
        self,
        cmd: commands.Command,
        permissions: Dict[str, bool],
    ) -> None:
        """
        Test that `cmd` raises a `MissingPermissions` exception if author lacks `permissions`.

        Every permission in `permissions` is expected to be reported as missing. In other words, do
        not include permissions which should not raise an exception along with those which should.
        """
        # Invert permission values because it's more intuitive to pass to this assertion the same
        # permissions as those given to the check decorator.
        permissions = {k: not v for k, v in permissions.items()}

        ctx = helpers.MockContext()
        ctx.channel.permissions_for.return_value = discord.Permissions(**permissions)

        with self.assertRaises(commands.MissingPermissions) as cm:
            await cmd.can_run(ctx)

        self.assertCountEqual(permissions.keys(), cm.exception.missing_perms) 
开发者ID:python-discord,项目名称:bot,代码行数:24,代码来源:base.py

示例2: test_get_code

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def test_get_code(self):
        """Should return 1st arg (or None) if eval cmd in message, otherwise return full content."""
        prefix = constants.Bot.prefix
        subtests = (
            (self.cog.eval_command, f"{prefix}{self.cog.eval_command.name} print(1)", "print(1)"),
            (self.cog.eval_command, f"{prefix}{self.cog.eval_command.name}", None),
            (MagicMock(spec=commands.Command), f"{prefix}tags get foo"),
            (None, "print(123)")
        )

        for command, content, *expected_code in subtests:
            if not expected_code:
                expected_code = content
            else:
                [expected_code] = expected_code

            with self.subTest(content=content, expected_code=expected_code):
                self.bot.get_context.reset_mock()
                self.bot.get_context.return_value = MockContext(command=command)
                message = MockMessage(content=content)

                actual_code = await self.cog.get_code(message)

                self.bot.get_context.assert_awaited_once_with(message)
                self.assertEqual(actual_code, expected_code) 
开发者ID:python-discord,项目名称:bot,代码行数:27,代码来源:test_snekbox.py

示例3: get_commands_brief_details

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def get_commands_brief_details(commands_: List[Command], return_as_list: bool = False) -> Union[List[str], str]:
        """
        Formats the prefix, command name and signature, and short doc for an iterable of commands.

        return_as_list is helpful for passing these command details into the paginator as a list of command details.
        """
        details = []
        for command in commands_:
            signature = f" {command.signature}" if command.signature else ""
            details.append(
                f"\n**`{PREFIX}{command.qualified_name}{signature}`**\n*{command.short_doc or 'No details provided'}*"
            )
        if return_as_list:
            return details
        else:
            return "".join(details) 
开发者ID:python-discord,项目名称:bot,代码行数:18,代码来源:help.py

示例4: help_embed

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def help_embed(self, prefix):
        em = discord.Embed(color=0x00FFFF)
        em.set_author(name='Mod Mail - Help', icon_url=self.user.avatar_url)
        em.description = 'This bot is a python implementation of a stateless "Mod Mail" bot. ' \
                         'Made by kenng and improved by the suggestions of others. This bot ' \
                         'saves no data and utilises channel topics for storage and syncing.' 
                 

        cmds = f'`{prefix}setup [modrole] <- (optional)` - Command that sets up the bot.\n' \
               f'`{prefix}reply <message...>` - Sends a message to the current thread\'s recipient.\n' \
               f'`{prefix}close` - Closes the current thread and deletes the channel.\n' \
               f'`{prefix}disable` - Closes all threads and disables modmail for the server.\n' \
               f'`{prefix}customstatus` - Sets the Bot status to whatever you want.' \
               f'`{prefix}block` - Blocks a user from using modmail!' \
               f'`{prefix}unblock` - Unblocks a user from using modmail!'

        warn = 'Do not manually delete the category or channels as it will break the system. ' \
               'Modifying the channel topic will also break the system.'
        em.add_field(name='Commands', value=cmds)
        em.add_field(name='Warning', value=warn)
        em.add_field(name='Github', value='https://github.com/kenng69/modmailbotkenng')
        em.set_footer(text='Star the repository to unlock hidden features!')

        return em 
开发者ID:kenng69,项目名称:modmailbotkenng,代码行数:26,代码来源:bot.py

示例5: in_month_command

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def in_month_command(*allowed_months: Month) -> t.Callable:
    """
    Check whether the command was invoked in one of `enabled_months`.

    Uses the current UTC month at the time of running the predicate.
    """
    async def predicate(ctx: Context) -> bool:
        current_month = resolve_current_month()
        can_run = current_month in allowed_months

        log.debug(
            f"Command '{ctx.command}' is locked to months {human_months(allowed_months)}. "
            f"Invoking it in month {current_month!s} is {'allowed' if can_run else 'disallowed'}."
        )
        if can_run:
            return True
        else:
            raise InMonthCheckFailure(f"Command can only be used in {human_months(allowed_months)}")

    return commands.check(predicate) 
开发者ID:python-discord,项目名称:seasonalbot,代码行数:22,代码来源:decorators.py

示例6: _category_key

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def _category_key(self, cmd: Command) -> str:
        """
        Returns a cog name of a given command for use as a key for `sorted` and `groupby`.

        A zero width space is used as a prefix for results with no cogs to force them last in ordering.
        """
        if cmd.cog:
            try:
                if cmd.cog.category:
                    return f'**{cmd.cog.category}**'
            except AttributeError:
                pass

            return f'**{cmd.cog_name}**'
        else:
            return "**\u200bNo Category:**" 
开发者ID:python-discord,项目名称:seasonalbot,代码行数:18,代码来源:help.py

示例7: embed_page

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def embed_page(self, page_number: int = 0) -> Embed:
        """Returns an Embed with the requested page formatted within."""
        embed = Embed()

        if isinstance(self.query, (commands.Command, Cog)) and page_number > 0:
            title = f'Command Help | "{self.query.name}"'
        else:
            title = self.title

        embed.set_author(name=title, icon_url=constants.Icons.questionmark)
        embed.description = self._pages[page_number]

        page_count = len(self._pages)
        if page_count > 1:
            embed.set_footer(text=f'Page {self._current_page+1} / {page_count}')

        return embed 
开发者ID:python-discord,项目名称:seasonalbot,代码行数:19,代码来源:help.py

示例8: _commands

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def _commands(self, ctx: NabCtx):
        """Shows a simple list of all commands.

        This displays all the commands you can use, with no description or subcommand information.
        Note that different commands might show up in server channels and in private messages.

        For more details, use `help`."""
        embed = discord.Embed(title=f"{ctx.me.display_name} commands")
        embed.set_footer(text=f"For a more detailed list, try '{ctx.clean_prefix}help' or "
                              f"'{ctx.clean_prefix}help [command_name]'")
        _commands: List[commands.Command] = [c for c in self.bot.commands if not c.hidden and await _can_run(c, ctx)]
        categories = {}
        for command in _commands:
            if command.cog_name not in categories:
                categories[command.cog_name] = []
            categories[command.cog_name].append(command.name)

        for k in sorted(categories):
            embed.add_field(name=k, value=", ".join(f"`{c}`" for c in sorted(categories[k])), inline=False)
        await ctx.send(embed=embed) 
开发者ID:NabDev,项目名称:NabBot,代码行数:22,代码来源:info.py

示例9: on_command

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def on_command(self, command: Command, ctx: Context):
        """Track command usage."""
        server = ctx.message.server
        author = ctx.message.author
        channel = ctx.message.channel

        if server is None:
            return
        if author is None:
            return
        if "TID" not in self.settings:
            return

        # client_id = self.get_member_uuid(author)
        client_id = uuid.uuid4()
        self.log_command(client_id, server, channel, author, command) 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:18,代码来源:ga.py

示例10: dd_log_command

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def dd_log_command(self, command: Command, ctx: Context):
        """Log commands with datadog."""
        channel = ctx.message.channel
        channel_name = ''
        channel_id = ''
        if channel is not None:
            if not channel.is_private:
                channel_name = channel.name
                channel_id = channel.id
        server = ctx.message.server
        server_id = server.id
        server_name = server.name
        statsd.increment(
            'bot.cmd',
            tags=[
                *self.tags,
                'author:' + str(ctx.message.author.display_name),
                'author_id:' + str(ctx.message.author.id),
                'author_name:' + str(ctx.message.author.name),
                'server_id:' + str(server_id),
                'server_name:' + str(server_name),
                'channel_name:' + str(channel_name),
                'channel_id:' + str(channel_id),
                'command_name:' + str(command),
                'cog_name:' + type(ctx.cog).__name__]) 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:27,代码来源:ddlog.py

示例11: help

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def help(self, ctx, *, command: str = None):
        """Shows help about a command or the bot"""
        try:
            if command is None:
                p = await HelpPaginator.from_bot(ctx)
            else:
                entity = self.bot.get_cog(command) or self.bot.get_command(command)

                if entity is None:
                    clean = command.replace('@', '@\u200b')
                    return await ctx.send(f'Command or category "{clean}" not found.')
                elif isinstance(entity, commands.Command):
                    p = await HelpPaginator.from_command(ctx, entity)
                else:
                    p = await HelpPaginator.from_cog(ctx, entity)

            await p.paginate()
        except Exception as e:
            await ctx.send(e) 
开发者ID:F4stZ4p,项目名称:DJ5n4k3,代码行数:21,代码来源:misc.py

示例12: walk_commands

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def walk_commands(cog: commands.Cog) -> t.Iterator[commands.Command]:
        """An iterator that recursively walks through `cog`'s commands and subcommands."""
        # Can't use Bot.walk_commands() or Cog.get_commands() cause those are instance methods.
        for command in cog.__cog_commands__:
            if command.parent is None:
                yield command
                if isinstance(command, commands.GroupMixin):
                    # Annoyingly it returns duplicates for each alias so use a set to fix that
                    yield from set(command.walk_commands()) 
开发者ID:python-discord,项目名称:bot,代码行数:11,代码来源:test_cogs.py

示例13: get_qualified_names

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def get_qualified_names(command: commands.Command) -> t.List[str]:
        """Return a list of all qualified names, including aliases, for the `command`."""
        names = [f"{command.full_parent_name} {alias}".strip() for alias in command.aliases]
        names.append(command.qualified_name)

        return names 
开发者ID:python-discord,项目名称:bot,代码行数:8,代码来源:test_cogs.py

示例14: get_all_commands

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def get_all_commands(self) -> t.Iterator[commands.Command]:
        """Yield all commands for all cogs in all extensions."""
        for module in self.walk_modules():
            for cog in self.walk_cogs(module):
                for cmd in self.walk_commands(cog):
                    yield cmd 
开发者ID:python-discord,项目名称:bot,代码行数:8,代码来源:test_cogs.py

示例15: subcommand_not_found

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import Command [as 别名]
def subcommand_not_found(self, command: Command, string: str) -> "HelpQueryNotFound":
        """
        Redirects the error to `command_not_found`.

        `command_not_found` deals with searching and getting best choices for both commands and subcommands.
        """
        return await self.command_not_found(f"{command.qualified_name} {string}") 
开发者ID:python-discord,项目名称:bot,代码行数:9,代码来源:help.py


注:本文中的discord.ext.commands.Command方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。