Reputation: 55
I recently started working with Discord.py. My question is: How can I tag a random user, for example if you write !tag in the chat? I haven't found an answer yet.
if message.content.startswith('+best'):
userid = '<@ # A RANDOM ID #>'
yield from client.send_message(message.channel, ' : %s is the best ' % userid)
Thank´s
Upvotes: 1
Views: 8085
Reputation: 1812
First of all, I suggest you install discord.py-rewrite
, as it is more advanced.
Then, I suggest you create bot commands using the @client.command()
decorator, like this:
@client.command()
async def testcommand(ctx):
pass
Now that you have done both things, there are several ways to do it. For example, if you don't want the bot to mention the command invoker or other bots, you can write:
from random import choice
from discord.ext import commands
@client.command()
@commands.guild_only()
async def tag(ctx):
try:
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members if not member.bot and member!=ctx.author)))
except IndexError:
await ctx.send("You are the only human member on it!")
If you don't want the bot to mention other bots, but it can mention the command invoker, use:
from random import choice
from discord.ext import commands
@client.command()
@commands.guild_only()
async def tag(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members if not member.bot)))
If you want the bot to mention any guild member, human or bot, use:
from random import choice
from discord.ext import commands
@client.command()
@commands.guild_only()
async def tag(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members)))
Upvotes: 0
Reputation: 1
I was playing around a bit and got this to work, you can try it.
@client.command(pass_context=True)
async def hug(ctx):
user = choice(ctx.message.channel.guild.members)
await ctx.send(f'{ctx.message.author.mention} hugged {user.mention}')
Upvotes: 0
Reputation: 131
Elaborating on aeshthetic's answer, you can do something like this:
import random
if message.content.startswith('+best'):
channel = message.channel
randomMember = random.choice(channel.guild.members)
await channel.send(f'{randomMember.mention} is the best')
Please note that the code is in the rewrite version of discord.py and not the async version - if you're using the async version, I'd recommend you migrate to rewrite as support for the async version of discord.py has ceased. To learn more about that, refer to the migrating documentation found here.
Let me know if you need help - happy coding!
Upvotes: 1
Reputation: 36
Here's how I'd do it:
random.choice
to select a random user from the listHere's the implementation:
from random import choice
if message.content.startswith('+best'):
user = choice(message.channel.guild.members)
yield from client.send_message(message.channel, ' : %s is the best ' % user.mention)
Upvotes: 2