Search code examples
pythondiscorddiscord.py

Discord Bot Command to use random mention when a mention is not used. Having Issues


Somewhat new to python and getting nowhere with getting this to work. I get the following error on line 23 when typing the command without a mention:

'NoneType' object has no attribute 'mention'

I don't why it's trying to use this response section as its for when there's a mention, useless I'm missing something.

import discord
from redbot.core import commands
import random

class boop(commands.Cog):
    """My custom cog"""

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def boop(self, ctx, user: discord.User=None):
        """Boop Someone"""
        # Your code will go here
        author_name = ctx.author.mention
        member = random.choice(ctx.guild.members)
        
        randomuser = [f"{author_name} booped {member.mention}",
                     f"{author_name} booped {member.mention} on the nose",
                     f"{author_name} booped {member.mention}'s snoot",
                     f"{author_name} gave {member.mention} a boop"]
                     
        mentionuser = [f"{author_name} booped {user.mention}",
                     f"{author_name} booped {user.mention} on the nose",
                     f"{author_name} booped {user.mention}'s snoot",
                     f"{author_name} gave {user.mention} a boop"]
        if not user:        
          await ctx.send(random.choice(randomuser))
        else:
          await ctx.send(random.choice(mentionuser))


Solution

  • When you run the command without a mention, user becomes None because that is the default value for the parameter that you set in the function definition.

    Then:

    mentionuser = [f"{author_name} booped {user.mention}",
                         f"{author_name} booped {user.mention} on the nose",
                         f"{author_name} booped {user.mention}'s snoot",
                         f"{author_name} gave {user.mention} a boop"]
    

    You're trying to retrieve the mention attribute of a NoneType. That's where the error results from. To avoid this, include the mentionuser definition in the else block:

    ...
    else:
      mentionuser = [f"{author_name} booped {user.mention}",
                           f"{author_name} booped {user.mention} on the nose",
                           f"{author_name} booped {user.mention}'s snoot",
                           f"{author_name} gave {user.mention} a boop"]
      await ctx.send(random.choice(mentionuser))