DM a specific user in discord.py

THE PROBLEM WASN’t THE CODE, BUT MY BOT

BOTH THIS POST AND THE FIRST ANSWER WORK TO SEND A DM TO A SPECIFIC PERSON


I’d like to know how to dm a specific person that will always be the same. I’ve tried many StackOverFlow posts and the official discord.py documentation but none of them worked. I have discord.py 1.7.3. So far I’ve got the following:

import discord
from discord.ext import commands

@client.command()
async def dm(ctx):
    user = client.get_user(1234567891011) # <- This user will always be the same.
    await user.send("Hi")

When I type the command in the server the following exception appears:

'''
Ignoring exception in command dm:
Traceback (most recent call last):
  File "C:UsersmyuserAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:UsersmyuserDocumentsPython ScriptsBotmain.py", line 110, in dm    await user.send("Hola")
AttributeError: 'NoneType' object has no attribute 'send'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:UsersmyuserAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandsbot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:UsersmyuserAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:UsersmyuserAppDataLocalProgramsPythonPython39libsite-packagesdiscordextcommandscore.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'

Answer

This implementation allows for any member of the guild to simply type !dm in any channel, and the bot will message the user-specified in client.get_user(<user ID>) a message

import discord
import os
from discord.ext import commands

# Declaration Discord.py Variables
intents = discord.Intents.default()  # Turns on the connection
intents.members = True  # Ensures the member list will be updated properly
client = commands.Bot(command_prefix='!', intents=intents)  # defines the symbol used to call a command from the bot


@client.command()
async def dm(ctx):
    """
    Sends a message to a user every time a member types '!dm' in the channel.
    :param ctx: represents the context in which a command is being invoked under
    :return: a message to the user
    """
    await client.get_user(470163626083352577).send("Enter Text")

client.run("Bot_Token")
  • Here is some more information about how intents work Privileged Intents as you will need Server Member Intent activated.