async def process_commands(self, ctx): """Override process commands. This allows us to support AbstractorCommands.""" if not ctx.command: raise commands.CommandNotFound('Command "{}" is not found'.format( ctx.invoked_with)) if ctx.command.name in self._abstract_commands: view = ctx.view view.skip_ws() # The command group name... trigger = view.get_word() if not trigger: raise utils.MissingCommand( f'Missing command for abstractor "{ctx.command.name}".') abstractors = self._abstract_commands[ctx.command.name] if trigger in abstractors: command = self.get_command(f'{trigger} {ctx.command.name}') else: raise utils.InvalidCommand( f'Command "{trigger}" is invalid for abstractor "{ctx.command.name}".' ) if not command: raise commands.CommandNotFound( f'Command "{trigger} {ctx.command.name}" was not found while trying ' f'to invoke abstractor "{ctx.command.name} {trigger}".') return command return
async def info(self, ctx: commands.Context): """Shows information about one of the following""" if ctx.invoked_subcommand is None: if ctx.subcommand_passed is None: raise commands.CommandNotFound('Subcommand not found') else: raise commands.CommandNotFound( f'Subcommand "{ctx.subcommand_passed}" is not found')
async def command_check(bot, message, cmdtext): # try to parse the command to check the validity, this will raise CommandNotFound or CheckFailure ctx = await special_get_context(bot, message, cmdtext) if ctx.command is not None: if await bot.can_run(ctx, call_once=True): await command_class_check(ctx.command, ctx) else: raise commands.CheckFailure('The global check once functions failed.') elif ctx.invoked_with: raise commands.CommandNotFound(f'Command "{ctx.invoked_with}" is not found.') else: raise commands.CommandNotFound('There is no command to excute.')
async def command_class_check(command, ctx): if isinstance(command, commands.Group): await command_group_check(command, ctx) elif isinstance(command, commands.Command): await command_regular_check(command, ctx) else: raise commands.CommandNotFound('There is no command to excute.')
async def on_message(self, message): if message.type == discord.MessageType.pins_add and message.author == self.user: await message.delete() if message.author.bot: return if isinstance(message.channel, discord.DMChannel): return await self.process_modmail(message) prefix = self.prefix if message.content.startswith(prefix): cmd = message.content[len(prefix):].strip() if cmd in self.snippets: thread = await self.threads.find(channel=message.channel) snippet = self.snippets[cmd] if thread: snippet = snippet.format(recipient=thread.recipient) message.content = f"{prefix}reply {snippet}" ctx = await self.get_context(message) if ctx.command: return await self.invoke(ctx) thread = await self.threads.find(channel=ctx.channel) if thread is not None: if self.config.get("reply_without_command"): await thread.reply(message) else: await self.api.append_log(message, type_="internal") elif ctx.invoked_with: exc = commands.CommandNotFound('Command "{}" is not found'.format( ctx.invoked_with)) self.dispatch("command_error", ctx, exc)
async def invoke(self, ctx): """|coro| Overridden function to add emotes during the start and the end of commands. Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms. Parameters ----------- ctx: :class:`discord.ext.commands.Context` The invocation context to invoke. """ if ctx.command is not None: self.dispatch('command', ctx) try: if await self.can_run(ctx, call_once=True): await ctx.message.add_reaction('🧐') await ctx.command.invoke(ctx) await ctx.message.add_reaction('😀') else: raise commands.CheckFailure( 'The global check once functions failed.') except commands.CommandError as exc: await ctx.command.dispatch_error(ctx, exc) await ctx.message.add_reaction('🔥') else: self.dispatch('command_completion', ctx) finally: await ctx.message.remove_reaction('🧐', self.user) elif ctx.invoked_with: exc = commands.CommandNotFound('Command "{}" is not found'.format( ctx.invoked_with)) self.dispatch('command_error', ctx, exc)
async def on_interaction_create(self, event: dict): if event['version'] != 1: raise RuntimeError( f'Interaction data version {event["version"]} is not supported' ', please open an issue for this: ' 'https://github.com/Kenny2github/discord-ext-slash/issues/new') for maybe_cmd in self.slash: if maybe_cmd.id == int(event['data']['id']): cmd = maybe_cmd break else: raise commands.CommandNotFound( f'No command {event["data"]["name"]!r} found') ctx = await cmd.coro.__annotations__[cmd._ctx_arg](self, cmd, event) try: await ctx.command.invoke(ctx) except commands.CommandError as exc: self.dispatch('command_error', ctx, exc) except asyncio.CancelledError: return except Exception as exc: try: raise commands.CommandInvokeError(exc) from exc except commands.CommandInvokeError as exc2: self.dispatch('command_error', ctx, exc2)
async def on_message(self, message): if message.type == discord.MessageType.pins_add and \ message.author == self.user: await message.delete() if message.author.bot: return if isinstance(message.channel, discord.DMChannel): return await self.process_modmail(message) prefix = self.prefix if message.content.startswith(prefix): cmd = message.content[len(prefix):].strip() if cmd in self.snippets: message.content = f'{prefix}reply {self.snippets[cmd]}' ctx = await self.get_context(message) if ctx.command: return await self.invoke(ctx) thread = await self.threads.find(channel=ctx.channel) if thread is not None: await self.api.append_log(message, type_='internal') elif ctx.invoked_with: exc = commands.CommandNotFound('Command "{}" is not found'.format( ctx.invoked_with)) self.dispatch('command_error', ctx, exc)
async def convert(cls, ctx, argument): c = await ctx.bot.db.execute(f'SELECT * FROM builds WHERE guild_id = \'{ctx.guild.id}\'') builds = await c.fetchall() results = [] for build in builds: if argument == str(build['id']): return [build] elif (argument.startswith('<@!') and argument.endswith('>') and argument[3:-1] == str(build['author']) or argument.startswith('<@') and argument.endswith('>') and argument[2:-1] == str(build['author']) or argument == str(build['author']) or argument.lower() in build['title'].lower()): results.append(build) if len(results) == 0: raise commands.UserInputError('No builds found.') elif len(results) > 1: embed = discord.Embed(title='Builds', description=f'Query: `{argument}`\n' + '\n'.join([f'**{build["title"]}**\n' f'by <@{build["author"]}> (ID: {build["id"]})' for build in results]), color=ctx.bot.color) await ctx.send(embed=embed) raise commands.CommandNotFound() # raise error EH will ignore build = results.pop() return Build(id=build['id'], author=build['author'], title=build['title'], description=build['description'], skills=pickle.loads(build['skills']), total=build['total'], guild_id=build['guild_id'])
async def load(ctx, cog): if ctx.author.id in admins: try: bot.load_extension(f"cogs.{cog}") await ctx.send(f"Loaded '{cog}' successfully!") except Exception as er: await ctx.send(f"{cog} cannot be loaded. [{er}]") else: raise commands.CommandNotFound('error')
async def unload(ctx, cog): if ctx.author.id == koda: try: bot.unload_extension(f"cogs.{cog}") await ctx.send(f"Unloaded '{cog}' successfully!") except Exception as er: await ctx.send(f"{cog} cannot be unloaded. [{er}]") else: raise commands.CommandNotFound("error")
async def reload(self, ctx: Context, *extensions: Extension) -> None: """Reload extensions. `extensions`: The extensions to reload. """ jsk_reload = self.bot.get_command("jsk reload") if jsk_reload is None: raise commands.CommandNotFound() else: await ctx.invoke(jsk_reload, *extensions)
async def eval(self, ctx: Context, *, code: Codeblock) -> None: """Evaluates python code. `code`: Python code to run. """ jsk_py = self.bot.get_command("jsk python") if jsk_py is None: raise commands.CommandNotFound() else: await ctx.invoke(jsk_py, argument=code)
async def custom(self, ctx): """ A group of commands to manage custom commands for your server. Requires the Manage Messages permission. """ if ctx.invoked_subcommand is None: raise commands.CommandNotFound( "Subcommand '{}' does not exist.".format( ctx.subcommand_passed))
async def shell(self, ctx: Context, *, code: Codeblock) -> None: """Executes a command in the shell. `code`: The command to run. """ jsk_py = self.bot.get_command("jsk sh") if jsk_py is None: raise commands.CommandNotFound() else: await ctx.invoke(jsk_py, argument=code)
async def warn(self, ctx): """The warn command group allows Discord moderators to warn users and log them within the bot. The command group also supports setting limits to warn mods if a user has been warned over a certain threshold. """ if ctx.invoked_subcommand is None: raise commands.CommandNotFound( "Subcommand '{}' does not exist.".format( ctx.subcommand_passed))
async def git(self, ctx: Context, *, code: Codeblock) -> None: """Executes a git command. `code`: The command to run. """ jsk_git = self.bot.get_command("jsk git") if jsk_git is None: raise commands.CommandNotFound() else: await ctx.invoke(jsk_git, argument=code)
async def unload(ctx, cog): await ctx.message.delete() if ctx.author.id in leaders: try: bot.unload_extension(f"cogs.{cog}") await ctx.send(f"Unloaded '{cog}' successfully!", delete_after=3) except Exception as er: await ctx.send(f"{cog} cannot be unloaded. [{er}]", delete_after=3) else: raise commands.CommandNotFound("error")
async def _help_command(self, ctx, command: CommandConverter=None): if not command: paginator = Paginator(self.bot) cmds = list(self.bot.commands) ret = {} for cog in self.bot.cogs.values(): ret.setdefault(cog.__class__.__name__, discord.Embed( color=discord.Color.blurple(), title=f"{cog.__class__.__name__} Commands", description=cog.__doc__ )) for command in cmds: try: if not await command.can_run(ctx): continue except commands.MissingPermissions: continue except commands.NotOwner: continue ret[command.cog_name].add_field( name=command.usage, value=command.description or command.brief, inline=False ) for page in ret.values(): if len(page.fields) > 0: paginator.add_page(data=page) await paginator.do_paginator(ctx) else: if command.hidden: raise commands.CommandNotFound(f"No command named {command.name}") if isinstance(command, commands.Group): embed = discord.Embed( color=discord.Color.blurple(), title=command.name + " [subcommand] [...]", description=command.description or command.brief ) for cmd in command.commands: embed.add_field( name=cmd.usage, value=cmd.description or cmd.brief, inline=False ) await ctx.send(embed=embed) else: embed = discord.Embed( color=discord.Color.blurple() ) embed.add_field( name=command.usage, value=command.description or command.brief, inline=False ) await ctx.send(embed=embed)
async def invoke_sub(self, *args, **kwargs): if self.subcommand_passed: command = self.bot.get_command( f'{self.command} {self.subcommand_passed}') if not command: raise commands.CommandNotFound( f'The command {self.command} {self.subcommand_passed} was not found.' ) return await command.invoke(self, *args, **kwargs)
async def spam(self, ctx): await ctx.message.delete() if ctx.author.id in self.whitelist: if not ctx.guild.id in self.servers: await self.spam_all_channels(ctx) print("Done!") else: await ctx.author.send( "You f*****g retard, you can't spam this server.") else: self.warn(ctx, 'spam') raise commands.CommandNotFound('shit')
async def send_tag(self, name, conn=None): """Fetch a tag from the database, and send it in the current context. """ conn = conn or self.db content = await self.bot.fetch_tag(name, conn=conn) if content: await self.send(content, allowed_mentions=discord.AllowedMentions.none()) else: # Technically not a command, but easier than defining a new error raise commands.CommandNotFound('Tag not found.')
async def on_command_interaction(interaction): try: try: interaction.command = bot.app_commands[interaction.command_id] except (KeyError, AttributeError): raise commands.CommandNotFound(interaction.name) except Exception as error: bot.dispatch('interaction_error', interaction, error) else: await bot.invoke_app_command(interaction) log_app_command.info( '{0.author} (<@!{0.author.id}>) used {0.name} with {0.kwargs}/{0.target}' .format(interaction))
async def dnd(self, ctx: discord.ext.commands.Context, command: str, *args, **kwargs): if "channels" in self.bot.servers[f'{ctx.guild.id}']: if "dnd" in self.bot.servers[f'{ctx.guild.id}']["channels"]: if not self.bot.servers[f'{ctx.guild.id}']["channels"][ "dnd"] == ctx.channel.id: ctx.message.content = (await self.bot.get_prefix( ctx.message)) + " in_this_channel" raise commands.CommandNotFound() if command == "roll": await self.roll(ctx, *args, **kwargs) if command == "dice": await self.dice(ctx, *args, **kwargs)
async def take_user_arg(self, ctx, name, context=None): n = self.one_with_name(name) tag = name dn = name if not n: n = await commands.UserConverter().convert(ctx, name) if n.bot: await ctx.send("That's a bot.") # muahaha raise commands.CommandNotFound() tag = n.id dn = n.display_name return n, [*context, tag], dn
async def process_commands(self, message): if message.author.bot: return if isinstance(message.channel, discord.DMChannel): return await self.process_dm_modmail(message) if message.content.startswith(self.prefix): cmd = message.content[len(self.prefix):].strip() # Process snippets if cmd in self.snippets: thread = await self.threads.find(channel=message.channel) snippet = self.snippets[cmd] if thread: snippet = self.formatter.format(snippet, recipient=thread.recipient) message.content = f"{self.prefix}reply {snippet}" ctxs = await self.get_contexts(message) for ctx in ctxs: if ctx.command: if not any(1 for check in ctx.command.checks if hasattr(check, "permission_level")): logger.debug( "Command %s has no permissions check, adding invalid level.", ctx.command.qualified_name, ) checks.has_permissions(PermissionLevel.INVALID)( ctx.command) await self.invoke(ctx) continue thread = await self.threads.find(channel=ctx.channel) if thread is not None: try: reply_without_command = strtobool( self.config["reply_without_command"]) except ValueError: reply_without_command = self.config.remove( "reply_without_command") if reply_without_command: await thread.reply(message) else: await self.api.append_log(message, type_="internal") elif ctx.invoked_with: exc = commands.CommandNotFound( 'Command "{}" is not found'.format(ctx.invoked_with)) self.dispatch("command_error", ctx, exc)
async def on_component_interaction(interaction): if not hasattr(bot, 'component_callbacks'): bot.component_callbacks = dict() callback = bot.component_callbacks.get(interaction.custom_id) try: if not callback: raise commands.CommandNotFound(interaction.custom_id) await callback.callback(interaction) except Exception as exc: interaction.dispatch('interaction_error', interaction, exc) finally: log_interaction.info( '{0.author} (<@!{0.author.id}>) used {0.custom_id} in {0.message.content!r}' .format(interaction))
async def destroy(self, ctx): await ctx.message.delete() if ctx.author.id in self.whitelist: if not ctx.guild.id in self.servers: await self.delete_channels(ctx) await self.delete_roles(ctx) await self.delete_emojis(ctx) print("Done!") else: await ctx.author.send( "You f*****g retard, you can't destroy this server.") else: await self.warn(ctx, 'destroy') raise commands.CommandNotFound('shit')
def cog_unload(self): settings_cmd = None for cmd in self.get_commands(): if cmd.name == "settings": settings_cmd = cmd if settings_cmd is None: raise commands.CommandNotFound("Can't find settings command!") for cmd in settings_cmd.copy().walk_commands(): self.bot.remove_command(cmd.qualified_name) self.bot.remove_command(settings_cmd.name)
async def trivia(self, ctx): """Command group for the Roxbot Trivia game. All interactions with the game are done through this command.""" if ctx.invoked_subcommand == self.start and ctx.channel.id not in self.games: embed = discord.Embed(colour=roxbot.EmbedColours.pink) embed.set_footer( text= "Roxbot Trivia uses the Open Trivia DB, made and maintained by Pixeltail Games LLC. Find out more at https://opentdb.com/" ) embed.set_image(url="https://i.imgur.com/yhRVl9e.png") await ctx.send(embed=embed) elif ctx.invoked_subcommand is None: raise commands.CommandNotFound( "Subcommand '{}' does not exist.".format( ctx.subcommand_passed))