Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python 3.x - discord.py get member instance from name#discriminator

I have a string with the name of an user user = 'somename#1111' how can I mention him? (I get the name from google sheets that's why it's a string)

I tried with:

@client.command()
async def mention(ctx):
    user : discord.Member = 'somename#1111'
    await ctx.send(f"{user.mention} hello!")

But it doesn't work

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Although this method is valid, I'd recommend switching to saving user IDs instead of usernames + discriminators, as user IDs are constant, but users are able to change their names and discriminators.

@client.command()
async def mention(ctx):
    user = discord.utils.get(ctx.guild.members, name="somename", discriminator="1111")
    await ctx.send(f"{user.mention} hello!")

And with the ID:

@client.command()
async def mention(ctx):
    user = ctx.guild.get_member(112233445566778899) # replace user ID there
    try:
        await ctx.send(f"{user.mention} hello!")
    except:
        await ctx.send("Sorry, that user has left the server!")

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...