def role_by_substring(ctx: commands.Context, substring: str):
"""This searches for a role by substrings."""
try:
return await roleconverter.convert(ctx, substring)
except commands.CommandError:
pass
substring = substring.lower()
for role in ctx.guild.roles:
if substring in role.name.lower():
return role
raise commands.BadArgument(f"No role with substring `{substring}` was found.")
python类BadArgument()的实例源码
def _get_random_author_quote(self, ctx, author):
sid = ctx.message.server.id
if sid not in self.quotes or len(self.quotes[sid]) == 0:
raise AssertionError("There are no quotes in this server!")
if isinstance(author, discord.User):
uid = author.id
quotes = [(i, q) for i, q in enumerate(self.quotes[sid]) if q['author_id'] == uid]
else:
quotes = [(i, q) for i, q in enumerate(self.quotes[sid]) if q['author_name'] == author]
if len(quotes) == 0:
raise commands.BadArgument("There are no quotes by %s." % author)
return randchoice(quotes)
def addquote(self, ctx, message: str, *, author: str = None):
"""Adds a quote to the server quote list. The quote must be enclosed
in \"double quotes\". If a member mention or name is the last argument,
the quote will be stored as theirs. If not, the last argument will
be stored as the quote's author. If left empty, "Unknown" is used.
"""
if author:
try:
author = commands.MemberConverter(ctx, author).convert()
except commands.errors.BadArgument:
author = author.strip(' \t\n\r\x0b\x0c-–—') # whitespace + dashes
pass
self._add_quote(ctx, author, message)
await self.bot.say("Quote added.")
def member_check(self, ctx, member):
try:
return await commands.converter.MemberConverter().convert(ctx, member)
except (commands.BadArgument, commands.NoPrivateMessage):
return None
def convert(self):
cache_path = os.path.join('data/audio/cache', self.argument)
if not os.path.exists(cache_path):
raise commands.BadArgument("Cache file '{}' not found.".format(
cache_path))
return cache_path
def convert(self):
cache_path = os.path.join('data/audio/cache',
self.argument + "-encoded")
if not os.path.exists(cache_path):
raise commands.BadArgument("Cache file '{}' not found.".format(
cache_path))
return cache_path
def convert(self, ctx, argument):
match = EMOJI_REGEX.match(argument)
if not match:
raise commands.BadArgument('Invalid custom emoji.')
return BareCustomEmoji(id=int(match.group(2)), name=match.group(1))
def convert(self, ctx, argument):
for converter in (MemberConverter, UserConverter):
try:
return await converter().convert(ctx, argument)
except commands.BadArgument:
pass
try:
return await ctx.bot.get_user_info(argument)
except discord.HTTPException:
raise commands.BadArgument("That user wasn't found.")
def convert(self, ctx, argument):
try:
return await MemberConverter().convert(ctx, argument)
except commands.BadArgument:
try:
return discord.Object(id=int(argument))
except ValueError:
raise commands.BadArgument('Invalid member ID. I also couldn\'t find the user by username.')
def convert(self, ctx, argument):
# Scan attached images.
if argument == 'attached':
for attachment in ctx.message.attachments:
if attachment.height:
return attachment.proxy_url
# Scan channel for any recent images.
if argument == 'recent':
result = await _get_recent_image(ctx.channel)
if not result:
raise commands.BadArgument('No recent image was found in this channel.')
return result
try:
# Resolve avatar.
user = await UserConverter().convert(ctx, argument)
return user.avatar_url_as(format='png')
except commands.BadArgument:
pass
# ok image
if any(argument.startswith(safe_url) for safe_url in SAFE_IMAGE_HOSTS):
return argument
error = ("Invalid image URL or user. To use a recent image from this channel, specify `recent`. You can also "
"attach any image and specify `attached` to use that image.")
raise commands.BadArgument(error)
def convert(self, ctx, arg):
try:
days = int(arg)
if days < 0 or days > 7:
raise commands.BadArgument('Invalid `delete_days`: cannot be lower than 0, or higher than 7.')
except ValueError:
raise commands.BadArgument('Invalid `delete_days`: not a valid number.')
return days
def convert(cls: Enum, ctx: 'DogbotContext', arg: str):
try:
if arg not in [e.name for e in cls]:
return cls[arg.upper()]
else:
return cls[arg]
except KeyError:
# value in enum not found
valid_keys = ', '.join('`{}`'.format(num.name.lower()) for num in list(cls))
raise commands.BadArgument('Invalid type. Valid types: {}'.format(valid_keys))
def convert(self, ctx, arg):
if arg == 'default':
return ''
if len(arg) != 5:
raise commands.BadArgument('Languages are 5 letters long, like so: `en-US`')
if not os.path.isfile(f'./resources/lang/{arg}.yml'):
raise commands.BadArgument('That language isn\'t supported.')
return arg
def _cog__error(self, ctx, error):
if isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, errors.InvalidUsernameError):
await ctx.send(f'Invalid username: {str(original)}')
if isinstance(original, errors.StreamerNotFoundError):
await ctx.send(f'Streamer not found: {str(original)}')
if isinstance(original, errors.NotSubscribedError):
await ctx.send(f"You're not subscriber to the streamer {str(original)}")
if isinstance(original, errors.StreamerAlreadyExists):
await ctx.send("You're already subscribed to this streamer!")
if isinstance(original, errors.InvalidChannelError):
await ctx.send(str(original))
if isinstance(error, commands.BadArgument):
await ctx.send(str(error))
def convert(cls, ctx, arg):
lowered = arg.lower()
try:
return cls[lowered]
except KeyError:
difficulties = '\n'.join(str(m).lower() for m in cls)
raise commands.BadArgument(f'"{arg}"" is not a valid level. Valid difficulties:\n{difficulties}') from None
def _get_category(self, ctx, category):
lowered = category.lower()
c = self.default_categories.get(lowered)
if not c:
raise commands.BadArgument(f"Category {category} doesn't exist... :(")
return c
def _error(self, ctx, error):
if isinstance(error, NoSelfArgument):
message = random.choice((
"Don't play with yourself. x3",
"You should mention someone else over there. o.o",
"Self inviting, huh... :eyes:",
))
await ctx.send(message)
elif issubclass(type(error), commands.BadArgument) and not type(error) is commands.BadArgument:
await ctx.send(error)
def convert(cls, ctx, arg):
try:
return cls[arg.lower()]
except KeyError:
raise commands.BadArgument(f'{arg} is not a valid side...')
def convert(cls, ctx, arg):
lowered = arg.lower()
with contextlib.suppress(KeyError):
return cls._default_categories[lowered]
query = ctx.session.select.from_(cls).where((cls.guild_id == ctx.guild.id)
& (cls.name == lowered))
result = await query.first()
if result is None:
raise commands.BadArgument(f"Category {lowered} doesn't exist... :(")
return result
def convert(cls, ctx, arg):
lowered = arg.lower()
try:
return cls[lowered]
except KeyError:
raise commands.BadArgument(f'No level called {arg}.') from None