Discord Moderation Bot Source Code in Python

Every message that reaches your bot forces a decision, and the hard part is not deleting a bad message — it is leaving a good one alone. This guide is discord moderation bot source code you can run today: a discord.py on_message handler with a maintainable blocklist, an honest look at where word lists break, and how to screen every message with an HTTP moderation API once a list stops being enough.
What a moderation bot actually has to decide
For every message the bot has five possible moves: allow, delete, warn, time out the author, or escalate to a human moderator. One string of text, five outcomes, and the choice has to be made before any person reads the message.
The decision happens before any human sees the message
- It runs inside your event handler. A check in
on_messageshares the asyncio event loop that keeps your bot connected, answers slash commands and handles every other gateway event. Anything blocking there stalls the whole client. - It has to be fast. Whatever latency your filter adds is time the message spends unmoderated. A filter that takes two seconds per message is a filter your moderators will ask you to turn off.
- False positives hurt more than a missed edge case. A wrongly deleted message is visible to the whole channel, and the author will complain loudly. A missed edge case usually passes unnoticed. When in doubt, tune toward precision.
- Text arrives messy. Casing tricks, zero-width characters inserted between letters, leetspeak, homoglyphs, repeated characters, emoji separators and several languages in one server all defeat literal matching.
- Moderators need a paper trail. A delete with no log entry gives a human nothing to review, appeal or learn from.
The rest of this article builds a baseline that handles the easy cases well, then replaces the matching step with a classifier that can read context.
A working baseline: blocklist screening in a discord.py bot
A blocklist is the fastest thing to ship: one file of terms, one regex, one delete call. It is also a good way to learn the shape of the problem, so let's build it properly and keep the word list in a config file that moderators can edit without touching your code.
Step 1: Listen for message events
Start with the smallest possible bot. The handler returns early for bot authors so the bot never moderates itself or other bots, and it calls process_commands at the end so manual moderation commands still work.
# bot.py
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True # also enable the message content intent in your app settings
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author.bot:
return # ignore other bots and our own messages
# screening goes here
await bot.process_commands(message) # keeps !commands working
if __name__ == "__main__":
bot.run("YOUR_BOT_TOKEN")Step 2: Normalize the text before you match
Attackers do not type words the way your list spells them. Normalizing first means one entry in the list catches many spellings. casefold beats lower for non-English text, NFKC folds full-width and compatibility forms, and dropping zero-width and combining characters defeats the cheapest evasion tricks.
import re
import unicodedata
ZERO_WIDTH = dict.fromkeys(map(ord, "\u200b\u200c\u200d\u2060\ufeff"), None)
REPEATS = re.compile(r"(.)\1{2,}")
def normalize(text: str) -> str:
"""Fold a message down to a comparable form."""
text = unicodedata.normalize("NFKC", text) # full-width and compatibility forms
text = text.translate(ZERO_WIDTH) # drop zero-width characters
text = "".join(
ch for ch in text if unicodedata.category(ch) != "Mn"
) # drop combining accents and marks
text = text.casefold() # case-insensitive comparison
text = REPEATS.sub(r"\1\1", text) # "loooool" -> "lool"
return textCollapsing repeats also means you only need one entry for a stretched spelling. Keep the collapse conservative — squash runs of three or more down to two, so ordinary words are not mangled.
Step 3: Match whole words, not substrings
Plain "ass" in text is how you end up deleting a message about a class assignment in Scunthorpe. Word boundaries fix that: \bass\b only matches the standalone word. Build the pattern once at startup rather than per message, and sort the terms longest-first so the most specific one wins.
import re
from pathlib import Path
BLOCKED_FILE = Path("blocked_words.txt")
def load_blocklist(path: Path) -> set[str]:
"""One term per line; blank lines and # comments are ignored."""
return {
normalize(line.strip())
for line in path.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.startswith("#")
}
def build_pattern(words: set[str]) -> re.Pattern[str]:
escaped = sorted((re.escape(w) for w in words), key=len, reverse=True)
return re.compile(r"\b(?:" + "|".join(escaped) + r")\b")
BLOCKLIST_PATTERN = build_pattern(load_blocklist(BLOCKED_FILE))The config file itself stays tiny and readable, and moderators can extend it during an incident:
# blocked_words.txt
# one term per line, case does not matter
term-one
term-twoStep 4: Act, log, and tell the author
Now assemble the file. On a match the bot deletes the message, tells the author why, and writes an entry to a moderator channel that includes the message id, the author and the matched term. The same log_action helper serves your manual moderation commands, so automated screening and human action share one workflow.
# bot.py — full baseline
import re
import unicodedata
from datetime import timedelta
from pathlib import Path
import discord
from discord.ext import commands
TOKEN = "YOUR_BOT_TOKEN"
MOD_LOG_CHANNEL_ID = 123456789012345678 # your moderator channel
BLOCKED_FILE = Path("blocked_words.txt")
ZERO_WIDTH = dict.fromkeys(map(ord, "\u200b\u200c\u200d\u2060\ufeff"), None)
REPEATS = re.compile(r"(.)\1{2,}")
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
def normalize(text: str) -> str:
text = unicodedata.normalize("NFKC", text)
text = text.translate(ZERO_WIDTH)
text = "".join(ch for ch in text if unicodedata.category(ch) != "Mn")
return REPEATS.sub(r"\1\1", text.casefold())
def load_blocklist(path: Path) -> set[str]:
return {
normalize(line.strip())
for line in path.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.startswith("#")
}
def build_pattern(words: set[str]) -> re.Pattern[str]:
escaped = sorted((re.escape(w) for w in words), key=len, reverse=True)
return re.compile(r"\b(?:" + "|".join(escaped) + r")\b")
BLOCKLIST_PATTERN = build_pattern(load_blocklist(BLOCKED_FILE))
async def log_action(
message: discord.Message,
action: str,
detail: str,
include_content: bool = True,
) -> None:
channel = bot.get_channel(MOD_LOG_CHANNEL_ID)
if channel is None:
return
line = (
f"**{action}** in {message.channel.mention} | "
f"{message.author} ({message.author.id}) | msg {message.id} | {detail}"
)
if include_content:
line += f"\n> {message.content[:500]}"
await channel.send(line)
@bot.event
async def on_message(message: discord.Message) -> None:
if not message.author.bot and message.guild is not None:
match = BLOCKLIST_PATTERN.search(normalize(message.content))
if match:
try:
await message.delete()
except discord.Forbidden:
pass # the bot is missing Manage Messages in this channel
await message.channel.send(
f"{message.author.mention}, that message was removed. Keep the channel civil.",
delete_after=10,
)
await log_action(message, "delete+warn", f"matched {match.group(0)!r}")
await bot.process_commands(message)
@bot.command()
@commands.has_permissions(moderate_members=True)
async def timeout(
ctx: commands.Context,
member: discord.Member,
minutes: int = 10,
*,
reason: str = "no reason given",
) -> None:
await member.timeout(timedelta(minutes=minutes), reason=reason)
await ctx.reply(f"{member.mention} timed out for {minutes} minutes.")
await log_action(ctx.message, "timeout", f"{member} ({member.id}) | {reason}")
@bot.command()
@commands.has_permissions(manage_messages=True)
async def warn(ctx: commands.Context, member: discord.Member, *, reason: str) -> None:
await ctx.reply(f"{member.mention} has been warned: {reason}")
await log_action(ctx.message, "warn", f"{member} ({member.id}) | {reason}")
if __name__ == "__main__":
bot.run(TOKEN)That is a complete, working discord moderation bot code baseline. It is also, after a few weeks in a busy server, the thing you will start fighting.
Where the blocklist breaks down
A word list answers one question — "does this string contain a term I already know?" — and almost every interesting moderation problem is a different question.
- Context and intent. Sarcasm, quoted speech, jokes between friends and reclaimed language all read as a match to a regex and as something else entirely to a human. A member quoting a slur to condemn it gets deleted alongside the person who used it as an insult.
- Evasion. Coded spellings, homoglyphs, spacing tricks and slang that appears this week and spreads next week all arrive faster than you can add entries. You are always writing the regex for last month's evasion.
- Multilingual servers. The same idea is spelled differently in every language your members speak, and words that are innocuous in one language are slurs in another.
- Harm with no profanity at all. Scams, spam floods, doxxing and politely worded harassment aimed at one person contain no blocked term by design. If you have ever read a thread of polite, targeted cruelty, you know the blocklist will allow every word of it.
- No category information. You get a boolean. Spam, harassment, personal data and self-harm all look identical to the filter, so you cannot route them to different actions. Everything has to be handled with the same hammer.
- Maintenance cost. Every evasion becomes another regex, another regression test, and another chance to break the innocent word that happens to contain it. If you want a longer treatment of false positives, false negatives and list maintenance, see filtering profanity with a Python blocklist.
The pattern is familiar: you are not really maintaining a word list, you are maintaining a decoder ring for a moving target.
The general fix: classify each message over HTTP
The alternative is to stop matching and start classifying. Instead of asking "does this text contain a known bad word?", you send the message text to a moderation service and ask "what kinds of harm does this text contain?" The service returns categories, and your job moves from pattern writing to policy writing.
What to send and what to expect back
Most moderation endpoints follow the same shape:
- Send a
POSTwith a JSON body containing the message text, and authenticate with a key in a header. - Receive a JSON object with category results. Some services return booleans, others return numeric scores you have to threshold yourself. Know which one you are adopting before you write policy code around it.
- Map each category to an action in a small table you keep in your own code — delete for spam, timeout for harassment, hold for review, and so on.
- Log the category alongside the message id so moderators can audit decisions later.
The call has to be asynchronous. requests blocks the event loop and will make your bot feel dead under load; use aiohttp or httpx with an asyncio-friendly client, and reuse one session for the life of the bot instead of opening a connection pool per message.
import asyncio
import os
import aiohttp
MODERATION_ENDPOINT = "https://your-moderation-service.example/v1/check"
MODERATION_KEY = os.environ["MODERATION_API_KEY"]
async def classify(session: aiohttp.ClientSession, text: str) -> dict | None:
"""Return the service's JSON payload, or None when the check fails."""
try:
async with session.post(
MODERATION_ENDPOINT,
headers={"Authorization": f"Bearer {MODERATION_KEY}"},
json={"text": text},
timeout=aiohttp.ClientTimeout(total=3),
) as response:
response.raise_for_status()
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
return NoneAlways give the call a timeout, and always decide in advance what None means for your bot. "Fail open and log" keeps the conversation moving; "hold for review" is stricter but will stall messages when the network is unhappy. Pick one and write it down, because you will be asked about it after the first outage.
How to compare moderation tools
There is no single best option, only the best fit for your server's rules, volume and data constraints. The broad families are hand-maintained blocklists (what we built above), hosted moderation APIs, and self-hosted models you run on your own hardware. When you evaluate any of them, check these things against the vendor's current documentation rather than a comparison table you found in a search result:
- Category coverage. Does it separate spam from harassment from personal data, or does it return one generic "bad" flag? Category granularity is what lets you route actions instead of deleting everything.
- Language coverage. Which languages are supported, and does your server actually speak them?
- Latency. What round-trip time can you expect, and how does it behave under your peak traffic? Measure it with your own messages.
- Deployment model. Hosted, self-hosted, or both. If message text cannot leave your network, a hosted API is a non-starter no matter how good the categories are.
- Data handling. Read what the vendor says about whether text is stored, for how long and for what purpose. This is the question your trust and safety lead will ask first.
- Result shape. Booleans you map to policy, or scores you have to threshold and tune? Scores give you more control and more ways to be wrong.
- Integration details. Batch endpoints, webhooks, rate limits and error behaviour — all of these change, so confirm them in the documentation before you architect around them.
If you want a fuller Python request-and-response walkthrough of a hosted moderation call before wiring one into a bot, adding a content moderation API to a Python backend covers the mechanics in more detail.
How CautionLabs does the same job
CautionLabs is a content moderation API with the same shape as the pattern above, and its results are deliberately simple to wire into a bot.
The call
Send a POST request to https://api.cautionlabs.com/moderation with your Cloud API key as a Bearer token and a JSON body of {"text": "..."}. The response contains a categories object with twelve boolean fields — toxic, profanity, hate, harassment, self_harm, adult, violence, drugs, weapons, pii, spam and minor — plus an overall flagged boolean that is true when any category is flagged.
There are no scores, probabilities or confidence values, and no thresholds to tune. Your work is policy, not parameter fiddling: decide which flag triggers which action, and write that down in your own code. Text of up to 10,000 characters is checked in 3,000-character pieces, and each started piece counts as one request. There is no batch endpoint and no webhooks, so the bot calls the endpoint per message — which fits an on_message handler naturally. The full schema lives in the Cloud API reference.
Wiring the flags into your bot's actions
Here is the screening call inside the handler you already have. The log_action helper is the one from the baseline above.
import asyncio
import os
from datetime import timedelta
import aiohttp
CAUTIONLABS_URL = "https://api.cautionlabs.com/moderation"
CAUTIONLABS_KEY = os.environ["CAUTIONLABS_API_KEY"]
http: aiohttp.ClientSession | None = None
async def screen(text: str) -> dict | None:
"""POST the message text; return the payload, or None if the check failed."""
if http is None:
return None
headers = {"Authorization": f"Bearer {CAUTIONLABS_KEY}"}
try:
async with http.post(
CAUTIONLABS_URL,
headers=headers,
json={"text": text},
timeout=aiohttp.ClientTimeout(total=5),
) as response:
response.raise_for_status()
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
return None
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author.bot or message.guild is None:
return
result = await screen(message.content)
if result is None:
# Fallback policy: allow the message and log that it was unchecked.
await log_action(message, "check-failed", "message allowed, not screened")
await bot.process_commands(message)
return
categories = result["categories"]
if categories["spam"]:
await message.delete()
await log_action(message, "delete", "spam")
elif categories["hate"] or categories["harassment"]:
await message.delete()
await message.author.timeout(timedelta(minutes=10), reason="hate or harassment")
await log_action(message, "delete+timeout", "hate or harassment")
elif categories["pii"]:
await message.delete()
# Refuse to store or forward the text: log the id, withhold the content.
await log_action(message, "delete", "pii", include_content=False)
elif result["flagged"]:
flagged = ", ".join(name for name, hit in categories.items() if hit)
await log_action(message, "review", f"flagged: {flagged}")
await bot.process_commands(message)Create that aiohttp.ClientSession once, in setup_hook or on_ready, and close it on shutdown. Reusing the session is the difference between a filter that adds a few milliseconds and one that adds a connection handshake to every message. Before you commit to screening every message in a large server, it is worth estimating the cost of screening every message so the bill does not surprise you.
When the text cannot leave your network
Some communities have rules — legal, contractual or internal — that mean message text cannot be sent to a hosted service at all. CautionLabs ships the same model as an on-premises deployment: you run the container inside your own infrastructure and call POST /moderate locally, by default at http://localhost:8000. The model container makes no outbound requests and has no telemetry. A private (on-premises) key does not work with the cloud API, so keep the two environments' credentials separate. See the on-premises guide for the deployment steps, or running moderation on your own infrastructure with Docker for the operational detail.
Roll it out without breaking your community
The first version of any filter will be wrong about someone. Rolling out in stages is how you find out before your members do.
Log-only mode first
Run the whole pipeline but change nothing in the channel: call the API, log the categories, and take no action. After a few days, sample the log — grab the messages flagged for each category, read them, and ask whether the action you planned would have been right. Adjust your mapping before it affects anyone. This is also the fastest way to learn which categories generate the most false positives in your specific community.
Per-category actions
Resist a global delete rule. Spam is cheap to remove. Harassment usually needs a timeout and a moderator's attention. Personal data needs the content gone and, ideally, out of your logs. Self-harm flagged content should reach a human rather than a punishment. Map each category to its own action, and let the unknown category fall through to review instead of enforcement.
What happens when the check fails
Decide this before you ship: if the moderation call times out or errors, does the bot allow the message and log it, or hold it? Allowing is friendlier and keeps the server moving; holding is stricter and creates a backlog. Neither is wrong, but leaving it undefined means your handler crashes or silently drops messages during an outage.
Before you enforce, test the paths that are easy to forget: edited messages (a separate gateway event), replies, direct messages, very long messages, and messages from webhooks. And keep a human appeal path — a pinned note in your rules channel explaining how to ask a moderator to review an automated decision costs nothing and defuses most of the anger a false positive creates.
Questions developers ask
Will screening every message slow my bot down?
It adds one network round trip per message. With a reused aiohttp session and a short timeout, it is usually small enough to be invisible — but measure it on your own traffic rather than trusting anyone's numbers, including ours. If latency matters more than coverage, log-only mode on a sample of channels is a reasonable compromise.
Should I delete the message or just log it?
Delete for spam and personal data, where leaving the content visible is itself the harm. For categories like toxicity or profanity, many communities prefer a warning and a log entry, because deletion without explanation reads as arbitrary.
How do I handle edited messages?
Discord delivers edits as a separate event from new messages, so your on_message filter does not see them. Add a handler for edits and run the same check, or a member can post something harmless and edit it afterwards.
Do I still need human moderators?
Yes. Automated screening triages; it does not judge intent, settle disputes or handle appeals. The log channel is what makes the automation useful to your moderators rather than a nuisance they work around.
Try one of your server's messages in the CautionLabs playground, then drop the POST /moderation call into your bot's on_message handler and start in log-only mode. When your volume or your data rules mean message text cannot leave your network, move the same check to the on-premises model.