[英]Discord.py: How do I get a user from a UserID?
So I need my bot to get a user from a UserID.所以我需要我的机器人从 UserID 中获取用户。 I tried it like this:
我试过这样:
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix = '&')
@client.command(pass_context = True)
async def test(ctx, id : int):
user = client.get_user(id)
print(user)
TOKEN = ""
client.run(TOKEN)
but it always returns None, but why?但它总是返回无,但为什么呢? :C Thanks for helping.
:C 感谢您的帮助。
async def test(id: int):
user = client.get_user(id)
if user is None: # Maybe the user isn't cached?
user = await client.fetch_user(id)
return user
# Inside the loop
user = await test(12312312313)
Also remember to enable intents.members
, here's how还要记得启用
intents.members
,方法如下
Depending on what you're trying to do you're probably missing intents.根据您要执行的操作,您可能缺少意图。
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='&', intents=intents) # renamed bot because you're using an instance of Bot
@bot.command() # pass_context is not necesary since more than few versions back
async def test(ctx, user_id): # renamed id to user_id to make it more readable
user = bot.get_user(user_id)
print(user)
TOKEN = ""
bot.run(TOKEN)
Take into consideration the code above retreives a "user" object not a "member".考虑到上面的代码检索“用户” object 而不是“成员”。 The distinction is important if your leaderboard is related to a specific server.
如果您的排行榜与特定服务器相关,则区别很重要。 Also, the user object doen't have attributes such as "roles", "nickname", etc. If you wish to retreive that information you need to get a member object using
ctx.guild.get_member
instead of bot.get_user
此外,用户 object 没有“角色”、“昵称”等属性。如果您希望检索该信息,您需要使用
ctx.guild.get_member
而不是 bot.get_user 获取成员bot.get_user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.