Python discord.ext.commands 模块,Command() 实例源码

我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用discord.ext.commands.Command()

项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        # Add commands as random subcommands
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "random":
                self.bot.add_command(command)
                self.random.add_command(command)
        # Add fact subcommands as subcommands of corresponding commands
        for command, parent in ((self.fact_cat, self.cat), (self.fact_date, self.date), (self.fact_number, self.number)):
            utilities.add_as_subcommand(self, command, parent, "fact")
        # Add random subcommands as subcommands of corresponding commands
        self.random_subcommands = ((self.color, "Resources.color"), (self.giphy, "Resources.giphy"), (self.map, "Resources.map"), (self.streetview, "Resources.streetview"), (self.uesp, "Search.uesp"), (self.wikipedia, "Search.wikipedia"), (self.xkcd, "Resources.xkcd"))
        for command, parent_name in self.random_subcommands:
            utilities.add_as_subcommand(self, command, parent_name, "random")
        # Import jokes
        self.jokes = []
        try:
            with open("data/jokes.csv", newline = "") as jokes_file:
                jokes_reader = csv.reader(jokes_file)
                for row in jokes_reader:
                    self.jokes.append(row[0])
        except FileNotFoundError:
            pass
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def add_as_subcommand(cog, command, parent_name, subcommand_name, *, aliases = []):
    if isinstance(parent_name, commands.Command):
        parent = parent_name
        # parent_cog = cog.bot.get_cog(parent.cog_name)
        parent_cog = parent.instance
        parent_command_name = parent.name
    else:
        parent_cog_name, parent_command_name = parent_name.split('.')
        parent_cog = cog.bot.get_cog(parent_cog_name)
        parent = getattr(parent_cog, parent_command_name, None)
        if not parent: return
    subcommand = copy.copy(command)
    subcommand.name = subcommand_name
    subcommand.aliases = aliases
    # async def wrapper(*args, **kwargs):
    # async def wrapper(*args, command = command, **kwargs):
        # await command.callback(cog, *args, **kwargs)
    # subcommand.callback = wrapper
    # subcommand.params = inspect.signature(subcommand.callback).parameters.copy()
    setattr(parent_cog, "{}_{}".format(parent_command_name, subcommand_name), subcommand)
    parent.add_command(subcommand)
项目:GAFBot    作者:DiNitride    | 项目源码 | 文件源码
def format_help_for(self, context, command_or_bot):
        """Formats the help page and handles the actual heavy lifting of how
        the help command looks like. To change the behaviour, override the
        :meth:`format` method.
        Parameters
        -----------
        context : :class:`Context`
            The context of the invoked help command.
        command_or_bot : :class:`Command` or :class:`Bot`
            The bot or command that we are getting the help of.
        Returns
        --------
        list
            A paginated output of the help command.
        """
        self.context = context
        return await self.format(command_or_bot)
项目:PyMiki    作者:TheGrammarJew    | 项目源码 | 文件源码
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:
                    return await ctx.send(f'Command "{command}" 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 CannotPaginate as e:
            await ctx.send(e)
项目:hawking    作者:naschorr    | 项目源码 | 文件源码
def add_phrase(self, phrase):
        if(not isinstance(phrase, Phrase)):
            raise TypeError("{} not instance of Phrase.".format(phrase))

        ## Manually build command to be added
        command = commands.Command(
            phrase.name,
            self._create_phrase_callback(phrase.message, phrase.is_music),
            **phrase.kwargs,
            **self.command_kwargs
        )
        ## _phrase_callback doesn't have an instance linked to it, 
        ## (not technically a method of Phrases?) so manually insert the correct instance anyway.
        ## This also fixes the broken category label in the help page.
        command.instance = self

        self.bot.add_command(command)


    ## Build a dynamic callback to invoke the bot's say method
项目:Cassandra    作者:Avinch    | 项目源码 | 文件源码
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)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        # Add commands as search subcommands
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "search":
                self.bot.add_command(command)
                self.search.add_command(command)
        # Add search subcommands as subcommands of corresponding commands
        self.search_subcommands = ((self.imgur, "Resources.imgur"), (self.youtube, "Audio.audio"))
        for command, parent_name in self.search_subcommands:
            utilities.add_as_subcommand(self, command, parent_name, "search")
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        self.players = {}
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "audio":
                self.bot.add_command(command)
                self.audio.add_command(command)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def process_commands(self, message):
        _internal_channel = message.channel
        _internal_author = message.author
        view = StringView(message.content)
        if self._skip_check(message.author, self.user):
            return
        prefix = await self._get_prefix(message)
        invoked_prefix = prefix
        if not isinstance(prefix, (tuple, list)):
            if not view.skip_string(prefix):
                return
        else:
            invoked_prefix = discord.utils.find(view.skip_string, prefix)
            if invoked_prefix is None:
                return
        invoker = view.get_word().lower() # case-insensitive commands
        tmp = {'bot': self, 'invoked_with': invoker, 'message': message, 'view': view, 'prefix': invoked_prefix}
        ctx = Context(**tmp)
        del tmp
        if invoker in self.commands:
            command = self.commands[invoker]
            self.dispatch('command', command, ctx)
            try:
                await command.invoke(ctx)
            except CommandError as e:
                ctx.command.dispatch_error(e, ctx)
            else:
                self.dispatch('command_completion', command, ctx)
        elif invoker:
            exc = CommandNotFound('Command "{}" is not found'.format(invoker))
            self.dispatch('command_error', exc, ctx)

# Make Subcommands Case-Insensitive
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def command_ancestry(command):
    if isinstance(command, Command):
        cmd = command
        while cmd is not None:
            yield cmd.qualified_name
            cmd = cmd.parent
        if command.instance:
            yield '_' + command.cog_name.casefold()
    elif command != '_all':
        yield '_' + type(command).__name__.casefold()
    yield '_all'
项目:GAFBot    作者:DiNitride    | 项目源码 | 文件源码
def is_cog(self, command):
        """bool : Specifies if the command being formatted is actually a cog."""
        return not self.is_bot(command) and not isinstance(command, commands.Command)
项目:aryas    作者:lattkkthxbbye    | 项目源码 | 文件源码
def format(self):
        """
        Formats the help page.
        """
        # Adapted from discord.ext.commands.formatter.HelpFormatter.format

        self._paginator = AryasPaginator()

        description = self.command.description if not self.is_cog() else inspect.getdoc(self.command)

        if description:
            self._paginator.new_page(description=description)

        if isinstance(self.command, Command):
            # long help doc
            if self.command.help:
                self._paginator.add_line(self.command.help)

            self._paginator.set_name(self.get_command_signature())
            self._paginator.make_field(inline=False)

            # if it's just a single command we're done here
            if not self.has_subcommands():
                return self._paginator.pages

        # Helper method for sorting by category (cog)
        def category(tup):
            cog = tup[1].cog_name
            # Unicode invisible space is there to set No Category last
            return cog + ':' if cog is not None else '\u200bNo Category:'

        # if command is a bot we need to process the entire command list
        if self.is_bot():
            data = sorted(self.filter_command_list(), key=category)
            for category, commands in itertools.groupby(data, key=category):
                commands = list(commands)
                if len(commands) > 0:
                    self._add_entries(commands)
                    self._paginator.set_name(category)
                    self._paginator.make_field(inline=False)
        else:
            # if command is just a cog or Group we can print all the commands
            # returned by filter_command_list
            self._add_entries(self.filter_command_list())
            self._paginator.set_name('Commands:')
            self._paginator.make_field(inline=False)

        # Get the ending message
        self._paginator.set_name('More:')
        self._paginator.add_line(self.get_ending_note())
        self._paginator.make_field(inline=False)
        return self._paginator.pages
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def permissions(self, ctx, target_name, command_name, allow: bool=None):
        """Sets permissions for a user, role, or everyone.
        You can mention a user or role, or use their name or ID, to set permissions for them.
        Use "everyone" to affect everyone's permissions in this guild.
        Allow can be true/false, yes/no, or on/off.
        """
        target = await self.find_target(ctx, target_name)
        if target is None:
            await ctx.send('BAKA! Target must be a member, role, or "everyone"!')

        command, command_name = self.find_command(ctx, command_name)
        if command is None:
            await ctx.send('BAKA! Command must be command name, category name, or "all"!')

        if allow is None: # Get
            allowed = config.allowed(ctx, user=target, command=command)
            perm_str = 'allowed' if allowed else 'not allowed'
        elif config.allowed(ctx, command=command): # Check the caller has permission to give/take this command
            with db.Session() as session:
                attrs = {'guild_id': ctx.guild.id, 'target_id': target.id, 'command_name': command_name}
                record = session.get(config.Permission, **attrs).one_or_none()
                if record is None:
                    record = session.add(config.Permission(**attrs, allowed=allow))
                else:
                    record.allowed = allow
            perm_str = 'now allowed' if allow else 'no longer allowed'
        else:
            return await ctx.send('BAKA! You can only control permissions for commands you can use!')

        if isinstance(target, discord.Member):
            target_str = target.name
        elif isinstance(target, discord.Role):
            target_str = 'The {} role'.format(target.name.capitalize())
        else:
            target_str = 'Everyone'

        if command_name == '_all':
            command_str = 'all commands'
        elif command_name.startswith('_'):
            command_str = 'the {} category'.format(command_name[1:].capitalize())
        else:
            command_str = 'the {} command'.format(command_name)

        await ctx.send('{0} is {1} to use {2}.'.format(target_str, perm_str, command_str))
项目:StreamNotificationBot    作者:ivandardi    | 项目源码 | 文件源码
def _make_commands(self):
        group = commands.Group(
            name=self.service_name,
            callback=self._group_command,
            help=self._make_help_string(strings.group_command_help),
        )
        group.instance = self
        cmd = commands.Command(
            name='add',
            aliases=['subscribe'],
            callback=self._add_command,
            help=self._make_help_string(strings.add_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='del',
            aliases=['unsubscribe', 'remove', 'delete'],
            callback=self._del_command,
            help=self._make_help_string(strings.del_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='list',
            callback=self._list_command,
            help=self._make_help_string(strings.list_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='enable',
            callback=self._enable_command,
            help=self._make_help_string(strings.enable_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='disable',
            callback=self._disable_command,
            help=self._make_help_string(strings.disable_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)

        return group