Welcome to OGeek Q&A 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 Reply

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...