A powerful Discord bot that automatically detects and removes scam messages from your server using machine learning. The bot uses a fine-tuned BERT model to identify spam, phishing attempts, and other malicious content with high accuracy.
Automatic Spam Detection - Uses ML model to detect scam messages in real-time
Auto Message Deletion - Instantly removes detected spam from your channels
Detailed Logging - Sends comprehensive reports to a private logging channel
Owner Notifications - Pings server owner when spam is detected
Role-Based Whitelisting - Exempt specific roles (Admins, Moderators) from scanning
Manual Checking - Admin command to manually check if text is spam
Statistics Dashboard - View bot stats and configuration
Lightweight Model - Runs efficiently on CPU or GPU
- Python 3.8+
- A Discord server where you have admin permissions
- A Discord bot token
Clone or download the bot files:
cd spam_botInstall dependencies:
pip install -r requirements.txt- Go to Discord Developer Portal
- Click "New Application" and name it
- Go to the "Bot" section and click "Add Bot"
- Under "TOKEN", click "Copy" and save this somewhere safe
- Enable these Privileged Gateway Intents:
- ✅ MESSAGE CONTENT INTENT (critical!)
- ✅ SERVER MEMBERS INTENT
- Go to "OAuth2" → "URL Generator"
- Select scopes:
bot - Select permissions:
- Read Messages/View Channels
- Send Messages
- Manage Messages (critical for deletion!)
- Embed Links
- Copy the generated URL and open it to add bot to your server
Create a .env file in the root directory:
# Your Discord bot token (from Developer Portal)
DISCORD_TOKEN=your_bot_token_here
# The private channel ID where spam logs are sent
# Create a private channel, right-click → Copy Channel ID
LOG_CHANNEL_ID=123456789012345678
MODERATOR_ROLE_ID=987654321 # Your role ID here
# Machine learning model to use
MODEL_NAME=mrm8488/bert-tiny-finetuned-sms-spam-detection
# Confidence threshold (0.0 to 1.0)
# Messages with confidence > this value are marked as spam
# Higher = more strict, lower = more lenient
SCAM_THRESHOLD=0.85
# Environment mode (development or production)
ENVIRONMENT=developmentHow to get LOG_CHANNEL_ID:
- Create a private channel in your server (e.g.,
#spam-logs) - Enable Developer Mode in Discord (Settings → Advanced → Developer Mode)
- Right-click the channel → "Copy Channel ID"
- Paste this ID in
.env
python bot.pyYou should see:
Loading model: mrm8488/bert-tiny-finetuned-sms-spam-detection
Model loaded successfully!
[INFO] All cogs loaded successfully
[INFO] Logged in as YourBotName (...)
[INFO] Moderation cog loaded. Monitoring messages...
Once running, the bot automatically monitors all messages. When spam is detected:
- Message is deleted from the channel
- Log entry is created in your
LOG_CHANNEL_IDchannel with:- User who sent the message
- User ID and join date
- Confidence score
- Detection method
- Full message content (for review)
- User's avatar
- Server owner is pinged to review the log
!check <message text>
Manually test if a message would be detected as spam.
Example:
!check @everyone FREE NITRO CLICK HERE NOW
Response:
Scam Detection Result
Is Scam?: Yes
Confidence: 95.20%
Reason: ML Detection + Suspicious Patterns
Tested Message: @everyone FREE NITRO CLICK HERE NOW
!stats
Shows bot statistics and current configuration.
Response:
Bot Statistics
Servers: 1
Model: mrm8488/bert-tiny-finetuned-sms-spam-detection
Threshold: 85.00%
Edit .env to change SCAM_THRESHOLD:
# More sensitive (catches more spam, more false positives)
SCAM_THRESHOLD=0.70
# Default (good balance)
SCAM_THRESHOLD=0.85
# Less sensitive (misses more spam, fewer false positives)
SCAM_THRESHOLD=0.95Edit cogs/moderation.py and update this line:
self.whitelisted_roles = ['Admin', 'Moderator', 'executive', 'chat revive ping']Add or remove role names to whitelist them from spam scanning.
Replace MODEL_NAME in .env with other spam detection models:
mrm8488/bert-tiny-finetuned-sms-spam-detection(recommended - small, fast)mariagrandury/roberta-base-finetuned-sms-spam-detection(more accurate, larger)unitary/toxic-bert(detects toxic/hateful content)
spam_bot/
├── bot.py # Main bot entry point
├── config.py # Configuration loader
├── requirements.txt # Python dependencies
├── .env # Environment variables
├── .env.example # Example env file
├── .gitignore # Git ignore file
├── LICENSE # License file
├── README.md # Documentation
├── utils/
│ ├── __init__.py # Package marker
│ ├── logger.py # Logging setup
│ ├── scam_detector.py # ML model for spam detection
│ └── config.py # (optional - if moved to utils)
└── cogs/
├── __init__.py # Package marker
└── moderation.py # Moderation commands and message monitoring
Try sending these messages to test the bot:
Strong Spam (should be detected):
@everyone 🎉 FREE DISCORD NITRO GIVEAWAY! 🎉 Click here to claim your free 3 months of Nitro: https://discord-nitro-free.com/claim Limited time only!
Phishing (should be detected):
⚠️ URGENT: Your Discord account has been flagged for suspicious activity. Verify your account now: bit.ly/verify-discord
Crypto Scam (should be detected):
💰 FREE ETHEREUM AIRDROP! 💰 Claim 0.5 ETH instantly! No verification needed: eth-airdrop-free.net
Legitimate Message (should pass):
Hey everyone! Check out this cool Python tutorial: https://realpython.com/python-basics/
To see detailed logs of what the bot is doing, set:
ENVIRONMENT=developmentThis will show [DEBUG] messages in the console for every message processed.
Check 1: MESSAGE_CONTENT Intent
- Go to Discord Developer Portal
- Select your bot
- Go to "Bot" section
- Verify "MESSAGE CONTENT INTENT" is enabled (toggle is blue)
- Restart your bot
Check 2: Bot Permissions
- In your server, right-click your bot role
- Ensure it has these permissions:
- Read Messages/View Channels
- Send Messages
- Manage Messages (essential!)
- Embed Links
Check 3: Bot Role Hierarchy
- Your bot's role must be above the users' roles
- Go to Server Settings → Roles
- Drag your bot's role above other roles
The bot likely doesn't have "Manage Messages" permission. See Bot Permissions above.
- Verify
LOG_CHANNEL_IDin.envis correct - Check the bot can send messages in that channel
- Check the channel exists and is private
If you see errors like Model not found, make sure you have an internet connection - the model downloads on first run (~500MB).
Make sure __init__.py exists in the cogs/ folder:
touch cogs/__init__.pyEdit scam_detector.py:
# Change from:
device=-1 # CPU
# To:
device=0 # GPU (CUDA)Requires GPU and PyTorch GPU support.
To fine-tune the model on your server's data:
- Collect examples of spam messages your server receives
- Label them as spam/ham
- Fine-tune the BERT model using Hugging Face
transformers - Replace
MODEL_NAMEin.envwith your model
See Hugging Face Fine-tuning Guide
- Model Size: ~18MB (tiny BERT)
- Inference Time: 0.1-0.3 seconds per message
- Accuracy: ~92-96% on spam detection tasks
- Memory: ~100-200MB RAM
- CPU: Can run on standard CPU
- GPU: Optional (much faster)
- Messages are only analyzed locally (not sent to external APIs)
- Logs are stored only in your private Discord channel
- Bot token is stored in
.env(never commit this to version control) - Only admins can use manual check commands
If you encounter issues:
- Check the console logs for error messages
- Enable debug mode in
.envto see detailed logs - Verify all permissions are granted to the bot
- Restart the bot after making changes
See requirements.txt:
discord.py>=2.3.2
python-dotenv>=1.0.0
transformers>=4.35.0
torch>=2.0.0
aiohttp>=3.9.0
This project is licensed under the MIT License - see the LICENSE file for details.
- Set up Discord bot token and permissions
- Create
.envfile with configuration - Install dependencies:
pip install -r requirements.txt - Run the bot:
python bot.py - Test with spam messages
- Adjust
SCAM_THRESHOLDbased on results - Whitelist trusted roles if needed
Good luck protecting your server!