[英]Kick Command (discord.py)
所以我试图发出一个踢命令,这样如果原因是什么,那么它会说“没有理由”而不是“没有理由”。 不要问为什么。
这是我的代码:
@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.
我不明白为什么它说“原因是缺少的必需参数”,因为我说如果原因是 None 它会说没有原因?
如果您将None
分配给reason
,那么您可以检查它。 例如reason = None
。 之后,如果原因是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}**.")
您收到该错误是因为您的函数如下所示:
async def kick(ctx, user: discord.Member, *, reason: str):
Reason 在这里不是可选的,因此它是required argument
。 这意味着在没有该参数的情况下调用此函数将导致错误。 添加默认值使其成为可选的。
def function(requiredArgument, optionalArgument=defaultValue)
在这种情况下, defaultValue
应该是None
。 现在,当您不为该参数传递任何内容时,将使用它的默认值。 这样,您不再需要添加原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.