Redyne
Redyne

Reputation: 27

Get user id from mention using discord.ext in python

When I try to run the command $getUserId @user using the below code, and try to print it, I get the @mention username as a string and not the user's id:

from discord.ext import commands

client = commands.Bot(command_prefix = "$")

@client.command()
async def getUserId(ctx, *arg):
if not arg:
    userId = ctx.author.id
else:
    userId = arg.id
await ctx.send(userId)

I could not find good documentation on finding the id from a given mention without using on_message(message). I have had luck using async def getUserId(ctx, user: Discord.user) and importing discord itself, but this causes an error when I just run $getUserId

How would I go about approaching this having: the mentioned user as a parameter and handling all exceptions when the $getUserId command is given ?

Upvotes: 0

Views: 314

Answers (1)

Pascal
Pascal

Reputation: 70

you can make something like that :

@bot.command()
async def get_userId(ctx, user: discord.User):
    await ctx.send(user.id)
    

for the firt you need mention your user or you can get like this

@bot.command()
async def get_userId(ctx, user:discord.User):
    user_id = user.id
    get_user_id = bot.get_user(user_id)
    await ctx.send(get_user_id)

Upvotes: 1

Related Questions