Hey everyone! I’m working on a Discord bot using Python. I want it to randomly slap someone who has the “slapped” role. Most of my code is working, but I’m stuck on how to pick a random person with that role. It would be awesome if I could also make it only choose from people who are online right now.
I’m pretty comfortable with Python, but Discord bots are new to me. Any help would be super appreciated! Here’s a simplified version of what I’ve got so far:
import discord
from discord.ext import commands
import random
bot = commands.Bot(command_prefix='!')
@bot.command()
async def slap(ctx):
role = discord.utils.get(ctx.guild.roles, name="slapped")
# Need help here to pick a random member with the role
await ctx.send(f"{{random_member}} got slapped!")
bot.run('YOUR_TOKEN_HERE')
How can I pick a random member with the “slapped” role? And is there a way to only include online members? Thanks in advance!
I’ve tackled a similar problem in one of my Discord bots. Here’s what worked for me:
First, get all members with the role using role.members. Then, filter for online members with member.status != discord.Status.offline. Finally, use random.choice() to pick one.
Here’s a snippet that should do the trick:
@bot.command()
async def slap(ctx):
role = discord.utils.get(ctx.guild.roles, name="slapped")
online_slappable = [m for m in role.members if m.status != discord.Status.offline]
if online_slappable:
victim = random.choice(online_slappable)
await ctx.send(f"{victim.mention} got slapped!")
else:
await ctx.send("No online members to slap!")
This approach ensures you’re only targeting online members with the specific role. Hope this helps!
yo, i got u fam. try this:
@bot.command()
async def slap(ctx):
slapped = discord.utils.get(ctx.guild.roles, name="slapped")
victims = [m for m in slapped.members if m.status != discord.Status.offline]
if victims:
unlucky_dude = random.choice(victims)
await ctx.send(f"{unlucky_dude.mention} just got slapped! ouch!")
else:
await ctx.send("no victims online. everyone's safe... for now 😈")
Having worked with Discord bots before, I can offer some insight. To select a random user with a specific role, you’ll want to utilize Discord.py’s built-in methods. First, fetch the role using discord.utils.get(), then filter the members list to those with the role and online status. Finally, use random.choice() to select one.
Here’s a code snippet that should work:
@bot.command()
async def slap(ctx):
role = discord.utils.get(ctx.guild.roles, name="slapped")
eligible_members = [m for m in ctx.guild.members if role in m.roles and m.status != discord.Status.offline]
if eligible_members:
victim = random.choice(eligible_members)
await ctx.send(f"{victim.mention} just got slapped!")
else:
await ctx.send("No eligible members to slap right now.")
This approach ensures you’re only targeting online members with the ‘slapped’ role. Remember to handle cases where no eligible members are available to avoid errors.