當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。