Python discord.ext.commands.CommandError() Examples
The following are 24
code examples of discord.ext.commands.CommandError().
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: snakes_cog.py From seasonalbot with MIT License | 6 votes |
def command_error(self, ctx: Context, error: CommandError) -> None: """Local error handler for the Snake Cog.""" embed = Embed() embed.colour = Colour.red() if isinstance(error, BadArgument): embed.description = str(error) embed.title = random.choice(ERROR_REPLIES) elif isinstance(error, OSError): log.error(f"snake_card encountered an OSError: {error} ({error.original})") embed.description = "Could not generate the snake card! Please try again." embed.title = random.choice(ERROR_REPLIES) else: log.error(f"Unhandled tag command error: {error} ({error.original})") return await ctx.send(embed=embed) # endregion
Example #2
Source File: converter.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def convert(self, ctx, argument): err = None try: logged_emote = await LoggedEmote().convert(ctx, argument) except commands.CommandError as exc: pass else: return logged_emote try: db_emote = await self.db_conv.convert(ctx, argument) except commands.CommandError as exc: raise commands.BadArgument( _('Failed to interpret {argument} as a logged emote message or an emote in my database.') .format(argument=argument)) return db_emote
Example #3
Source File: thread.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def __init__( self, manager: "ThreadManager", recipient: typing.Union[discord.Member, discord.User, int], channel: typing.Union[discord.DMChannel, discord.TextChannel] = None, ): self.manager = manager self.bot = manager.bot if isinstance(recipient, int): self._id = recipient self._recipient = None else: if recipient.bot: raise CommandError("Recipient cannot be a bot.") self._id = recipient.id self._recipient = recipient self._channel = channel self.genesis_message = None self._ready_event = asyncio.Event() self.close_task = None self.auto_close_task = None
Example #4
Source File: checks.py From xenon with GNU General Public License v3.0 | 6 votes |
def check_role_on_support_guild(role_name): async def predicate(ctx): support_guild = ctx.bot.get_guild(ctx.config.support_guild) if support_guild is None: log.warning("Support Guild is unavailable") raise cmd.CommandError( "The support guild is currently unavailable. Please try again later." ) try: member = await support_guild.fetch_member(ctx.author.id) except discord.NotFound: raise cmd.CommandError("You need to be on the support guild to use this command.") roles = filter(lambda r: r.name == role_name, member.roles) if len(list(roles)) == 0: raise cmd.CommandError( f"You are **missing** the `{role_name}` **role** on the support guild." ) return True return predicate
Example #5
Source File: templates.py From xenon with GNU General Public License v3.0 | 6 votes |
def approve(self, ctx, *, template_name): """ Approve a template __Arguments__ **template_name**: The name of the template """ template_name = template_name.lower().replace(" ", "_") template = await ctx.db.templates.find_one(template_name) if template is None: raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.") await ctx.send(**ctx.em(f"Successfully **approved template**.", type="success")) await self._approve(template)
Example #6
Source File: templates.py From xenon with GNU General Public License v3.0 | 6 votes |
def feature(self, ctx, *, template_name): """ Feature a template __Arguments__ **template_name**: The name of the template """ feature = True if ctx.invoked_with == "unfeature": feature = False template_name = template_name.lower().replace(" ", "_") template = await ctx.db.templates.find_one(template_name) if template is None: raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.") await ctx.send(**ctx.em(f"Successfully **{'un' if not feature else ''}featured template**.", type="success")) await self._feature(template, state=feature)
Example #7
Source File: templates.py From xenon with GNU General Public License v3.0 | 6 votes |
def delete(self, ctx, *, template_name): """ Delete a template __Arguments__ **template_name**: The name of the template """ template_name = template_name.lower().replace(" ", "_") template = await ctx.db.templates.find_one(template_name) if template is None: raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.") await self._delete(template, ctx.author, ctx.channel) await ctx.send(**ctx.em("Successfully **deleted/denied template**.", type="success"))
Example #8
Source File: admin.py From xenon with GNU General Public License v3.0 | 6 votes |
def su(self, ctx, member: discord.User, *, msg): """ Execute a command in place of another user __Arguments__ **member**: The user (must be a member of this guild) **msg**: The message, doesn't need to be a command """ if member.id == ctx.bot.owner_id: raise cmd.CommandError("How about ... **no**?") webhook = await ctx.channel.create_webhook(name="sudo") await webhook.send(content=msg, username=member.name, avatar_url=member.avatar_url) await webhook.delete() await asyncio.sleep(1) # Webhooks are slow message = ctx.message message.author = member message.content = msg await self.bot.process_commands(message)
Example #9
Source File: templates.py From xenon with GNU General Public License v3.0 | 6 votes |
def info(self, ctx, *, template_name): """ Get information about a template __Arguments__ **template_name**: The name of the template __Examples__ ```{c.prefix}template info starter``` """ template_name = template_name.lower().replace(" ", "_") template = await ctx.db.templates.find_one(template_name) if template is None: raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.") embed = self._template_info(template) embed._fields.insert(1, {"name": "Uses", "value": str(template.get("used") or 0), "inline": True}) await ctx.send(embed=embed)
Example #10
Source File: users.py From xenon with GNU General Public License v3.0 | 5 votes |
def __init__(self, bot): self.bot = bot @bot.check async def not_blacklisted(ctx): entry = await ctx.db.users.find_one({"_id": ctx.author.id, "blacklist.state": True}) if entry is None: return True raise cmd.CommandError("Sorry, **you are blacklisted**.\n\n" f"**Reason**: {entry['blacklist']['reason']}")
Example #11
Source File: core.py From NabBot with Apache License 2.0 | 5 votes |
def on_command_error(self, ctx: context.NabCtx, error: commands.CommandError): """Handles command errors""" if isinstance(error, commands.errors.CommandNotFound): return elif isinstance(error, commands.CommandOnCooldown): await ctx.error(f"You're using this too much! " f"Try again {timing.HumanDelta.from_seconds(error.retry_after).long(1)}.") elif isinstance(error, commands.CheckFailure): await self.process_check_failure(ctx, error) elif isinstance(error, commands.UserInputError): await self.process_user_input_error(ctx, error) elif isinstance(error, commands.CommandInvokeError): await self.process_command_invoke_error(ctx, error) else: log.warning(f"Unhandled command error {error.__class__.__name__}: {error}")
Example #12
Source File: converter.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
def convert(cls, context, argument): channel, argument = await cls._parse_argument(context, argument) await cls._check_reaction_permissions(context, channel) for converter in convert_offset, convert_id, convert_member, convert_keyword: try: return await converter(context, channel, argument) except commands.CommandError as exception: pass raise commands.BadArgument(_( 'Failed to interpret that as a message offset, message ID, or user, ' 'or failed to find a message containing that search keyword.'))
Example #13
Source File: checks.py From RPGBot with GNU General Public License v3.0 | 5 votes |
def role_or_permissions(ctx, check, **perms): if check_permissions(ctx, perms): return True if callable(check): fcheck = check else: fcheck = lambda r: r.name in check ch = ctx.message.channel author = ctx.message.author if isinstance(ch, (discord.DMChannel, discord.GroupChannel)): return False # can't have roles in PMs role = discord.utils.find(fcheck, author.roles) if role is None: if callable(check): raise commands.CommandError("You do not have permission to use this command!") else: for role in ctx.guild.roles: if role.name in check: raise commands.CommandError( "You need a special role to do this! ({})".format(", ".join(f"'{n}'" for n in check))) else: raise commands.CommandError("You need to create a role with one of the following names and give it to " "yourself: {}".format(", ".join(f"'{n}'" for n in check))) return True
Example #14
Source File: admin.py From xenon with GNU General Public License v3.0 | 5 votes |
def reload(self, ctx, cog): """ Reload a cog __Arguments__ **cog**: The name of the cog """ if cog.lower() == "all": failed = 0 success = 0 for cog in self.bot.config.extensions: try: self.bot.reload_extension(cog) success += 1 except: failed += 1 traceback.print_exc() await ctx.send(**ctx.em(f"Reloaded all cogs.\n**Success**: {success} **Failed**: {failed}", type="info")) return base_path = "cogs." try: self.bot.reload_extension(base_path + cog.lower()) await ctx.send(**ctx.em(f"Successfully reloaded the cog named **{cog}**.", type="success")) except: traceback.print_exc() raise cmd.CommandError(f"Error while reloading the cog named **{cog}**.")
Example #15
Source File: templates.py From xenon with GNU General Public License v3.0 | 5 votes |
def _approve(self, template, *args): await self.bot.db.templates.update_one({"_id": template["_id"]}, {"$set": {"approved": True}}) try: channel = await self.bot.fetch_channel(self.bot.config.template_list) await channel.send(embed=self._template_info(template)) except Exception as e: raise cmd.CommandError("Failed to access the template list channel: **%s**" % str(e)) try: user = await self.bot.fetch_user(template["creator"]) await user.send(**self.bot.em(f"Your **template `{template['_id']}` has been approved**.", type="info")) except: pass
Example #16
Source File: backups.py From xenon with GNU General Public License v3.0 | 5 votes |
def info(self, ctx, backup_id): """ Get information about a backup __Arguments__ **backup_id**: The id of the backup or the guild id to for latest automated backup __Examples__ ```{c.prefix}backup info oj1xky11871fzrbu``` """ backup_id = str(ctx.guild.id) if backup_id.lower() == "interval" else backup_id backup = await self._get_backup(backup_id) if backup is None or backup.get("creator") != ctx.author.id: raise cmd.CommandError(f"You have **no backup** with the id `{backup_id}`.") handler = BackupInfo(self.bot, backup["backup"]) embed = ctx.em("")["embed"] embed.title = handler.name embed.set_thumbnail(url=handler.icon_url) embed.add_field(name="Creator", value=f"<@{backup['creator']}>") embed.add_field(name="Members", value=handler.member_count, inline=True) embed.add_field(name="Created At", value=helpers.datetime_to_string( backup["timestamp"]), inline=False ) embed.add_field(name="Channels", value=handler.channels(), inline=True) embed.add_field(name="Roles", value=handler.roles(), inline=True) await ctx.send(embed=embed)
Example #17
Source File: backups.py From xenon with GNU General Public License v3.0 | 5 votes |
def purge(self, ctx): """ Delete all your backups __**This cannot be undone**__ __Examples__ ```{c.prefix}backup purge``` """ warning = await ctx.send( **ctx.em("Are you sure that you want to delete all your backups?\n" "__**This cannot be undone!**__", type="warning")) await warning.add_reaction("✅") await warning.add_reaction("❌") try: reaction, user = await self.bot.wait_for( "reaction_add", check=lambda r, u: r.message.id == warning.id and u.id == ctx.author.id, timeout=60) except TimeoutError: await warning.delete() raise cmd.CommandError( "Please make sure to **click the ✅ reaction** to delete all of your backups.") if str(reaction.emoji) != "✅": ctx.command.reset_cooldown(ctx) await warning.delete() return await ctx.db.backups.delete_many({"creator": ctx.author.id}) await ctx.send(**ctx.em("Deleted all your backups.", type="success"))
Example #18
Source File: backups.py From xenon with GNU General Public License v3.0 | 5 votes |
def create(self, ctx): """ Create a backup __Examples__ ```{c.prefix}backup create``` """ backup_count = await ctx.db.backups.count_documents({"creator": ctx.author.id}) if backup_count >= max_backups: raise cmd.CommandError("You have **exceeded the maximum count** of backups.\n\n" f"Upgrade to Pro (`x!pro`) to be able to create more than **{max_backups}**. " f"backups **or delete one of your old backups** (`x!backup list` " f"& `x!backup delete <id>`).") status = await ctx.send(**ctx.em("**Creating backup** ... Please wait", type="working")) handler = BackupSaver(self.bot, self.bot.session, ctx.guild) backup = await handler.save() id = await self._save_backup(ctx.author.id, backup) embed = ctx.em(f"Successfully **created backup** with the id `{id}`.\n", type="success")["embed"] embed.add_field(name="Usage", value=f"```{ctx.prefix}backup load {id}```\n```{ctx.prefix}backup info {id}```") await status.edit(embed=embed) try: if ctx.author.is_on_mobile(): await ctx.author.send(f"{ctx.prefix}backup load {id}") else: embed = ctx.em( f"Created backup of **{ctx.guild.name}** with the backup id `{id}`\n", type="info")["embed"] embed.add_field(name="Usage", value=f"```{ctx.prefix}backup load {id}```\n```{ctx.prefix}backup info {id}```") await ctx.author.send(embed=embed) except Exception: pass
Example #19
Source File: builder.py From xenon with GNU General Public License v3.0 | 5 votes |
def _cancel(self): try: await self.msg.clear_reactions() except Exception: pass raise cmd.CommandError("You canceled the build process.")
Example #20
Source File: builder.py From xenon with GNU General Public License v3.0 | 5 votes |
def run(self): self.msg = await self.ctx.send(embed=self._create_embed()) options = { **{f"{i + 1}\u20e3": self._switch_option(i) for i in range(9)}, "◀": self._prev_page, "▶": self._next_page, "❎": self._cancel, "✅": self._finish, } for option in options: await self.msg.add_reaction(option) try: async for reaction, user in helpers.IterWaitFor( self.ctx.bot, event="reaction_add", check=lambda r, u: u.id == self.ctx.author.id and r.message.id == self.msg.id and str(r.emoji) in options.keys(), timeout=3 * 60 ): self.ctx.bot.loop.create_task(self.msg.remove_reaction(reaction.emoji, user)) if not await options[str(reaction.emoji)](): try: await self.msg.clear_reactions() except Exception: pass return {name: value for page in self.pages for name, value in page["options"]} await self.update() except asyncio.TimeoutError: try: await self.msg.clear_reactions() except Exception: pass raise cmd.CommandError("**Canceled build process**, because you didn't do anything.")
Example #21
Source File: basic_voice.py From discord.py with MIT License | 5 votes |
def ensure_voice(self, ctx): if ctx.voice_client is None: if ctx.author.voice: await ctx.author.voice.channel.connect() else: await ctx.send("You are not connected to a voice channel.") raise commands.CommandError("Author not connected to a voice channel.") elif ctx.voice_client.is_playing(): ctx.voice_client.stop()
Example #22
Source File: templates.py From xenon with GNU General Public License v3.0 | 4 votes |
def load(self, ctx, template_name, *options): """ Load a template You can find templates in the #template-list and #featured-templates channels on the support discord. The template name is always the first line of the message (e.g. "starter"), you don't need the backup id! You can also use `{c.prefix}backup search <search-term>` to find templates. __Arguments__ **template_name**: The name of the template __Examples__ Default options ```{c.prefix}template load starter``` Only roles ```{c.prefix}template load starter !* roles``` """ template_name = template_name.lower().replace(" ", "_") template = await ctx.db.templates.find_one(template_name) if template is None: raise cmd.CommandError(f"There is **no template** with the name `{template_name}`.") warning = await ctx.send( **ctx.em("Are you sure you want to load this template? **All channels and roles will get replaced!**", type="warning")) await warning.add_reaction("✅") await warning.add_reaction("❌") try: reaction, user = await self.bot.wait_for( "reaction_add", check=lambda r, u: r.message.id == warning.id and u.id == ctx.author.id, timeout=60) except TimeoutError: await warning.delete() raise cmd.CommandError( "Please make sure to **click the ✅ reaction** in order to load the template." ) if str(reaction.emoji) != "✅": ctx.command.reset_cooldown(ctx) await warning.delete() return await ctx.db.templates.update_one({"_id": template_name}, {"$inc": {"used": 1}}) handler = BackupLoader(self.bot, self.bot.session, template["template"]) await handler.load(ctx.guild, ctx.author, types.BooleanArgs( ["channels", "roles"] + list(options) ))
Example #23
Source File: checks.py From xenon with GNU General Public License v3.0 | 4 votes |
def bot_has_managed_top_role(): async def predicate(ctx): if ctx.guild.roles[-1].managed and ctx.guild.roles[-1] in ctx.guild.me.roles: return True else: sended = await ctx.send(**ctx.em( f"The role called **{ctx.bot.user.name}** is currently not at the top of the role hierarchy.\n\n" "Continuing could cause bugs. Do you want to continue?", type="warning")) await sended.add_reaction("✅") await sended.add_reaction("❌") try: reaction, user = await ctx.bot.wait_for( "reaction_add", check=lambda r, u: r.message.id == sended.id and u.id == ctx.author.id, timeout=60) except asyncio.TimeoutError: try: ctx.command.reset_cooldown(ctx) except: pass await sended.delete() raise cmd.CommandError( "Please make sure to **click the ✅ reaction** in order to continue.") if str(reaction.emoji) != "✅": try: ctx.command.reset_cooldown(ctx) except: pass await sended.delete() raise cmd.CommandError( "Please make sure to **click the ✅ reaction** in order to continue.") await sended.delete() return True return cmd.check(predicate)
Example #24
Source File: backups.py From xenon with GNU General Public License v3.0 | 4 votes |
def load(self, ctx, backup_id, *options): """ Load a backup __Arguments__ **backup_id**: The id of the backup or the guild id of the latest automated backup **options**: A list of options (See examples) __Examples__ Default options: ```{c.prefix}backup load oj1xky11871fzrbu``` Only roles: ```{c.prefix}backup load oj1xky11871fzrbu !* roles``` Everything but bans: ```{c.prefix}backup load oj1xky11871fzrbu !bans``` """ backup_id = str(ctx.guild.id) if backup_id.lower() == "interval" else backup_id backup = await self._get_backup(backup_id) if backup is None or backup.get("creator") != ctx.author.id: raise cmd.CommandError(f"You have **no backup** with the id `{backup_id}`.") warning = await ctx.send( **ctx.em("Are you sure you want to load this backup? " "**All channels and roles will get deleted** and reconstructed from the backup!\n" "**Messages will not get loaded** and will be lost, use " "[Xenon Pro](https://www.patreon.com/merlinfuchs) to load up to 25 messages per channel.", type="warning")) await warning.add_reaction("✅") await warning.add_reaction("❌") try: reaction, user = await self.bot.wait_for( "reaction_add", check=lambda r, u: r.message.id == warning.id and u.id == ctx.author.id, timeout=60) except TimeoutError: await warning.delete() raise cmd.CommandError( "Please make sure to **click the ✅ reaction** to load the backup.") if str(reaction.emoji) != "✅": ctx.command.reset_cooldown(ctx) await warning.delete() return handler = BackupLoader(self.bot, self.bot.session, backup["backup"]) await handler.load(ctx.guild, ctx.author, types.BooleanArgs( ["channels", "roles", "bans", "members", "settings"] + list(options) )) await ctx.guild.text_channels[0].send(**ctx.em("Successfully loaded backup.", type="success"))