首页 > 解决方案 > 提及用户的 discord.py 随机消息

问题描述

py 最近,我希望机器人发送提及用户的随机消息,但它给了我这个错误:

discord.ext.commands.errors.CommandInvokeError:命令引发异常:AttributeError:“NoneType”对象没有属性“提及”

这是代码:

@client.command()
async def randomroman(ctx, *,member: discord.Member=None):

    mention = member.mention
    variable=[
        f'{mention} ama tanto roman!',
        f'{mention} odia tanto roman!',
        f'{mention} ama roman!',
        f'{mention} odia roman!'
    ]
    await ctx.message.channel.send(random.choice(variable))

标签: discord.py

解决方案


所以看起来你已经设置了一个默认值,因此你应该在尝试发送消息之前检查是否提到了一个成员。这是您可以使用的两段不同的代码。

@client.command()
async def randomroman(ctx, member: discord.Member=None):
    if not member:
        # We dont have anyone to mention so tell the user
        await ctx.send("You need to mention someone for me to mention!")
        return

    variable=[
        f'{member.mention} ama tanto roman!',
        f'{member.mention} odia tanto roman!',
        f'{member.mention} ama roman!',
        f'{member.mention} odia roman!'
    ]
    await ctx.send(random.choice(variable))

您也可以简单地使用ctx.send()

您可以做的另一件事是,如果他们不调用命令提及任何人,则让它提及作者,就像这样

@client.command()
async def randomroman(ctx, member: discord.Member=None):
    member = member or ctx.author

    variable=[
        f'{member.mention} ama tanto roman!',
        f'{member.mention} odia tanto roman!',
        f'{member.mention} ama roman!',
        f'{member.mention} odia roman!'
    ]
    await ctx.send(random.choice(variable))

在这种情况下,这两种方法都会起作用。!randomroman!randomroman @user会提到一个用户。

希望这可以帮助!


推荐阅读