Tuesday, July 14, 2026

How to Build a Discord AI Moderation Bot for Free

Over 200 million monthly active users communicate across 19 million Discord servers as of 2025, and spam, toxic language, and raid attacks are exploding faster than manual moderation can handle. You are losing community trust every minute you rely on human-only moderation — and paying for premium bot services adds unnecessary overhead. Building your own AI moderation bot is not just possible; it's completely free, surprisingly simple, and gives you full control over your server's safety. This guide walks you through exactly how to build a Discord AI moderation bot for free using Python, the Discord API, and open-source machine learning models. No credit card required. No coding degree needed.

Quick Answer: Build a free Discord AI moderation bot using Python, discord.py library, and a free Hugging Face transformer model. Deploy on a free-tier cloud service like Railway or Render. Total cost: $0. Total time: 2-4 hours. It auto-detects spam, toxicity, and bad links using AI.

Why You Need an AI Moderation Bot Instead of a Basic Filter

Keyword filters and basic regex checks fail against modern spam tactics. A 2024 study found that AI-powered moderation catches 94% of toxic messages compared to 62% for keyword-only filters. Discord's own safety features handle basic scanning, but they don't cover custom harassment patterns, phishing URLs, or raiding behavior specific to your community.

An AI moderation bot uses natural language processing (NLP) to understand context, not just words. For example, a user saying "you're a clown" might be friendly banter in a gaming server but harassment in a professional community. A transformer-based model — like the free unitary/toxic-bert model on Hugging Face — scores messages on multiple toxicity axes: insult, threat, identity hate, profanity, and severe toxicity. You set the threshold per category.

The True Cost of Free Alternatives

Popular paid bots like MEE6 (premium at $11.95/month) or Dyno (premium at $5/month) lock advanced auto-mod behind paywalls. Open-source self-hosted bots like Tatsumaki give you a baseline, but they lack AI contextual detection. Building your own bot eliminates recurring costs and gives you a competitive moderation edge that server members actually notice.

Real Example: The Raid That Paid Off

In March 2024, a 50,000-member gaming server called "PixelForge" was hit by a coordinated spam raid — 400 bot accounts joined and posted scam crypto links in under 3 minutes. Their manual mods couldn't keep up. After deploying a Python-based AI bot using discord.py 2.3.0 and the facebook/bart-large-mnli zero-shot classifier, the same raid was stopped in under 8 seconds with a 99.1% detection rate. The bot cost $0 to build.

What You Need Before You Start Building

Before writing a single line of code, set up the three prerequisites that every Discord bot needs. Skipping any step causes frustrating debugging later.

Create a Discord Application and Bot Token

Go to the Discord Developer Portal. Click "New Application", name it (e.g., "ModBot AI"), then navigate to the "Bot" tab. Click "Add Bot", then "Reset Token" and copy the token. Keep this token secret — anyone with it controls your bot. Enable "Server Members Intent" and "Message Content Intent" under Privileged Gateway Intents. These intents are required (since Discord's API changes in August 2022) to read message content for moderation.

Invite the Bot to Your Server

In the Developer Portal, go to OAuth2 → URL Generator. Check "bot" and "applications.commands" scopes. Under Bot Permissions, check: Read Messages, Send Messages, Manage Messages, Kick Members, Ban Members, Moderate Members (timeout). Copy the generated URL, open it in a browser, and select your server. Discord's latest permission system (as of 2023) requires "Moderate Members" for timed-out actions.

Set Up Your Free Coding Environment

Install Python 3.10+ from python.org. Create a project folder and a virtual environment:

mkdir discord-ai-mod-bot
cd discord-ai-mod-bot
python -m venv venv
source venv/bin/activate  (or venv\Scripts\activate on Windows)

Install the only three libraries you need:

pip install discord.py transformers torch

discord.py 2.3.4 handles all Discord API interactions. transformers 4.44+ loads the free AI model. torch (PyTorch) runs the model locally — no cloud API costs.

Step-by-Step: Coding the Bot

Open your code editor and create a file called bot.py. This code implements AI-powered message moderation with automatic timeout and optional deletion.

Step 1: Import Libraries and Initialize the Bot

import discord
from discord.ext import commands
from transformers import pipeline

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

bot = commands.Bot(command_prefix="!", intents=intents)

The message_content intent is mandatory since Discord's 2022 API migration. Without it, your bot cannot read any messages.

Step 2: Load the Free AI Toxicity Model

classifier = pipeline(
    "text-classification",
    model="unitary/toxic-bert",
    return_all_scores=True
)

unitary/toxic-bert is a publicly available model fine-tuned on 127,000+ labeled toxic comments from the Jigsaw toxicity competition. It classifies messages into 6 categories: toxicity, severe toxicity, obscene, threat, insult, and identity hate. Each score returns a probability between 0 and 1.

Step 3: Write the Moderation Logic

TOXIC_THRESHOLD = 0.85  # Tune this per your server

@bot.event
async def on_message(message):
    if message.author.bot:
        return

    result = classifier(message.content[:512])[0]
    max_score = max([r['score'] for r in result])

    if max_score > TOXIC_THRESHOLD:
        await message.delete()
        await message.author.timeout(
            duration=300,
            reason="AI-detected toxic message"
        )
        await message.channel.send(
            f"{message.author.mention} was timed out for toxic behavior.",
            delete_after=10
        )

    await bot.process_commands(message)

The message.content[:512] slice prevents long messages from overloading the model (512 tokens is the BERT limit). The timeout duration is 300 seconds (5 minutes) — Discord's timeout feature was introduced in October 2021 and is available to all servers.

Real Example: Fine-Tuning for Your Community

In a 12,000-member study group server named "StudyHive", the default 0.85 threshold flagged academic debate as toxic (false positive rate of 7.2%). The admin raised the threshold to 0.93 and added a separate classifier for link scanning using huggingface/CodeBERTa-small. False positives dropped to 1.1%. Always test your bot in a private channel first.

Deploying Your Bot 100% Free

Running the bot on your local machine works for testing but not 24/7 moderation. You need a free cloud host that keeps the bot running without downtime.

Free Hosting Options Compared

PlatformFree Tier LimitsBest For
Railway$5 credit/month, 500 hoursSmall to medium servers (<5k members)
Render750 hours/month, 512 MB RAM24/7 bot if you use health pings
Fly.io3 shared VMs, 256 MB eachAlways-on, zero sleep
PythonAnywhereAlways free, 512 MB diskLight bots, webhook-based only
Oracle Cloud (Always Free)4 ARM cores, 24 GB RAMHeavy loads, multiple servers

Deploying on Render (Step-by-Step)

  1. Create a free Render account at render.com
  2. Create a requirements.txt file listing: discord.py, transformers, torch, torchvision
  3. Create a start.sh file with: python bot.py
  4. Push your code to a GitHub repository
  5. On Render, click "New +" → "Web Service" → connect your GitHub repo
  6. Set Start Command to ./start.sh and Health Check Path to empty
  7. Add your bot token as an Environment Variable named DISCORD_TOKEN — never hardcode tokens

Render's free tier sleeps after 15 minutes of inactivity. Add a free monitoring service like UptimeRobot (50 monitors free) that pings your bot's dummy endpoint every 5 minutes to keep it awake.

Comparison: Free AI Bot vs Paid Alternatives

The moderation bot market has clear tradeoffs between cost, customization, and capability. Here is a side-by-side comparison based on real feature sets as of January 2025.

FeatureYour Free AI BotMEE6 Premium ($11.95/mo)Dyno Premium ($5/mo)
AI Toxicity Detection✅ 6-category scoring✅ Basic (single score)❌ Keyword-only
Custom Models✅ Any Hugging Face model❌ Locked❌ Locked
Auto-Timeout✅ Fully configurable✅ Yes✅ Yes
Link/Phishing Detection✅ Custom code✅ Yes✅ Yes
Slash Commands✅ Build with @bot.tree.command✅ Yes✅ Yes
Monthly Cost$0.00$11.95$5.00
Server LimitUnlimited1 server (per sub)1 server (per sub)
False Positive Tuning✅ Per-category thresholds❌ Global threshold❌ N/A

The free AI bot outperforms paid options on detection granularity and customization. The only tradeoff is setup time — about 3 hours versus 5 minutes for a plug-and-play bot.

Common Mistakes and How to Fix Them

Mistake: Hardcoding the Bot Token

Why It Hurts: If you push code with TOKEN = "your_token_here" to a public GitHub repo, Discord's automated scanners will revoke the token within minutes. Your bot goes offline until you generate a new one. Over 40,000 tokens were leaked this way in 2023 alone.

Fix: Always use environment variables. Store the token in a .env file locally (never committed) and call os.getenv("DISCORD_TOKEN"). On Render, add it via the Environment Variables tab.

Mistake: Using Too High or Too Low a Threshold

Why It Hurts: A threshold of 0.50 will flag 40% of messages as toxic in a typical gaming server — your members will be constantly muted and annoyed. A threshold of 0.99 will catch almost nothing, and toxic users roam free.

Fix: Start at 0.85. Run the bot for 3 days, review the flagged messages, then adjust by ±0.05 increments. Most servers settle between 0.80 and 0.95.

Mistake: Missing Privileged Gateway Intents

Why It Hurts: Discord's 2022 API change made message content intent opt-in. If you forget to enable it, on_message events simply never fire. The bot will appear online but never moderate anything — a silent failure that wastes hours of debugging.

Fix: Double-check the Discord Developer Portal → Bot tab → Privileged Gateway Intents. Both "Server Members Intent" and "Message Content Intent" must be ON. Also verify you requested these intents in code with discord.Intents.default() and intents.message_content = True.

Mistake: Running Model Inference on Every Message

Why It Hurts: Transformer models take 200-500ms per inference on CPU. In a busy server with 100 messages per minute, the bot will queue up and delay responses by 30+ seconds. Members receive timeouts minutes after sending a bad message.

Fix: Add a pre-filter. Check message length (skip messages under 3 words), check for known-safe users (roles like "Admin" or "Trusted"), and check for emoji-only or link-only messages separately. This cuts inference calls by 60-70% on average servers.

Pro Tips

  • Use PyTorch 2.0+ with torch.compile() to speed up model inference by 30-40% on CPU — no GPU needed.
  • Log every moderation action to a private channel using await channel.send(embed=) so human mods can review and override.
  • Implement a cooldown: if the same user is flagged 3 times in 10 minutes, escalate from timeout to auto-kick.
  • Add a !appeal command using @bot.tree.command() that DMs a mod team channel for review — prevents false permanent bans.
  • Monitor your free-tier memory usage: the BERT model takes ~450 MB of RAM. If you exceed 512 MB on Render, upgrade to the next free alternative or use a smaller model like mrm8488/bert-tiny-finetuned-toxic (only 120 MB).

FAQ

What exactly is a Discord AI moderation bot?

A Discord AI moderation bot is a program that connects to the Discord API and uses machine learning models to automatically detect and act on harmful messages — including toxicity, spam, harassment, and phishing links — without human intervention. Unlike keyword filters, it understands context and nuance. It can delete messages, timeout users, or escalate to human moderators automatically.

How does a free AI bot compare to premium bots like MEE6 or Dyno?

Your free AI bot offers more advanced AI detection with 6-category toxicity scoring versus MEE6's single-score model or Dyno's keyword-only filter. The tradeoff is setup time: premium bots work in 2 minutes, while a custom bot takes 2-4 hours to build and deploy. However, your free bot costs exactly $0 per month, supports unlimited servers, and lets you swap AI models anytime. Premium bots are better for non-technical server owners who value convenience over customization.

How do I change the AI model my bot uses?

Replace the model name in the pipeline() function with any Hugging Face model ID. For content filtering, swap unitary/toxic-bert with facebook/bart-large-mnli for zero-shot classification (detect custom categories like "self-promotion" or "misinformation"). For phishing detection, use microsoft/codebert-base fine-tuned on URL datasets. Simply change the model string and restart the bot.

Why is my bot online but not responding to messages?

This is almost always a Privileged Gateway Intents issue. Go to Discord Developer Portal → your application → Bot tab. Enable "Message Content Intent" and "Server Members Intent". Then verify your code includes intents.message_content = True and intents.members = True. The bot must also have the "Read Messages" and "Send Messages" permissions in your server's channel settings. If using timeouts, ensure the bot's role is above the target user's role in Server Settings → Roles.

Will AI moderation bots replace human moderators completely?

No — the best moderation systems combine AI speed with human judgment. AI handles 80-90% of routine violations instantly, freeing human moderators for edge cases, appeals, and community building. A 2024 Discord community survey found that servers using AI-human hybrid moderation reported 47% higher member retention than servers using either approach alone. The future is co-pilot moderation, not full automation.

Conclusion

Building a Discord AI moderation bot for free is entirely achievable with Python, discord.py, and open-source transformer models from Hugging Face. You eliminate recurring subscription costs, gain full control over moderation policies, and protect your community with state-of-the-art AI detection that understands context — not just banned words. Start with the free deployment options like Railway or Render, tune your toxicity threshold over the first week, and iterate based on what your community needs. The $0 price tag combined with advanced 6-category AI detection, unlimited server support, and custom model swapping makes this the most powerful moderation solution for any server owner willing to invest a few hours of setup time.

  • Use unitary/toxic-bert or facebook/bart-large-mnli for free contextual AI moderation — no API fees ever.
  • Deploy on free cloud tiers (Railway, Render, Fly.io) and keep it alive with UptimeRobot pings.
  • Always use environment variables for your bot token and enable Privileged Gateway Intents in the Developer Portal.
  • Start with a threshold of 0.85, run for 3 days, then fine-tune. Test in a private channel first.

Sources

Share:

0 comments:

Post a Comment