Get User Id From Mention In Discord.py
When I try to run the command $getUserId @user using the below code, it works as intended but gives an error when something like $getUserId 123 is sent when trying to pass the para
Solution 1:
Idk if it was a mistake in the question or the code but your indents are messed up and arg doesn't exist
defconvert_mention_to_id(mention):
returnint(mention[1:][:len(mention)-2].replace("@","").replace("!",""))
@client.command(name="getUserId")asyncdefgetUserId(ctx ,*arg):
ifnot arg:
await ctx.send(ctx.author.id)
else:
try:
await ctx.send({i:convert_mention_to_id(arg[i]) for i in arg})
except ValueError:
await ctx.send("Invalid ID")
convert_mention_to_id is a utility function, mentions are passed in <@!id>
format the function simply gets id from it.
The ID is used in the discord API as int so it is converted in the function which raises value error when invalid id is passed
And you can get the mentioned user with client.get_user() but it needs the member intents to be true
Solution 2:
There are a few things wrong with your code.
- Using arg: You do not define
arg
anywhere in the code you provided. Instead, replace arg with user. - if not user: If you were to leave user blank, you would have raised an error such as "user is a required argument that is missing." One way to combat this would be to default it to
None
.
You can review the above observations in the code below, as well as the tested example.
@client.command()asyncdefgetUserId(ctx, user: discord.User=None): # defaults user to None if nothing is passedifnot user: # you are not using an arg variable, you're using user
userId = ctx.author.idelse:
userId = user.id# same as previousawait ctx.send(userId)
Post a Comment for "Get User Id From Mention In Discord.py"