Reputation: 254
So I'm trying to make a kick command so that if the reason is nothing, then it says "no reason" instead of none. Don't ask why.
Here's my code:
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member, *, reason: str):
if reason is None:
await user.kick()
await ctx.send(f"**{user}** has been kicked for **no reason**.")
else:
await user.kick(reason=reason)
await ctx.send(f"**{user}** has been kicked for **{reason}**.")
And here's the error:
Ignoring exception in command kick:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 847, in invoke
await self.prepare(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 784, in prepare
await self._parse_arguments(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 699, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 535, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: reason is a required argument that is missing.
I don't understand why it says that "reason is a required argument that is missing" because I said that if reason is None it would say no reason?
Upvotes: 1
Views: 4174
Reputation: 1
it is simple just write:
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, user: discord.Member, *, reason=None):
await user.kick(reason=reason)
await ctx.send(f'{user.mention} has been kicked for {reason}!')
Upvotes: 0
Reputation: 4743
If you assign None
to the reason
, then you can check it. For example reason = None
. After that you can check in the commmand if the reason is None. Here is the code:
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member, *, reason = None):
if not reason:
await user.kick()
await ctx.send(f"**{user}** has been kicked for **no reason**.")
else:
await user.kick(reason=reason)
await ctx.send(f"**{user}** has been kicked for **{reason}**.")
Upvotes: 2
Reputation: 5650
You're getting that error because your function looks like this:
async def kick(ctx, user: discord.Member, *, reason: str):
Reason is not optional here, so it is a required argument
. That means that calling this function without that argument will result in an error. Adding in a default value makes it optional.
def function(requiredArgument, optionalArgument=defaultValue)
In this case, defaultValue
should be None
. Now, when you don't pass in anything for that argument, it's default value will be used. That way, you no longer have to add a reason.
Upvotes: 0