例如,我有这样的代码(在一个齿轮):
@commands.command()
async def send_message(self, ctx, user : discord.Member = None,*, text = None)
if user and text:
await ctx.send(user.mention + text)
elif not user and text:
await ctx.send(text)
此代码应该发送消息并在提到用户时提到用户,但是,如果消息的第一个参数中没有成员对象,则只显示一个错误,而不将text设置为消息中的所有其他单词。如果没有正确的对象类型,是否有一种方法可以完全忽略user参数?
使用isinstance()
来测试参数的类型
if text:
if isinstance(user, discord.Member):
await ctx.send(user.mention + text)
else:
await ctx.send(text)
如上所述,isinstance是检查对象类型的正确方法。但是,如果您知道子类,也可以使用type。
if text is not None:
if type(user) is discord.Member:
await ctx.send(user.mention + text)
else:
await ctx.send(text)