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

Viewed 7295

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.

2 Answers

You could always use the coroutine client.fetch_user(id) to get it done. get_user() takes it from cache so when fresh, doesn't work most of the times.

In your case:

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)```

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.

Related