I want to make a command that makes my bot send a message to the mentioned person, but this one line of code keeps returning NoneType. how do i fix this?
user = client.get_user('user id')
get_
methods only work when the thing you're getting is already in the cache; you need to use fetch_user
. As you mentioned it's a command, you should already be within an async
function.
user = await client.fetch_user(USER_ID)
try:
await user.send(content="A direct message")
except discord.Forbidden:
# don't have permissions to dm the user
# they might have turned dms off from non-friends
# either pass/continue/return whatever is appropriate
You could also use get_user
in tandem with fetch_user
.
user = client.get_user(USER_ID)
if not user:
user = await client.fetch_user(USER_ID)
fetch_user
makes an API call so if you're doing this regularly then you might have the user in the cache from an earlier fetch
. We can use get
first to try and limit the API calls (and also make the command process slightly quicker).