Home > Back-end >  Checking if selected user is a bot. (discordpy)
Checking if selected user is a bot. (discordpy)

Time:01-14

Okay so im making a giveaway command, and i want to check if selected random user is a bot or nah. How could i exactly do that?

   user = discord.Member
    
   if not user.bot:
      winner = random.choice(ctx.guild.members)
    
      await channel.send(f"Congratulations! {winner.mention} won {prize}!")

Traceback:

Command raised an exception: UnboundLocalError: local variable 'winner' referenced before assignment

CodePudding user response:

You can't call a variable that has not been initialized, user = discord.Member does nothing. You can do it something like this (I did not test this):

winner = random.choice(ctx.guild.members)

# Just do it over if it is a bot
while (winner.bot):
  winner = random.choice(ctx.guild.members)

await channel.send(f"Congratulations! {winner.mention} won {prize}!")

As Lukasz Wiecek suggested in the comments it is also possible to do this below. Just note that the := (walrus-) operator which is used to assign variables while an expression is evaluated is added in Python 3.8

# Just do it over if it is a bot
while (winner := random.choice(ctx.guild.members).bot):
  pass

await channel.send(f"Congratulations! {winner.mention} won {prize}!")

CodePudding user response:

You can filter ctx.guild.members first:

eligible = [member for member in ctx.guild.members if not member.bot]
winner = random.choice(eligible)
await channel.send(f"Congratulations! {winner.mention} won {prize}!")

This completely removes the need for a while loop. Also please note that if all members are bots random.choice will raise an exception. With while the behavior is endless loop.

  •  Tags:  
  • Related