Python discord.ext.commands.Command() Examples
The following are 30
code examples of discord.ext.commands.Command().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord.ext.commands
, or try the search function
.
Example #1
Source File: ga.py From SML-Cogs with MIT License | 6 votes |
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)
Example #2
Source File: help.py From seasonalbot with MIT License | 6 votes |
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
Example #3
Source File: help.py From seasonalbot with MIT License | 6 votes |
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:**"
Example #4
Source File: base.py From bot with MIT License | 6 votes |
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)
Example #5
Source File: decorators.py From seasonalbot with MIT License | 6 votes |
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)
Example #6
Source File: info.py From NabBot with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: bot.py From modmailbotkenng with MIT License | 6 votes |
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
Example #8
Source File: help.py From bot with MIT License | 6 votes |
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)
Example #9
Source File: ddlog.py From SML-Cogs with MIT License | 6 votes |
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__])
Example #10
Source File: misc.py From DJ5n4k3 with MIT License | 6 votes |
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)
Example #11
Source File: test_snekbox.py From bot with MIT License | 6 votes |
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)
Example #12
Source File: ddlog.py From SML-Cogs with MIT License | 5 votes |
def on_command(self, command: Command, ctx: Context): """Logs commands.""" self.dd_log_command(command, ctx)
Example #13
Source File: logstash.py From SML-Cogs with MIT License | 5 votes |
def on_command(self, command: Command, ctx: Context): """Track command usage.""" self.log_command(command, ctx)
Example #14
Source File: ga.py From SML-Cogs with MIT License | 5 votes |
def log_command( self, client_id, server: Server, channel: Channel, member: Member, command: Command): """Log command usage.""" server_name = self.url_escape(server.name) channel_name = self.url_escape(channel.name) member_name = self.url_escape(member.display_name) self.gmp_report_event( client_id, '{}: Commands'.format(server_name), command.name, label='{}: {}: {}'.format( server_name, channel_name, member_name), value=1) log_params = OrderedDict([ ('server', server), ('command', command) ]) self.log_pageview_names(client_id, log_params) self.log_pageview_ids(client_id, log_params) log_params = OrderedDict([ ('server', server), ('command', command), ('member', member) ]) self.log_pageview_names(client_id, log_params) self.log_pageview_ids(client_id, log_params)
Example #15
Source File: help.py From seasonalbot with MIT License | 5 votes |
def __init__( self, ctx: Context, *command, cleanup: bool = False, only_can_run: bool = True, show_hidden: bool = False, max_lines: int = 15 ): """Creates an instance of the HelpSession class.""" self._ctx = ctx self._bot = ctx.bot self.title = "Command Help" # set the query details for the session if command: query_str = ' '.join(command) self.query = self._get_query(query_str) self.description = self.query.description or self.query.help else: self.query = ctx.bot self.description = self.query.description self.author = ctx.author self.destination = ctx.channel # set the config for the session self._cleanup = cleanup self._only_can_run = only_can_run self._show_hidden = show_hidden self._max_lines = max_lines # init session states self._pages = None self._current_page = 0 self.message = None self._timeout_task = None self.reset_timeout()
Example #16
Source File: info.py From NabBot with Apache License 2.0 | 5 votes |
def commandstats_global(self, ctx: NabCtx): """Shows command statistics of all servers.""" async with ctx.pool.acquire() as conn: stats = await conn.fetchrow("SELECT COUNT(*) as count, MIN(date) as start FROM command_use") _commands = await conn.fetch("""SELECT COUNT(*) as count, command FROM command_use GROUP BY command ORDER BY count DESC LIMIT 5""") users = await conn.fetch("""SELECT COUNT(*) as count, user_id FROM command_use GROUP BY user_id ORDER BY count DESC LIMIT 5""") guilds = await conn.fetch("""SELECT COUNT(*) as count, server_id FROM command_use GROUP BY server_id ORDER BY count DESC LIMIT 5""") embed = discord.Embed(colour=discord.Colour.blurple(), title="Global Command Stats", description=f"{stats['count']:,} command uses") embed.set_footer(text="Tracking usage since") entries = [] for i, row in enumerate(_commands, 1): entries.append(f"{i}. {row['command']} - {row['count']:,} uses") embed.add_field(name="Top commands", value="\n".join(entries), inline=False) entries = [] for i, row in enumerate(guilds, 1): if row["server_id"] is None: guild = "Private Message" else: guild = self.bot.get_guild(row["server_id"]) or f"<Guild {row['server_id']}>" entries.append(f"{i}. {guild} - {row['count']:,} uses") embed.add_field(name="Top servers", value="\n".join(entries), inline=False) entries = [] for i, row in enumerate(users, 1): user = self.bot.get_user(row['user_id']) or f"<User {row['user_id']}>" entries.append(f"{i}. {user} - {row['count']:,} uses") embed.add_field(name="Top users", value="\n".join(entries), inline=False) embed.timestamp = stats['start'] await ctx.send(embed=embed)
Example #17
Source File: info.py From NabBot with Apache License 2.0 | 5 votes |
def commandstats(self, ctx: NabCtx): """Shows command statistics.""" async with ctx.pool.acquire() as conn: stats = await conn.fetchrow("""SELECT COUNT(*) as count, MIN(date) as start FROM command_use WHERE server_id = $1""", ctx.guild.id) _commands = await conn.fetch("""SELECT COUNT(*) as count, command FROM command_use WHERE server_id = $1 GROUP BY command ORDER BY count DESC LIMIT 5""", ctx.guild.id) users = await conn.fetch("""SELECT COUNT(*) as count, user_id FROM command_use WHERE server_id = $1 GROUP BY user_id ORDER BY count DESC LIMIT 5""", ctx.guild.id) embed = discord.Embed(colour=discord.Colour.blurple(), title="Command Stats", description=f"{stats['count']:,} command uses") embed.set_footer(text="Tracking usage since") entries = [] for i, row in enumerate(_commands, 1): entries.append(f"{i}. {row['command']} - {row['count']:,} uses") embed.add_field(name="Top commands", value="\n".join(entries), inline=False) entries = [] for i, row in enumerate(users, 1): user = ctx.guild.get_member(row["user_id"]) user_str = user.mention if user else f"<User {row['user_id']}>" entries.append(f"{i}. {user_str} - {row['count']:,} uses") embed.add_field(name="Top users", value="\n".join(entries), inline=False) embed.timestamp = stats['start'] await ctx.send(embed=embed)
Example #18
Source File: timers.py From NabBot with Apache License 2.0 | 5 votes |
def event_edit(self, ctx): """Edits an event. Use one of the subcommands to edit the event. Only the creator of the event or mods can edit an event. Past events can't be edited.""" content = "To edit an event, use the subcommands:```" for command in ctx.command.commands: # type: commands.Command content += f"{ctx.clean_prefix}{command.qualified_name} {command.usage}\n" content += "```" await ctx.send(content)
Example #19
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
def command(self, *args, **kwargs): """Initiates a command""" kwargs.setdefault('cls', Command) return super(Group, self).command(*args, **kwargs)
Example #20
Source File: error_handler.py From seasonalbot with MIT License | 5 votes |
def revert_cooldown_counter(command: commands.Command, message: Message) -> None: """Undoes the last cooldown counter for user-error cases.""" if command._buckets.valid: bucket = command._buckets.get_bucket(message) bucket._tokens = min(bucket.rate, bucket._tokens + 1) logging.debug("Cooldown counter reverted as the command was not used correctly.")
Example #21
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
def command(**kwargs): """Represents bot commands""" kwargs.setdefault('cls', Command) return commands.command(**kwargs)
Example #22
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
def bot_has_permissions(**required): """Decorator to check if bot has certain permissions when added to a command""" def predicate(ctx): """Function to tell the bot if it has the right permissions""" given = ctx.channel.permissions_for((ctx.guild or ctx.channel).me) missing = [name for name, value in required.items() if getattr(given, name) != value] if missing: raise commands.BotMissingPermissions(missing) else: return True def decorator(func): """Defines the bot_has_permissions decorator""" if isinstance(func, Command): func.checks.append(predicate) func.required_permissions.update(**required) else: if hasattr(func, '__commands_checks__'): func.__commands_checks__.append(predicate) else: func.__commands_checks__ = [predicate] func.__required_permissions__ = discord.Permissions() func.__required_permissions__.update(**required) return func return decorator
Example #23
Source File: help.py From seasonalbot with MIT License | 5 votes |
def new_help(self, ctx: Context, *commands) -> None: """Shows Command Help.""" try: await HelpSession.start(ctx, *commands) except HelpQueryNotFound as error: embed = Embed() embed.colour = Colour.red() embed.title = str(error) if error.possible_matches: matches = '\n'.join(error.possible_matches.keys()) embed.description = f'**Did you mean:**\n`{matches}`' await ctx.send(embed=embed)
Example #24
Source File: help.py From seasonalbot with MIT License | 5 votes |
def _get_query(self, query: str) -> Union[Command, Cog]: """Attempts to match the provided query with a valid command or cog.""" command = self._bot.get_command(query) if command: return command # Find all cog categories that match. cog_matches = [] description = None for cog in self._bot.cogs.values(): if hasattr(cog, "category") and cog.category == query: cog_matches.append(cog) if hasattr(cog, "category_description"): description = cog.category_description # Try to search by cog name if no categories match. if not cog_matches: cog = self._bot.cogs.get(query) # Don't consider it a match if the cog has a category. if cog and not hasattr(cog, "category"): cog_matches = [cog] if cog_matches: cog = cog_matches[0] cmds = (cog.get_commands() for cog in cog_matches) # Commands of all cogs return Cog( name=cog.category if hasattr(cog, "category") else cog.qualified_name, description=description or cog.description, commands=tuple(itertools.chain.from_iterable(cmds)) # Flatten the list ) self._handle_not_found(query)
Example #25
Source File: decorators.py From seasonalbot with MIT License | 5 votes |
def in_month(*allowed_months: Month) -> t.Callable: """ Universal decorator for season-locking commands and listeners alike. This only serves to determine whether the decorated callable is a command, a listener, or neither. It then delegates to either `in_month_command`, or `in_month_listener`, or raises TypeError, respectively. Please note that in order for this decorator to correctly determine whether the decorated callable is a cmd or listener, it **has** to first be turned into one. This means that this decorator should always be placed **above** the d.py one that registers it as either. This will decorate groups as well, as those subclass Command. In order to lock all subcommands of a group, its `invoke_without_command` param must **not** be manually set to True - this causes a circumvention of the group's callback and the seasonal check applied to it. """ def decorator(callable_: t.Callable) -> t.Callable: # Functions decorated as commands are turned into instances of `Command` if isinstance(callable_, Command): logging.debug(f"Command {callable_.qualified_name} will be locked to {human_months(allowed_months)}") actual_deco = in_month_command(*allowed_months) # D.py will assign this attribute when `callable_` is registered as a listener elif hasattr(callable_, "__cog_listener__"): logging.debug(f"Listener {callable_.__qualname__} will be locked to {human_months(allowed_months)}") actual_deco = in_month_listener(*allowed_months) # Otherwise we're unsure exactly what has been decorated # This happens before the bot starts, so let's just raise else: raise TypeError(f"Decorated object {callable_} is neither a command nor a listener") return actual_deco(callable_) return decorator
Example #26
Source File: test_cog.py From jishaku with MIT License | 5 votes |
def test_loads(bot): assert bot.get_cog("Jishaku") assert isinstance(bot.get_cog("Jishaku"), commands.Cog) assert bot.get_command("jsk") assert isinstance(bot.get_command("jsk"), commands.Command)
Example #27
Source File: bot.py From modmailbotkenng with MIT License | 5 votes |
def _add_commands(self): '''Adds commands automatically''' for attr in dir(self): cmd = getattr(self, attr) if isinstance(cmd, commands.Command): self.add_command(cmd)
Example #28
Source File: __init__.py From Penny-Dreadful-Tools with GNU General Public License v3.0 | 5 votes |
def setup(bot: Bot) -> None: Card.convert = CardConverter.convert modules = glob.glob(path.join(path.dirname(__file__), '*.py')) files = [path.basename(f)[:-3] for f in modules if path.isfile(f) and not f.endswith('__init__.py')] commands, names = [], [] for mod in files: n = 0 m = importlib.import_module(f'.{mod}', package=__name__) for _, obj in inspect.getmembers(m): if isinstance(obj, Command): names.append(obj.name) names += obj.aliases commands.append(obj) n += 1 if n == 0: print(f'No command found in {m.__name__}') aliases = text.unambiguous_prefixes(names) for cmd in commands: to_add = [] for prefix in aliases: if cmd.name.startswith(prefix): to_add.append(prefix) for alias in cmd.aliases: if alias.startswith(prefix): to_add.append(prefix) cmd.aliases += to_add bot.add_command(cmd)
Example #29
Source File: help.py From bot with MIT License | 5 votes |
def send_category_help(self, category: Category) -> None: """ Sends help for a bot category. This sends a brief help for all commands in all cogs registered to the category. """ embed = Embed() embed.set_author(name="Command Help", icon_url=constants.Icons.questionmark) all_commands = [] for cog in category.cogs: all_commands.extend(cog.get_commands()) filtered_commands = await self.filter_commands(all_commands, sort=True) command_detail_lines = self.get_commands_brief_details(filtered_commands, return_as_list=True) description = f"**{category.name}**\n*{category.description}*" if command_detail_lines: description += "\n\n**Commands:**" await LinePaginator.paginate( command_detail_lines, self.context, embed, prefix=description, max_lines=COMMANDS_PER_PAGE, max_size=2000, )
Example #30
Source File: help.py From bot with MIT License | 5 votes |
def send_command_help(self, command: Command) -> None: """Send help for a single command.""" embed = await self.command_formatting(command) message = await self.context.send(embed=embed) await help_cleanup(self.context.bot, self.context.author, message)