@bot.command()
async def id(ctx, a:str): #a = @user
how would I get the ID of a user mentioned in the command, and output it as:
await ctx.send(id)
@bot.command()
async def id(ctx, a:str): #a = @user
how would I get the ID of a user mentioned in the command, and output it as:
await ctx.send(id)
Use a converter to get the User
object:
@bot.command(name="id")
async def id_(ctx, user: discord.User):
await ctx.send(user.id)
Or to get the id
of the author:
@bot.command(name="id")
async def id_(ctx):
await ctx.send(ctx.author.id)
Just realized that when you @someone and store it to the variable "a", it contains the user ID in the form of '<@userid>'. So a bit of clean up can get me the user ID
Here's the code:
@bot.command()
async def id(ctx, a:str):
a = a.replace("<","")
a = a.replace(">","")
a = a.replace("@","")
await ctx.send(a)
Since my command consists of "rev id @someone", the @someone gets stored in 'a' as the string '<@userid>' instead of '@someone'.
If you want to handle a mention within your function, you can get the mention from the context instead of passing the mention as a string argument.
@bot.command()
async def id(ctx):
# Loop through the list of mentioned users and print the id of each.
print(*(user_mentioned.id for user_mentioned in ctx.message.mentions), sep='\n')
ctx.message.mentions
will return:
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead.
When you loop through ctx.message.mentions
, each item is a mentioned member with attributes such as id, name, discriminator. Here's another example of looping through the mentioned list to handle each member who was mentioned:
for user_mentioned in ctx.message.mentions:
# Now we can use the .id attribute.
print(f"{user_mentioned}'s ID is {user_mentioned.id}")
It's up to you whether you want to require the argument a
as shown in the question above. If you do need this, note that the string will sometimes include an exclamation in the mention depending on whether it is:
<@1234567890>
<@!1234567890>
Which is why I prefer to get the id from a member/user attribute.