Aaron
Aaron

Reputation: 237

Discord.py Bot - How to mention random user

I'm making a Discord Bot in Python, and currently I want to add a feature, when a bot mention random user with the command _best

I tried this code:

if message.content.startswith('_best'):
    Channel = message.channel
    randomMember = random.choice(Channel.members)
    await message.channel.send(f'{randomMember.mention} is the best')

But the bot mention himself all over the time! Any ideas?

Upvotes: 2

Views: 1182

Answers (2)

Ghost Ops
Ghost Ops

Reputation: 1734

Try random.choice(message.guild.members) instead of random.choice(Channel.members) to get the list of members in the server

Because getting a random member from a text channel is same as from the entire server

And then try message.channel.send(f'{randomMember.mention} is the best')

And also, the bot will mention only itself unless you enable the Privileged Gateway Intents for your bot by going to https://discord.com/developers/applications/{your_bot's_client_id_goes_here}/bot and enable Server Members Intent to make your bot get access to server members list

And also use @bot.command instead of tons of if-else statements for each command inside on_message

Code:

import discord
from discord.ext.commands import Bot

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot('_', intents=intents)

@bot.command()
async def best(ctx):
    randomMember = random.choice(ctx.guild.members)
    await ctx.send(f'{randomMember.mention} is the best')

If still the above code doesn't work for you...

Change this

@bot.event
async def on_message(message):
    # do all your stuff here

into this

@bot.listen('on_message')
async def whatever_you_want_to_call_it(message):
    # do stuff here
    # do not process commands here

And if you still want to use the on_message with if statements, then use this code

@bot.event
async def on_message(message):
    randomMember = random.choice(message.guild.members)
    await message.channel.send(f'{randomMember.mention} is the best')

Tell me if its not working for you...

Upvotes: 1

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

Intents


You have to include the intents, like this:

intents = discord.Intents.all()
Bot = discord.commands.Bot(intents=intents)

You must have enabled the intents from Discord developer portal.

Members


It's better to use this code:

member = random.choice(message.guild.members)

since it includes all the users of the guild.

Command


Why don't you use a discord.Command? Like this:

@Bot.command()
async def best(ctx):
    member = random.choice(ctx.guild.members)
    ctx.send(member.mention)

Upvotes: 1

Related Questions