How to how to convert username to discord ID?

让人想犯罪 __ 提交于 2019-12-11 18:25:52

问题


I have a simple questions about discord. I am trying to create an economy system, and it works well, but I want to customize it a bit. I am using this person's module: https://github.com/Rapptz/discord.py

How do I convert a username to a discord ID. For example if I have a discord "command" to allow people to gift each other money, like: james#0243 types !give 100 bob#9413.

How can I convert bob#9413 to a discord id like 58492482649273613 because in my database, I have people's users stored as their ID rather than their actual username as people can change their username.


回答1:


Use a converter to get the Member object of the target, which will include their id.

from discord import Member
from dicord.ext.commands import Bot

bot = Bot(command_prefix='!')

@bot.command()
async def getids(ctx, member: Member):
    await ctx.send(f"Your id is {ctx.author.id}")
    await ctx.send(f"{member.mention}'s id is {member.id}")

bot.run("token")

Converters are pretty flexible, so you can give names, nicknames, ids, or mentions.




回答2:


on_message callback function is passed the message.

message is a discord.Message instance.
It has author and mentions attributes which could be instances of discord.Member or discord.User depending on whether the message is sent in a private channel.

The discord.Member class subclasses the discord.User and the user id can be accessed there.




回答3:


You could use get_member_named to do something like

@client.command(pass_context = True)
async def name_to_id(ctx, *, name):
  server = ctx.message.server
  user_id = server.get_member_named(name).id

The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result.




回答4:


prefix_choice = "!"
bot = commands.Bot(max_messages=10000, command_prefix=commands.when_mentioned_or(prefix_choice))

@bot.command()
async def membersLog(ctx):
    for i, member in enumerate(ctx.message.server.members):
        list_mem_num = (f'{i}')
        list_mem_id = (f'{member.id}')
        list_mem = (f'{member}')
        list_mem_name = (f'{member.name}')
        list_all = (f'Number: {list_mem_num} ID: {list_mem_id} Name: {list_mem} ({list_mem_name})\n')
        print(list_all)

You can use this to collect all memberinfo of the server where the call comes from. This is the code I use for this.



来源:https://stackoverflow.com/questions/55176129/how-to-how-to-convert-username-to-discord-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!