脚踢命令(discord.py)

时间:2020-09-29 15:29:32

标签: python discord discord.py

因此,我正在尝试执行kick命令,以便如果原因不成立,那么它说的是“没有理由”而不是没有理由。不要问为什么。

这是我的代码:

@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}**.")

这是错误:

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.

我不明白为什么它说“原因是缺少的必要论点”,因为我说如果原因为“无”,那就说没有理由?

2 个答案:

答案 0 :(得分:0)

如果将None分配给reason,则可以进行检查。例如reason = None。之后,您可以检查命令是否为。这是代码:

@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}**.")

答案 1 :(得分:0)

您收到该错误,因为您的函数如下所示:

async def kick(ctx, user: discord.Member, *, reason: str):

原因在这里不是可选的,因此它是required argument。这意味着在没有该参数的情况下调用此函数将导致错误。添加默认值使其成为可选。

def function(requiredArgument, optionalArgument=defaultValue)

在这种情况下,defaultValue应该是None。现在,当您不传递任何参数时,将使用默认值。这样,您就不再不必添加原因。

相关问题