get_user(id)找不到用户-返回None(自身bot discord.py) [英] get_user(id) cant find user - returns None (self bot discord.py)
问题描述
我正在尝试使用自助机器人来管理自己.我正在尝试在代码中使用 get_user()
函数.
I am trying to DM myself using a self bot. I am trying to use the get_user()
function in my code.
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,但不确定是什么问题.
The bot can't find the user and returns a None
value. I have tested multiple ID's and am unsure what the problem is.
推荐答案
您正在将任务附加到事件循环并立即运行,这意味着它会在连接机器人并准备就绪之前尝试运行.
You're attaching your task to the event loop and running it immediately, which means it tries to run before your bot is connected and ready.
您的机器人在首次连接时要做的一件事是建立一个对象知道的内部缓存,这就是 get_user
从中提取的内容(这就是为什么它是常规函数而非协程)
One of the things your bot does when it first connects is build an internal cache of objects it knows about, which is what get_user
draws from (this is why it's a regular function and not a coroutine)
因此,您只需要向任务添加等待,以便等待直到机器人准备就绪:
So you just need to add a wait to the task so that it waits until the bot is ready:
async def dm(userID):
print('Running Function')
global counter
await bot.wait_until_ready()
...
注意,我也删除了 bot.event
.没有 dm
事件,因此装饰器没有做任何事情.
Notice I removed the bot.event
too. There is no dm
event, so that decorator wasn't doing anything.
这篇关于get_user(id)找不到用户-返回None(自身bot discord.py)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!