python-3.xdiscord.pydm

How to send a DM to new members of a discord server using a discord bot (python 3)


I have tried using a few ways all of which did not cause any error messages (or if they did they were easy to fix) but they still did not send the DM.

the way that I'm most confident of is:

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!'
    )

There could be multiple issues with this but for the moment I'm stuck on the second line; it doesn't actually activate if a user joins my server (I tested this by just shoving a print command straight after it and watching the output as I joined the server on an alt). Any ideas would be appreciated. :)

oh yeah I tried another way that might work but I couldn't get to: how to make discord bot send a new user DM?


Solution

  • This is a little old, but when I ran into this issue it was because I was working from older examples that did not include the need for intents.

    While the below is very blanket and likely overkill(I am just in local dev atm), this fixed the issue:

    # bot.py
    import os
    
    import discord
    from dotenv import load_dotenv
    
    intents = discord.Intents.default()
    intents.members = True
    intents.presences = True
    intents.messages = True
    
    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN')
    
    client = discord.Client(intents=intents)
    
    @client.event
    async def on_ready():
        print(
            f'{client.user.name} has connected to discord!'
        )
    
    @client.event
    async def on_member_join(member):
        await member.send(f'Hi {member.name}, welcome to discord!')
    
    client.run(TOKEN)