本文整理汇总了Python中discord.ext.commands.BadArgument方法的典型用法代码示例。如果您正苦于以下问题:Python commands.BadArgument方法的具体用法?Python commands.BadArgument怎么用?Python commands.BadArgument使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.ext.commands
的用法示例。
在下文中一共展示了commands.BadArgument方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vote
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def vote(self, ctx: Context, title: str, *options: str) -> None:
"""
Build a quick voting poll with matching reactions with the provided options.
A maximum of 20 options can be provided, as Discord supports a max of 20
reactions on a single message.
"""
if len(options) < 2:
raise BadArgument("Please provide at least 2 options.")
if len(options) > 20:
raise BadArgument("I can only handle 20 options!")
codepoint_start = 127462 # represents "regional_indicator_a" unicode value
options = {chr(i): f"{chr(i)} - {v}" for i, v in enumerate(options, start=codepoint_start)}
embed = Embed(title=title, description="\n".join(options.values()))
message = await ctx.send(embed=embed)
for reaction in options:
await message.add_reaction(reaction)
示例2: allowed_strings
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def allowed_strings(*values, preserve_case: bool = False) -> t.Callable[[str], str]:
"""
Return a converter which only allows arguments equal to one of the given values.
Unless preserve_case is True, the argument is converted to lowercase. All values are then
expected to have already been given in lowercase too.
"""
def converter(arg: str) -> str:
if not preserve_case:
arg = arg.lower()
if arg not in values:
raise BadArgument(f"Only the following values are allowed:\n```{', '.join(values)}```")
else:
return arg
return converter
示例3: convert
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def convert(ctx: Context, url: str) -> str:
"""This converter checks whether the given URL can be reached with a status code of 200."""
try:
async with ctx.bot.http_session.get(url) as resp:
if resp.status != 200:
raise BadArgument(
f"HTTP GET on `{url}` returned status `{resp.status}`, expected 200"
)
except CertificateError:
if url.startswith('https'):
raise BadArgument(
f"Got a `CertificateError` for URL `{url}`. Does it support HTTPS?"
)
raise BadArgument(f"Got a `CertificateError` for URL `{url}`.")
except ValueError:
raise BadArgument(f"`{url}` doesn't look like a valid hostname to me.")
except ClientConnectorError:
raise BadArgument(f"Cannot connect to host with URL `{url}`.")
return url
示例4: proxy_user
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def proxy_user(user_id: str) -> discord.Object:
"""
Create a proxy user object from the given id.
Used when a Member or User object cannot be resolved.
"""
log.trace(f"Attempting to create a proxy user for the user id {user_id}.")
try:
user_id = int(user_id)
except ValueError:
log.debug(f"Failed to create proxy user {user_id}: could not convert to int.")
raise BadArgument(f"User ID `{user_id}` is invalid - could not convert to an integer.")
user = discord.Object(user_id)
user.mention = user.id
user.display_name = f"<@{user.id}>"
user.avatar_url_as = lambda static_format: None
user.bot = False
return user
示例5: retrieve_emoji
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def retrieve_emoji(self) -> typing.Tuple[str, str]:
sent_emoji = self.config["sent_emoji"]
blocked_emoji = self.config["blocked_emoji"]
if sent_emoji != "disable":
try:
sent_emoji = await self.convert_emoji(sent_emoji)
except commands.BadArgument:
logger.warning("Removed sent emoji (%s).", sent_emoji)
sent_emoji = self.config.remove("sent_emoji")
await self.config.update()
if blocked_emoji != "disable":
try:
blocked_emoji = await self.convert_emoji(blocked_emoji)
except commands.BadArgument:
logger.warning("Removed blocked emoji (%s).", blocked_emoji)
blocked_emoji = self.config.remove("blocked_emoji")
await self.config.update()
return sent_emoji, blocked_emoji
示例6: on_command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def on_command_error(ctx, error):
send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError)
if isinstance(error, commands.CommandNotFound): # fails silently
pass
elif isinstance(error, send_help):
_help = await send_cmd_help(ctx)
await ctx.send(embed=_help)
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the permissions to use this command.')
# If any other error occurs, prints to console.
else:
print(''.join(traceback.format_exception(type(error), error, error.__traceback__)))
示例7: convert
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def convert(self, ctx, argument):
message = await commands.converter.MessageConverter().convert(ctx, argument)
if message.channel not in ctx.bot.cogs['Logger'].channels:
raise commands.BadArgument(_('That message is not from a log channel.'))
try:
embed = message.embeds[0]
except IndexError:
raise commands.BadArgument(_('No embeds were found in that message.'))
m = re.match(LINKED_EMOTE, embed.description) or re.match(utils.lexer.t_CUSTOM_EMOTE, embed.description)
try:
return await ctx.bot.cogs['Database'].get_emote(m['name'])
except EmoteNotFoundError:
d = m.groupdict()
d['nsfw'] = 'MOD_NSFW'
d['id'] = int(d['id'])
d['animated'] = d.get('extension') == 'gif' or bool(d.get('animated'))
return DatabaseEmote(d)
# because MultiConverter does not support Union
示例8: command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
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
示例9: convert
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def convert(self, ctx: commands.Context, coordinate: str) -> typing.Tuple[int, int]:
"""Take in a coordinate string and turn it into an (x, y) tuple."""
if not 2 <= len(coordinate) <= 3:
raise commands.BadArgument('Invalid co-ordinate provided')
coordinate = coordinate.lower()
if coordinate[0].isalpha():
digit = coordinate[1:]
letter = coordinate[0]
else:
digit = coordinate[:-1]
letter = coordinate[-1]
if not digit.isdigit():
raise commands.BadArgument
x = ord(letter) - ord('a')
y = int(digit) - 1
if (not 0 <= x <= 9) or (not 0 <= y <= 9):
raise commands.BadArgument
return x, y
示例10: dj
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def dj(self, ctx, *, role):
settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id)
if role.lower() == "none":
settings.djroleId = "NONE"
await SettingsDB.get_instance().set_guild_settings(settings)
await ctx.send(f"{SUCCESS} The DJ role has been cleared, only people with the manage server permission "
f"can use DJ commands now")
else:
try:
role = await commands.RoleConverter().convert(ctx, role)
except commands.BadArgument:
await ctx.send(f"{WARNING} That role was not found!")
return
settings.djroleId = role.id
await SettingsDB.get_instance().set_guild_settings(settings)
await ctx.send(f"{SUCCESS} DJ commands can now only be used by people who have the **{role.name}** role "
f"or the manage server permission")
示例11: tc
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def tc(self, ctx, *, channel):
settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id)
if channel.lower() == "none":
settings.textId = "NONE"
await SettingsDB.get_instance().set_guild_settings(settings)
await ctx.send(f"{SUCCESS} The music text channel has been cleared, people can now use music commands in "
f"all text channels")
else:
try:
channel = await commands.TextChannelConverter().convert(ctx, channel)
except commands.BadArgument:
await ctx.send(f"{WARNING} That channel was not found!")
return
settings.textId = channel.id
await SettingsDB.get_instance().set_guild_settings(settings)
await ctx.send(f"{SUCCESS} Music commands can now only be used in the **{channel.name}** text channel")
示例12: vc
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def vc(self, ctx, *, channel):
settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id)
if channel.lower() == "none":
settings.voiceId = "NONE"
await SettingsDB.get_instance().set_guild_settings(settings)
await ctx.send(f"{SUCCESS} The music voice channel has been cleared, people can now play music in all "
f"channels")
else:
try:
channel = await commands.VoiceChannelConverter().convert(ctx, channel)
except commands.BadArgument:
await ctx.send(f"{WARNING} That channel was not found!")
return
settings.voiceId = channel.id
await SettingsDB.get_instance().set_guild_settings(settings)
await ctx.send(f"{SUCCESS} Music can now only be played in the **{channel.name}** voice channel")
示例13: on_command_error
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def on_command_error(self, ctx, exception):
exc_class = exception.__class__
if exc_class in (commands.CommandNotFound, commands.NotOwner):
return
exc_table = {
commands.MissingRequiredArgument: f"{WARNING} The required arguments are missing for this command!",
commands.NoPrivateMessage: f"{WARNING} This command cannot be used in PM's!",
commands.BadArgument: f"{WARNING} A bad argument was passed, please check if your arguments are correct!",
IllegalAction: f"{WARNING} A node error has occurred: `{getattr(exception, 'msg', None)}`",
CustomCheckFailure: getattr(exception, "msg", None) or "None"
}
if exc_class in exc_table.keys():
await ctx.send(exc_table[exc_class])
else:
await super().on_command_error(ctx, exception)
示例14: test_tag_content_converter_for_invalid
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def test_tag_content_converter_for_invalid(self):
"""TagContentConverter should raise the proper exception for invalid input."""
test_values = (
('', "Tag contents should not be empty, or filled with whitespace."),
(' ', "Tag contents should not be empty, or filled with whitespace."),
)
for value, exception_message in test_values:
with self.subTest(tag_content=value, exception_message=exception_message):
with self.assertRaisesRegex(BadArgument, re.escape(exception_message)):
await TagContentConverter.convert(self.context, value)
示例15: test_valid_python_identifier_for_invalid
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BadArgument [as 别名]
def test_valid_python_identifier_for_invalid(self):
"""ValidPythonIdentifier raises the proper exception for invalid identifiers."""
test_values = ('nested.stuff', '#####')
for name in test_values:
with self.subTest(identifier=name):
exception_message = f'`{name}` is not a valid Python identifier'
with self.assertRaisesRegex(BadArgument, re.escape(exception_message)):
await ValidPythonIdentifier.convert(self.context, name)