Python discord.ext.commands.BadArgument() Examples

The following are 30 code examples of discord.ext.commands.BadArgument(). 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: bot.py    From modmail with GNU Affero General Public License v3.0 7 votes vote down vote up
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 
Example #2
Source File: converters.py    From bot with MIT License 6 votes vote down vote up
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 
Example #3
Source File: snakes_cog.py    From seasonalbot with MIT License 6 votes vote down vote up
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 #4
Source File: converters.py    From bot with MIT License 6 votes vote down vote up
def convert(self, ctx: Context, arg: str) -> t.Union[discord.User, discord.Object]:
        """Convert the `arg` to a `discord.User` or `discord.Object`."""
        try:
            return await super().convert(ctx, arg)
        except BadArgument:
            pass

        try:
            user_id = int(arg)
            log.trace(f"Fetching user {user_id}...")
            return await ctx.bot.fetch_user(user_id)
        except ValueError:
            log.debug(f"Failed to fetch user {arg}: could not convert to int.")
            raise BadArgument(f"The provided argument can't be turned into integer: `{arg}`")
        except discord.HTTPException as e:
            # If the Discord error isn't `Unknown user`, return a proxy instead
            if e.code != 10013:
                log.info(f"Failed to fetch user, returning a proxy instead: status {e.status}")
                return proxy_user(arg)

            log.debug(f"Failed to fetch user {arg}: user does not exist.")
            raise BadArgument(f"User `{arg}` does not exist") 
Example #5
Source File: minesweeper.py    From seasonalbot with MIT License 6 votes vote down vote up
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 
Example #6
Source File: converters.py    From bot with MIT License 6 votes vote down vote up
def convert(self, ctx: Context, argument: str) -> t.Optional[int]:
        """
        Convert `argument` to a duration that's max 15 minutes or None.

        If `"forever"` is passed, None is returned; otherwise an int of the extracted time.
        Accepted formats are:
        * <duration>,
        * <duration>m,
        * <duration>M,
        * forever.
        """
        if argument == "forever":
            return None
        match = self.MINUTES_RE.match(argument)
        if not match:
            raise BadArgument(f"{argument} is not a valid minutes duration.")

        duration = int(match.group(1))
        if duration > 15:
            raise BadArgument("Duration must be at most 15 minutes.")
        return duration 
Example #7
Source File: settings.py    From rewrite with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #8
Source File: settings.py    From rewrite with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #9
Source File: converters.py    From bot with MIT License 6 votes vote down vote up
def convert(ctx: Context, tag_name: str) -> str:
        """Lowercase & strip whitespace from proposed tag_name & ensure it's valid."""
        tag_name = tag_name.lower().strip()

        # The tag name has at least one invalid character.
        if ascii(tag_name)[1:-1] != tag_name:
            raise BadArgument("Don't be ridiculous, you can't use that character!")

        # The tag name is either empty, or consists of nothing but whitespace.
        elif not tag_name:
            raise BadArgument("Tag names should not be empty, or filled with whitespace.")

        # The tag name is longer than 127 characters.
        elif len(tag_name) > 127:
            raise BadArgument("Are you insane? That's way too long!")

        # The tag name is ascii but does not contain any letters.
        elif not any(character.isalpha() for character in tag_name):
            raise BadArgument("Tag names must contain at least one letter.")

        return tag_name 
Example #10
Source File: converters.py    From bot with MIT License 6 votes vote down vote up
def convert(ctx: Context, sub: str) -> str:
        """
        Force sub to begin with "r/" and check if it's a valid subreddit.

        If sub is a valid subreddit, return it prepended with "r/"
        """
        sub = sub.lower()

        if not sub.startswith("r/"):
            sub = f"r/{sub}"

        resp = await ctx.bot.http_session.get(
            "https://www.reddit.com/subreddits/search.json",
            params={"q": sub}
        )

        json = await resp.json()
        if not json["data"]["children"]:
            raise BadArgument(
                f"The subreddit `{sub}` either doesn't exist, or it has no posts."
            )

        return sub 
Example #11
Source File: settings.py    From rewrite with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #12
Source File: converters.py    From bot with MIT License 6 votes vote down vote up
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 
Example #13
Source File: bot.py    From rewrite with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #14
Source File: converter.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #15
Source File: converter.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #16
Source File: bot.py    From RemixBot with MIT License 6 votes vote down vote up
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__))) 
Example #17
Source File: converter.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def convert(self, ctx, argument) -> discord.Role:
        argument = argument.replace("\"", "")
        guild = ctx.guild
        if not guild:
            raise commands.NoPrivateMessage()

        match = self._get_id_match(argument) or re.match(r'<@&([0-9]+)>$', argument)
        if match:
            result = guild.get_role(int(match.group(1)))
        else:
            result = discord.utils.find(lambda r: r.name.lower() == argument.lower(), guild.roles)
        if result is None:
            raise commands.BadArgument('Role "{}" not found.'.format(argument))
        return result 
Example #18
Source File: converter.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def Snowflake(argument: str):
	try:
		id = int(argument)
	except ValueError:
		raise commands.BadArgument(_('Not a valid integer.'))

	if id < utils.SMALLEST_SNOWFLAKE:
		raise commands.BadArgument(_('Not a valid message ID.'))

	return id 
Example #19
Source File: converter.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def _search_for_message(target, predicate):
	message = await target.history().find(predicate)
	if message is None:
		raise commands.BadArgument(_('Message not found.'))
	return message 
Example #20
Source File: converter.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def convert_offset(context, channel, offset):
	try:
		offset = int(offset, base=0) - 1  # skip the invoking message
	except ValueError:
		raise commands.BadArgument(_('Not a valid integer.'))

	if offset == 0:
		# not sure why this should be allowed, but i see no reason to disallow it either.
		return message
	if offset < 0:
		return await utils.get_message_by_offset(channel, offset)

	raise commands.BadArgument(_('Not a message offset.')) 
Example #21
Source File: converter.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def convert(self, ctx, argument):
        try:
            return await commands.TextChannelConverter().convert(ctx, argument)
        except commands.BadArgument:
            return await InsensitiveMember().convert(ctx, argument) 
Example #22
Source File: space.py    From seasonalbot with MIT License 5 votes vote down vote up
def convert(self, ctx: Context, argument: str) -> Union[int, datetime]:
        """Parse date (SOL or earth) into `datetime` or `int`. When invalid value, raise error."""
        if argument.isdigit():
            return int(argument)
        try:
            date = datetime.strptime(argument, "%Y-%m-%d")
        except ValueError:
            raise BadArgument(f"Can't convert `{argument}` to `datetime` in format `YYYY-MM-DD` or `int` in SOL.")
        return date 
Example #23
Source File: board.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def index(self, pos):
		col, row = pos
		row = int(row)
		if col == 'N' and row == 3:
			raise commands.BadArgument(_('Position may not be the free space.'))
		col, row = self.cls.COL_I[col], row - 1
		i = self.cls.HEIGHT * col + row
		return i 
Example #24
Source File: board.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def parse_pos(cls, pos):
		col, row = pos
		try:
			col, row = cls.COL_I[col], int(row) - 1
		except (KeyError, IndexError):
			raise commands.BadArgument(_('Invalid position.'))
		return col, row 
Example #25
Source File: misc.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_message_by_offset(channel, index: int) -> discord.Message:
	"""Gets channel[-index]. For instance get_message(channel, -2) == second to last message.
	Requires channel history permissions
	"""
	try:
		return (await channel.history(limit=abs(index)).flatten())[-1]
	except (discord.NoMoreItems, IndexError):
		raise commands.BadArgument(_('Message not found.')) 
Example #26
Source File: vote.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, ctx, argument):
        try:
            dt = datetime.strptime(argument, "%H:%M")
            d = ctx.message.created_at
            dt = dt.replace(year=d.year, month=d.month, day=d.day)
            return dt
        except ValueError:
            raise BadArgument() 
Example #27
Source File: vote.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def convert(self, ctx, argument):
        try:
            dt = datetime.strptime(argument, "%d.%m.")
            dt = dt.replace(year=ctx.message.created_at.year)
            return dt
        except ValueError:
            raise BadArgument() 
Example #28
Source File: meme.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def hug_error(self, ctx, error):
        if isinstance(error, commands.BadArgument):
            await ctx.send(utils.fill_message("member_not_found", user=ctx.author.id)) 
Example #29
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def leaderboard_error(self, ctx, error):
        if isinstance(error, commands.BadArgument):
            await ctx.send(utils.fill_message("karma_lederboard_offser_error", user=ctx.author.id)) 
Example #30
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def message(self, ctx, *args):
        try:
            converter = commands.MessageConverter()
            target_message = await converter.convert(ctx=ctx, argument=' '.join(args))
        except commands.errors.BadArgument:
            await ctx.send(utils.fill_message("karma_message_format", user=ctx.author.id))
            return
        await self.karma.message_karma(ctx, target_message)