【问题标题】:get_user(id) cant find user - returns None (self bot discord.py)get_user(id) 找不到用户 - 返回无(self bot discord.py)
【发布时间】:2020-07-21 13:14:10
【问题描述】:

我正在尝试使用自我机器人与自己联系。我正在尝试在我的代码中使用get_user() 函数。

bot = commands.Bot(command_prefix='', self_bot=True)

counter = 0
userID = 695724603406024726

@bot.event
async def dm(userID):
    print('Running Function')
    global counter

    if counter <= 0:
        print('Finding user.')
        counter += 1

        user = bot.get_user(userID)

        print('user:',user)

        await user.send("Hello")
        print('message sent')

    return


bot.loop.create_task(dm(userID))
bot.run(token, bot=False)

相反,我返回此错误:

  File "<ipython-input-1-90e5e962a6e9>", line 24, in dm
    await user.send("Hello")
AttributeError: 'NoneType' object has no attribute 'send'

机器人找不到用户并返回一个None 值。我已经测试了多个 ID,但不确定是什么问题。

【问题讨论】:

  • 它告诉你你的user 对象没有send 方法。您是否确认此方法存在于您从中派生的任何包中?
  • @Chris 用户对象必须是不和谐对象。我正在尝试从 get_user 函数中获取它。它并没有告诉我它没有发送方法,而是告诉我找不到用户因此弹出 NoneType 错误。

标签: python discord.py


【解决方案1】:

你总是可以使用协程client.fetch_user(id) 来完成它。 get_user() 从缓存中获取它,所以当新鲜时,大部分时间都不起作用。

在你的情况下:

bot = commands.Bot(command_prefix='', self_bot=True)

counter = 0
userID = 695724603406024726

async def dm(userID):
    print('Running Function')
    global counter

    if counter <= 0:
        print('Finding user.')
        counter += 1

        user = await bot.fetch_user(userID)

        print('user:',user)

        await user.send("Hello")
        print('message sent')

    return


bot.loop.create_task(dm(userID))
bot.run(token, bot=False)```

【讨论】:

  • 是的,这解决了我的问题!我仍然不确定我的问题是什么(考虑到 OP 的等待解决方案对我不起作用)但这解决了它。
【解决方案2】:

您将任务附加到事件循环并立即运行它,这意味着它会在您的机器人连接并准备好之前尝试运行。

您的机器人在首次连接时所做的其中一件事是构建它所知道的对象的内部缓存,这是 get_user 从中提取的(这就是为什么它是常规函数而不是协程的原因)

所以你只需要给任务添加一个等待,让它一直等到机器人准备好:

async def dm(userID):
    print('Running Function')
    global counter
    await bot.wait_until_ready()
    ...

请注意,我也删除了 bot.event。没有dm 事件,所以装饰器没有做任何事情。

【讨论】:

  • 所以这似乎解决了解决方案,但需要很长时间才能“准备好”。有什么办法可以让它更快?
  • 这取决于你的机器人连接了多少个公会以及它们的大小。 Client 有一些配置你可以尝试,如果你有超过 1000 个公会,你可能想切换到 AutoShardedClient
猜你喜欢
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2022-01-05
相关资源
最近更新 更多