discord.py random messages mentioning the user

py recently and I would like the bot to send random messages mentioning the user but it gives me this error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'

Here is the code:

@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))

1 answer

  • answered 2020-07-11 03:15 Ethan M-H

    So it would appear that you have set a default value, therefore you should check if a member has been mentioned before trying to send a message. Here are two different pieces of code that you could use.

    @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))
    

    You can also simply use ctx.send()

    Another thing you could do is have it mention the author if they dont call the command to mention anyone, like so

    @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))
    

    In this situation, both of these will work. !randomroman and !randomroman @user will mention a user.

    Hope this helps!