Discord.py | Trying to dm user and getting AttributeError: 'NoneType' object has no attribute 'send'

Discord.py | Trying to dm user and getting AttributeError: 'NoneType' object has no attribute 'send'

我试图在 bot 刚启动时向用户发送 dm,但出现错误。当我打印用户变量时,它显示 None,但如果 id 正确,为什么它是 None?代码取自 discord.py 文档,所以我觉得有点傻 :'d

@bot.event
async def on_ready():
    user = bot.get_user(427406422733619200)
    await user.send('Oh no.. I\'m alive..')

user = bot.get_user(427406422733619200)替换为user = await bot.fetch_user(427406422733619200)

这是可行的,因为 bot.get_user 从缓存中获取用户对象,而该缓存在机器人启动时可能尚未填充。

但是,bot.fetch_user 从 discord 服务器获取用户对象,这也是您需要使用 await 关键字的原因。