Error on user.send (But message is sent) and discord_client.get_user(int(ID)) return Null

Viewed 33
import discord
from discord.utils import get

import credentials

discord_client = None

class MyDiscordClient(discord.Client):

    async def on_ready(self):
        print("Logged on as {0}!".format(self.user))

    async def on_message(self, message):
        print("Massage from {0.author}: {0.content}".format(message))
        await message.author.send(message.author.id) #send author.id to author of the message. throw:discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user? BUT is successfully send message.
        user = discord_client.get_user(int(message.author.id)) #get user by message.author.id (same with '1234' and 1234)
        await user.send('sus') #throw: AttributeError: 'NoneType' object has no attribute 'send'?.

def handle_discord():
    print('Start:Discord.')
    global discord_client
    discord_client = MyDiscordClient(intents=discord.Intents.default())
    discord_client.run(credentials.TOKEN)
    print('Complete:Discord.')

def main():
    handle_discord()

main()

Error on user.send but message is being successfully sent to user.

Discord_client.get_user(int(ID)) given 100% valid id (from message.author.id)

(it reproduce on Windows and Termux)

1 Answers

you set discord_client to None. discord_client should be changed to MyDiscordClient() and on_message(message) should be moved out. Also: client.login() is a coroutine and should be awaited. For example:

import discord
from discord.utils import get
import asyncio

import credentials

intents = discord.Intents.default()
intents.message_content=True
class MyDiscordClient(discord.Client):

    async def on_ready(self):
        print("Logged on as {0}!".format(self.user))

discord_client = MyDiscordClient(intents=intents)

@discord_client.event
async def on_message(self, message):
        print("Massage from {0.author}: {0.content}".format(message))
        await message.author.send(message.author.id)
        user = discord_client.get_user(int(message.author.id))
        await user.send('sus')

async def handle_discord():
    print('Start:Discord.')
    await discord_client.run(credentials.TOKEN)
    print('Complete:Discord.')

async def main():
    handle_discord()

asyncio.run(main())
Related