How to Build Discord Verification Bot With Email or Phone Step
🔍 WiseChecker

How to Build Discord Verification Bot With Email or Phone Step

You want to add an email or phone verification step to your Discord server so that new members must verify their identity before gaining full access. Without this step, bots and spammers can join and cause problems. A verification bot can send a one-time code to a user’s email or phone and only grant roles after the code is entered. This article explains how to build a Discord verification bot using Python that requires an email or phone verification step.

Key Takeaways: Building a Discord Verification Bot with Email or Phone

  • discord.py library: The Python library that lets your bot interact with Discord servers and events.
  • SMTP server or Twilio API: The external service that sends the verification email or SMS code to the user.
  • Server Settings > Roles > Manage Permissions: The Discord server area where you configure the unverified role and the verified role.

ADVERTISEMENT

What the Verification Bot Does and What You Need Before Building It

A verification bot automates the process of confirming a new member’s identity using an email address or phone number. When a user joins, the bot sends a unique code to the provided contact method. The user then types the code in a Discord channel, and the bot grants a verified role that unlocks the rest of the server.

Before you start coding, you need the following prerequisites:

  • A Discord account and a server where you have administrator permissions.
  • A Discord application and bot token created from the Discord Developer Portal.
  • Python 3.8 or higher installed on your computer or hosting server.
  • The discord.py library installed via pip.
  • For email verification: access to an SMTP server (Gmail, Outlook, or a custom email service).
  • For phone verification: a Twilio account with SMS capabilities and a verified sender phone number.

How the Verification Flow Works

The bot listens for new members joining the server. When a member joins, the bot sends a private message asking for their email or phone number. The user replies with the contact info. The bot generates a random 6-digit code and sends it to that contact method via email or SMS. The user then types the code in the private channel. If the code matches, the bot assigns a verified role and removes the unverified role.

Steps to Build the Verification Bot

Follow these steps to create a working verification bot. The example uses email verification, but you can adapt it for SMS by replacing the email sending function with Twilio’s API.

  1. Create a Discord Application and Bot
    Go to the Discord Developer Portal at discord.com/developers/applications. Click “New Application” and give it a name. In the left menu, click “Bot”, then “Add Bot”. Copy the bot token. Under the “OAuth2” > “URL Generator”, select the “bot” scope and the “Send Messages”, “Manage Roles”, and “Read Message History” permissions. Use the generated URL to invite the bot to your server.
  2. Set Up the Python Environment
    Open a terminal and run pip install discord.py to install the library. If you plan to send emails, install smtplib (built-in) or yagmail for easier Gmail integration. For SMS, install twilio with pip install twilio.
  3. Write the Bot Code
    Create a new Python file named verification_bot.py. Start with the basic bot structure:
    import discord
    from discord.ext import commands
    import smtplib
    import random
    import string
    
    intents = discord.Intents.default()
    intents.members = True
    bot = commands.Bot(command_prefix='!', intents=intents)
    
    @bot.event
    async def on_ready():
        print(f'Logged in as {bot.user}')
    
    bot.run('YOUR_BOT_TOKEN')

    Replace YOUR_BOT_TOKEN with the token from the Developer Portal.

  4. Add the Verification Command
    Add a command that starts the verification process. For example, !verify email or !verify phone. The bot will ask for the contact info in a DM. Use this code:
    @bot.command()
    async def verify(ctx, method: str):
        if method.lower() not in ['email', 'phone']:
            await ctx.send('Please specify email or phone.')
            return
        await ctx.author.send(f'Please enter your {method} address:')
        def check(m):
            return m.author == ctx.author and isinstance(m.channel, discord.DMChannel)
        msg = await bot.wait_for('message', check=check)
        contact = msg.content
        # Generate a 6-digit code
        code = ''.join(random.choices(string.digits, k=6))
        # Store code in a dictionary (use database in production)
        verification_codes[ctx.author.id] = code
        # Send the code
        if method.lower() == 'email':
            send_email(contact, code)
        else:
            send_sms(contact, code)
        await ctx.author.send('A verification code has been sent. Please reply with the code.')
        msg_code = await bot.wait_for('message', check=check)
        if msg_code.content == code:
            role = discord.utils.get(ctx.guild.roles, name='Verified')
            await ctx.author.add_roles(role)
            await ctx.author.send('Verification successful!')
        else:
            await ctx.author.send('Incorrect code. Please try again.')
  5. Implement the Email Sending Function
    Add a function that sends an email using SMTP. For Gmail, you need an app password. Example:
    def send_email(to_email, code):
        from_email = 'your_email@gmail.com'
        password = 'your_app_password'
        subject = 'Your Discord Verification Code'
        body = f'Your verification code is: {code}'
        message = f'Subject: {subject}\n\n{body}'
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(from_email, password)
        server.sendmail(from_email, to_email, message)
        server.quit()
  6. Implement the SMS Sending Function (Optional)
    If you use Twilio, add this function:
    from twilio.rest import Client
    
    def send_sms(to_phone, code):
        account_sid = 'your_account_sid'
        auth_token = 'your_auth_token'
        client = Client(account_sid, auth_token)
        message = client.messages.create(
            body=f'Your Discord verification code is: {code}',
            from_='+1234567890',
            to=to_phone
        )
  7. Configure Server Roles
    In your Discord server, create two roles: “Unverified” and “Verified”. Set the “Unverified” role to have no permissions to see channels except a single verification channel. Set the “Verified” role to have access to all channels. Ensure the bot has the “Manage Roles” permission and its role is above both roles in the role hierarchy.
  8. Run the Bot
    Save the file and run it with python verification_bot.py. The bot should come online. Test by having a new member use the !verify email command.

ADVERTISEMENT

Common Mistakes and Limitations

Bot Cannot Send Direct Messages to New Members

Discord may block DMs from bots if the user has privacy settings set to allow only friends to DM them. To work around this, use a dedicated verification channel where users can type commands instead of relying on DMs.

Email or SMS Delivery Fails

Email may land in spam or SMS may be blocked by carriers. Always test with a real email or phone number. For email, use a service like SendGrid for better deliverability. For SMS, ensure your Twilio number is verified and has sufficient credits.

Code Expiration and Security

The example stores codes in a Python dictionary, which resets when the bot restarts. In production, use a database like SQLite or Redis. Add a code expiration timer (e.g., 5 minutes) to prevent reuse. Never log or expose the verification codes.

Item Email Verification Phone (SMS) Verification
Cost Free with SMTP (Gmail has limits) Paid per SMS via Twilio
Delivery Speed Seconds to minutes Usually within seconds
User Privacy Email may be shared with third parties Phone number is more sensitive
Setup Complexity Requires SMTP credentials Requires Twilio account

You now have a working Discord verification bot that can verify users via email or phone. Next, consider adding a database to store verification codes persistently and implementing rate limiting to prevent abuse. For advanced protection, integrate a CAPTCHA step before the code is sent to reduce bot registrations further.

ADVERTISEMENT