🚀 Executive Summary

TL;DR: Manually welcoming new Discord members is inefficient and lacks consistency. This guide provides a step-by-step solution to automate personalized welcome DMs using a Python bot built with discord.py, ensuring every new member receives a warm greeting upon joining.

🎯 Key Takeaways

  • Crucially enable the SERVER MEMBERS INTENT in the Discord Developer Portal for your bot to receive on_member_join events.
  • Utilize python-dotenv and a config.env file to securely manage your DISCORD_TOKEN, preventing hardcoding and enhancing security.
  • Implement discord.Intents.members = True in your Python script and wrap member.send() in a try/except block to gracefully handle users with DMs disabled.

Automate Welcoming New Discord Members with DM

Automate Welcoming New Discord Members with DM

Hey there, Darian Vance here. I’m a Senior DevOps Engineer at TechResolve. A few years back, I was helping manage a fairly large community Discord server. I found myself spending a couple of hours every week just manually checking the audit logs and sending welcome DMs to new members. It was a nice personal touch, but it just didn’t scale. Automating this single task not only gave me that time back but also ensured every single new member got a warm, consistent welcome the moment they joined. It’s a small change with a huge impact on community engagement.

Today, I’m going to walk you through how to build a simple, reliable Python bot to do exactly that. Let’s get this off your plate for good.

Prerequisites

Before we dive in, make sure you have the following ready:

  • A Discord account with administrator permissions on a server you can use for testing.
  • Python 3.8 or newer installed on your machine.
  • A basic understanding of Python and how to run scripts.

The Guide: Step-by-Step

Step 1: Create the Bot in the Discord Developer Portal

First, we need to register our application with Discord. This is where we get the credentials our script will use to authenticate.

  1. Navigate to the Discord Developer Portal and log in.
  2. Click the “New Application” button. Give it a memorable name, like “WelcomeBot”.
  3. Once created, navigate to the “Bot” tab on the left-hand menu. Click “Add Bot” and confirm.
  4. This is the most critical part: Scroll down to the “Privileged Gateway Intents” section. You MUST enable the SERVER MEMBERS INTENT. Without this, your bot will not be notified when a new user joins the server.
  5. Under the bot’s username, click “Reset Token” to reveal its authentication token. Copy this immediately and store it somewhere safe. Never share this token or commit it to a public repository. We’ll be putting it in a configuration file shortly.

Step 2: Configure Permissions and Invite the Bot

Now we generate an invite link to add the bot to our server with the correct, minimal permissions.

  1. In the Developer Portal, go to “OAuth2” and then “URL Generator”.
  2. Under “Scopes”, check the box for bot.
  3. A new “Bot Permissions” panel will appear below. For this task, the only permission we need is Send Messages. It’s always best practice to grant only the permissions a bot absolutely needs.
  4. Copy the generated URL at the bottom of the page. Paste it into your browser, select your server from the dropdown, and authorize it. You should see a message in your server that the bot has joined.

Step 3: Setting Up the Python Project

Alright, let’s get into the code. I’ll skip the standard project directory and virtual environment setup since you’ve likely got your own workflow for that. The key is to make sure you install the necessary libraries. In your terminal, you’ll need to run the pip command to install discord.py for the bot logic and python-dotenv to handle our credentials securely from a config file. This prevents us from hardcoding that secret token into our script.

In your project folder, create two files:

  • config.env – This will store our secret token.
  • welcome_bot.py – This will contain our Python logic.

Inside your config.env file, add the following line, pasting the bot token you copied earlier:

DISCORD_TOKEN="YourBotTokenGoesHere"

Step 4: Writing the Bot Logic

Now for the fun part. Open welcome_bot.py and add the following code. I’ll break down what each part does right below it.

import discord
import os
from dotenv import load_dotenv

# Load environment variables from config.env
load_dotenv(dotenv_path='config.env')
TOKEN = os.getenv('DISCORD_TOKEN')

# We need to declare the members intent to receive member join events
intents = discord.Intents.default()
intents.members = True

# Create a client instance with our intents
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    """This event triggers when the bot has successfully connected to Discord."""
    print(f'{client.user} has connected to Discord!')
    print('Ready to welcome new members.')

@client.event
async def on_member_join(member):
    """This event triggers whenever a new member joins the server."""
    print(f'{member.name} has joined the server.')
    
    # The welcome message we want to send
    welcome_message = (
        f"Hey {member.name}, welcome to our server!\n\n"
        "We're thrilled to have you here. To get started, please check out our #rules "
        "and feel free to introduce yourself in the #introductions channel.\n\n"
        "If you have any questions, don't hesitate to ask!"
    )
    
    try:
        # Attempt to send a direct message to the new member
        await member.send(welcome_message)
        print(f"Successfully sent a welcome DM to {member.name}.")
    except discord.errors.Forbidden:
        # This happens if the user has DMs disabled from server members
        print(f"Could not send DM to {member.name}. They may have DMs disabled.")
    except Exception as e:
        # Catch any other potential errors
        print(f"An unexpected error occurred while sending a DM to {member.name}: {e}")

# Run the bot with our token
if TOKEN is None:
    print("Error: DISCORD_TOKEN not found. Make sure it's set in your config.env file.")
else:
    client.run(TOKEN)

Code Breakdown:

  • Imports and Configuration: We import the necessary libraries. load_dotenv reads our config.env file, and os.getenv securely loads the DISCORD_TOKEN into our script.
  • Intents: This is crucial. We create a default set of `intents` and then explicitly enable intents.members = True. This is our subscription to member-related events like someone joining.
  • `on_ready` event: This is a simple function decorated with @client.event. It runs once the bot is online and connected. In my production setups, I use this for health checks and startup logging. Here, it just gives us a confirmation in the console.
  • `on_member_join` event: This is the core of our automation. The decorator tells `discord.py` to run this function whenever a new `member` object is detected joining the server.
  • The Message and `try/except` Block: We craft a friendly, multi-line welcome message. Critically, we wrap the `member.send()` call in a `try/except` block. Users can disable DMs from server members, which would otherwise crash our script. This graceful handling ensures the bot stays online even if it can’t message someone.
  • `client.run(TOKEN)`: This is the final line that starts the bot’s event loop, connecting it to Discord’s servers using your token.

Pro Tip: In a real-world scenario, I’d move the `welcome_message` content into a separate configuration file or even a database. This allows you to update the message without having to restart the bot service. You could also add placeholders for the server name (e.g., `member.guild.name`) to make the bot more reusable across different servers.

Common Pitfalls (Where I Usually Mess Up)

Even with a simple script, a few things can go wrong. Here are the top two issues I see:

  1. The Server Members Intent is Disabled: This is the #1 problem. If you forget to toggle this on in the Discord Developer Portal, the on_member_join event will never fire, and your bot will do nothing when people join. The bot will appear online, but it won’t be subscribed to the event.
  2. Incorrect Token or `config.env` Setup: A typo in the token or misplacing the config.env file will prevent the bot from logging in at all. The script will usually exit with an error telling you the token is missing, so check your console output when you run it.

Conclusion

And that’s it. You now have a fully automated, reliable bot that provides a consistent and welcoming onboarding experience for every new member of your community. This is a foundational DevOps principle: identify a repetitive, manual task and automate it to improve efficiency and consistency. From here, you can expand its functionality to assign roles, post a public welcome message, or whatever else you can think of.

Happy building!

– Darian Vance

Darian Vance - Lead Cloud Architect

Darian Vance

Lead Cloud Architect & DevOps Strategist

With over 12 years in system architecture and automation, Darian specializes in simplifying complex cloud infrastructures. An advocate for open-source solutions, he founded TechResolve to provide engineers with actionable, battle-tested troubleshooting guides and robust software alternatives.


🤖 Frequently Asked Questions

âť“ How do I automate sending welcome DMs to new Discord members?

Automate welcome DMs by creating a Python bot using discord.py. Register the bot in the Discord Developer Portal, enable the SERVER MEMBERS INTENT, grant ‘Send Messages’ permission, and implement an on_member_join event handler to send personalized direct messages.

âť“ How does this automated Discord welcome bot compare to manual welcomes or Discord’s built-in features?

This automated bot provides consistent, instant, and personalized welcome DMs, unlike manual welcomes which are time-consuming and inconsistent. It offers a more direct and personal touch than Discord’s built-in server welcome messages, which are typically public channel announcements.

âť“ What are the most common issues when setting up a Discord welcome bot?

The two most common issues are failing to enable the SERVER MEMBERS INTENT in the Discord Developer Portal, which prevents the bot from detecting new members, and incorrect DISCORD_TOKEN or config.env setup, leading to login failures.

Leave a Reply

Discover more from TechResolve - SaaS Troubleshooting & Software Alternatives

Subscribe now to keep reading and get access to the full archive.

Continue reading