在Discord.py中,要从UserID获取用户对象,你可以使用discord.utils.get()
函数或者guild.get_member()
方法。以下是两种方法的详细说明和示例代码:
discord.utils.get()
discord.utils.get()
函数可以用来从集合中获取具有特定属性的成员。在这种情况下,你可以使用它从服务器的所有成员中获取具有特定UserID的成员。
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True # 确保启用了成员意图
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.command()
async def get_user(ctx, user_id: int):
user = discord.utils.get(ctx.guild.members, id=user_id)
if user:
await ctx.send(f'User found: {user.name}')
else:
await ctx.send('User not found')
bot.run('YOUR_BOT_TOKEN')
guild.get_member()
guild.get_member()
方法可以直接从服务器获取具有特定UserID的成员。
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True # 确保启用了成员意图
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.command()
async def get_user(ctx, user_id: int):
user = ctx.guild.get_member(user_id)
if user:
await ctx.send(f'User found: {user.name}')
else:
await ctx.send('User not found')
bot.run('YOUR_BOT_TOKEN')
members
intent)。这在上面的示例代码中已经展示。通过以上方法,你可以根据UserID获取到相应的Discord用户对象。
领取专属 10元无门槛券
手把手带您无忧上云