Home > Back-end >  Get Python Discord Bot to DM Hardcoded recipient the Name of the person that joined
Get Python Discord Bot to DM Hardcoded recipient the Name of the person that joined

Time:10-05

I have done some research and I know to use on_member_join() to know when a user joins the server. But I am having a hard time finding out how to get the username of that user and send a message to my personal account with that username. The reason for this is because my discord server is fairly small, and I get new users every day, only I want to get notified of this that way I can personally talk to them when they join.

CodePudding user response:

You can easily get the Member object by referencing it in the function definition. Link to the Discord.py reference of the on_member_join event. After that you can just use something like the fetch_user("your personal ID") method and send to your dm the member.user.

Example Code:

    import discord
    # Starting the client with all Intents so you can use the on_member_join() event.
    Client = discord.Client(intents=discord.Intents.all())

    @Client.event
    def on_member_join(member):
      your_user = Client.fetch_user("your id")
      your_dm = await your_user.dm_channel
      # Verify if there is already a DM, otherwise create the channel
      if not your_dm:
        your_dm = await your_user.create_dm()
      await your_dm.send(member.user)

CodePudding user response:

You may need to enable the members intents by putting the following code as your bot definition:

intents = discord.Intents.default()
intents.members = True

# If you're using discord.Client():
client = discord.Client(intents=intents)
# If you're using commands.Bot():
client = commands.Bot(options_here,intents=intents)

After this, you can send a DM to a user object like a channel and use member.user to get the new member's name:

def on_member_join(member):
    dmUser = await client.fetch_user(579450993167564811)
    await dmUser.send(member.user) # Sends member's name to dmUser via DM
  • Related