get_user(id) cant find user - returns None (self bot discord.py)

房东的猫 提交于 2020-12-13 18:31:24

问题


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)

Instead, I am returned with this error:

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

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.


回答1:


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.

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()
    ...

Notice I removed the bot.event too. There is no dm event, so that decorator wasn't doing anything.



来源:https://stackoverflow.com/questions/61112322/get-userid-cant-find-user-returns-none-self-bot-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!