如何使在命令中提及成员是可选的?

时间:2020-07-12 10:57:18

标签: python bots discord discord.py discord.py-rewrite

我已经创建了一个代码,该代码可以发送命令拥抱的gif并指定要发送给谁,但是,我还想使其成为可选的提及成员。

当前代码为:

@client.command()
async def hug(ctx, member):
    username = ctx.message.author.display_name
    embed = discord.Embed(title = (f'{username} has sent a hug to {member}!'), description = ('warm, fuzzy and comforting <3'), color = 0x83B5E3)
    image = random.choice([(url1), (url2),....(url10)])
    embed.set_image(url=image)
    await ctx.channel.send(embed=embed)

我想更改它,以便如果作者使用命令而提及该成员,则该命令仍然有效,并发送其中一个gif。我必须创建一个if语句吗?

此外,如果可能的话,我该如何更改它,以便像使用作者的显示名一样使用成员的显示名?

我试图做这样的事情,但是不起作用:

@client.command()
async def hug(ctx, member):
    username = ctx.message.author.display_name
    name = member.display_name
    embed = discord.Embed(title = (f'{username} has sent a hug to {name}!'), description = ('warm, fuzzy and comforting <3'), color = 0x83B5E3)
    image = random.choice([(url1), (url2),...(url10)])
    embed.set_image(url=image)
    await ctx.channel.send(embed=embed)

在此先感谢您的帮助

1 个答案:

答案 0 :(得分:1)

默认情况下,您可以将member参数定义为None。如果您在不提及任何人的情况下调用命令,则member的值为None,并且不会触发if member语句。

此外,通过在函数的参数中将member定义为Member对象,您将能够访问提到的成员的信息。

这是您的使用方式:

@client.command()
async def hug(ctx, member: discord.Member = None):
    if member:
        embed = discord.Embed(title=f'{ctx.author} has sent a hug to {member}!',
                              description='warm, fuzzy and comforting <3',
                              color=0x83B5E3)
    else:
        embed = discord.Embed(color=0x83B5E3)
        image = random.choice([(url1), (url2),....(url10)])
        embed.set_image(url=image)

    await ctx.channel.send(embed=embed)