【问题标题】:Discord.py: How do I get a user from a UserID?Discord.py:如何从 UserID 获取用户?
【发布时间】:2021-05-08 22:07:56
【问题描述】:

所以我需要我的机器人从 UserID 中获取用户。我试过这样:

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)

但它总是返回 None,但为什么呢? :C 感谢您的帮助。

【问题讨论】:

  • 这能回答你的问题吗? Discord.py get user object from id/tag
  • 不,那篇文章中的任何内容都不适合我。
  • 命令由用户运行,否则使其成为常规函数。
  • 我在帖子中添加了实际代码。

标签: python discord discord.py


【解决方案1】:
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)

还要记得启用intents.membershere's how

【讨论】:

  • 是的,就像我说的我不能使用上下文,因为它不会由用户执行,而且我尝试将其定义为整数,但它不起作用。
  • 没有上下文就无法调用命令。那么你是如何“调用”命令的呢?
  • 我每 10 秒从 task.loop 调用一次。
  • 那么为什么它需要是一个命令呢?不能是正常的协程吗?
  • 成功了,非常感谢您的帮助! c:
【解决方案2】:

根据您要执行的操作,您可能缺少意图。

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)

考虑到上面的代码检索的是“用户”对象而不是“成员”。如果您的排行榜与特定服务器相关,则区别很重要。此外,用户对象没有“角色”、“昵称”等属性。如果您希望检索该信息,您需要使用ctx.guild.get_member 而不是bot.get_user 获取成员对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2021-07-18
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多