pythondiscord.pydm

Discord.py Send DM to specific User ID


I would just like to send a DM to my friend via python code.

This is my code, but it does not work.

Code:

import discord

client = discord.Client(token="MY_TOKEN")

async def sendDm():
    user = client.get_user("USER_ID")
    await user.send("Hello there!")

Solution

    1. Your bot might now have the user in its cache. Then use fetch_user instead of get_user (fetch requests the Discord API instead of its internal cache):
    async def sendDm():
        user = await client.fetch_user("USER_ID")
        await user.send("Hello there!")
    
    1. You can run it with on_ready event:
    @client.event
    async def on_ready():
        user = await client.fetch_user("USER_ID")
        await user.send("Hello there!")
    

    Copy and paste:

    import discord
    
    client = discord.Client()
    
    @client.event
    async def on_ready():
        user = await client.fetch_user("USER_ID")
        await user.send("Hello there!")
    
    client.run("MY_TOKEN")