繁体   English   中英

有没有办法从存储的 user_id 中获取 user_id 的用户名,即使它们不在同一台服务器上?

[英]Is there a way to get a username from a user_id from stored user_id's even if they aren't on the same server?

我想知道是否可以从 discord 上的全局用户 ID 获取用户名。

在 Cog 中,如果搜索是本地的,我目前正在使用下面的行来检索信息。 self.ctx.guild.get_member

但我希望扩展到全球搜索,但我什至不确定是否有可能我也在想如果我无法获得用户名,我想更改 NULL 返回我进入类似“外部用户”

我正在使用此行进行搜索并遍历列表(本地版本)

table = ("\n".join(f'{idx + 1}. {self.ctx.guild.get_member(entry[0])} (XP: {entry[1]} | Level: {entry[2]} \n' for idx, entry in enumerate(entries)))

您可以使用user = self.get_user(USERID)获取 discord 上的任何用户,并使用user.name获取他们的用户名。 查看https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user以了解有关get_user的更多信息。

仅当您缓存了用户时,另一个答案才有效。 这不能保证,并且在较大的机器人中几乎可以保证不会,除非您启用了成员意图。

您可以使用bot.fetch_user ,无论您的缓存如何,它都会为您提供用户 object。 首先检查.get_user 仍然是一个好主意。

我的代码中经常有这样的 function :

def get_or_fetch_user(bot, user_id):
    user = bot.get_user(user_id)
    if not user:  # the user isn't in the cache, or it doesn't exist
        try:
            user = await bot.fetch_user(user_id)
        except discord.NotFound:  # fetch_user raises an error if the user doesn't exist
            user = None
    return user

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM