【问题标题】:How do I make mentioning a member optional within a command?如何在命令中提及成员可选?
【发布时间】:2020-11-01 17:24:03
【问题描述】:

我已经创建了一个代码,它发送一个拥抱命令的 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)

提前感谢您的帮助

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 谢谢!如果我完全使用您的代码,我会收到一条错误消息,指出在定义之前引用了 embed。为了解决这个问题,我在 elif & else 语句下添加了“embed = discord.Embed(title = title, ...)”。它工作得很好,但我想知道是否有更有效的方法?
    • 我已经编辑了我的答案,应该更有效率^^
    猜你喜欢
    • 2021-09-05
    • 1970-01-01
    • 2021-07-26
    • 2021-04-29
    • 2021-04-13
    • 2021-03-05
    • 2022-12-05
    • 2021-11-25
    • 2020-12-30
    相关资源
    最近更新 更多