Skip to content

"Discord-Link-manager-Bot, your dedicated educational companion. ๐Ÿ“š I use advanced AI to help you filter, categorize, and organize the chaos of shared links into a structured study library. Whether it's research papers, tutorials, or project resources, I'm here to ensure you never lose a vital piece of information again! ๐Ÿ’–"

License

Notifications You must be signed in to change notification settings

Rajrooter/Discord-Link-Bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

188 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿค– Labour Bot - AI-Powered Discord Link Manager

A sophisticated Discord bot that helps students and researchers manage educational resources with GPT-5 AI-powered link evaluation and smart categorization.

Python Version Discord.py License

โœจ Features

๐Ÿ”— Smart Link Management

  • AI-Powered Evaluation: Automatic assessment of links using Google Gemini 2.0 for educational value
  • Security Scanning: Built-in phishing and spam detection with AI safety analysis
  • Interactive Button UI: Modern Discord buttons for Save/Ignore with confirmation flows
  • Persistent Storage: MongoDB support with JSON file fallback for reliable data persistence
  • Smart Filtering: Automatically ignores media files (images, GIFs, videos)
  • Auto-Delete: Configurable auto-deletion of unresponded links to keep channels clean

๐Ÿ“š Organization Tools

  • Custom Categories: Organize links into unlimited custom categories
  • Pending Links: Review accumulated links from burst periods with !pendinglinks
  • Search Functionality: Quickly find links by keyword or category
  • Statistics Dashboard: Track usage patterns and popular domains
  • Recent Links: View your most recently saved resources

๐Ÿ—„๏ธ Storage Options

  • MongoDB: Production-ready database with proper IDs and queries
  • JSON Files: Automatic fallback for development and testing
  • Dual-Mode: Seamlessly switches based on configuration

๐Ÿ‘ฅ Member Onboarding

  • Automated Welcome: DM-based onboarding flow for new members
  • Role Assignment: Automatic role assignment based on member information
  • Rule Distribution: Automated server rules delivery

๐ŸŽจ Beautiful UI/UX

  • Custom Embeds: Adorable, color-coded Discord embeds
  • Interactive Commands: React-based interactions for intuitive navigation
  • Help System: Comprehensive help command with command details

๐Ÿ“‹ Prerequisites

  • Python 3.8 or higher
  • Discord Bot Token (Get one here)
  • OpenAI API access (via Replit AI Integrations or direct OpenAI API)

๐Ÿš€ Installation

1. Clone the Repository

git clone https://github.com/yourusername/labour-bot.git
cd labour-bot

2. Install Dependencies

pip install -r requirements.txt

3. Configure Environment Variables

Create a .env file in the root directory:

cp .env.example .env

Edit .env and add your credentials:

# Discord Bot Token
DISCORD_TOKEN=your_discord_bot_token_here

# Google Gemini API Key (for AI link analysis)
GEMINI_API_KEY=your_gemini_api_key

# Auto-delete configuration
AUTO_DELETE_ENABLED=1
AUTO_DELETE_AFTER=5

# MongoDB configuration (optional - uses JSON files if not set)
# IMPORTANT: URL-encode special characters in password (e.g., # -> %23)
# Example: mongodb+srv://user:pass%23word@cluster.mongodb.net/
# MONGODB_URI=mongodb://localhost:27017
# DB_NAME=discord_link_manager

โš ๏ธ Security Note: If you accidentally leak your credentials in commits:

  1. Immediately rotate your Discord bot token and API keys
  2. Update MongoDB user password if MONGODB_URI was exposed
  3. Review commit history and force-push if necessary

4. (Optional) Set Up MongoDB

The bot supports two storage modes:

Option A: MongoDB (Recommended for Production)

  • Provides persistent storage with proper IDs and queries
  • Better for multiple bot instances and data integrity
  • Set MONGODB_URI in .env to enable

Example MongoDB Atlas setup:

  1. Create free cluster at MongoDB Atlas
  2. Create database user and get connection string
  3. URL-encode special characters in password (e.g., p@ss#word โ†’ p%40ss%23word)
  4. Set environment variables:
    MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/
    DB_NAME=discord_link_manager

Test your MongoDB connection:

python test_mongo.py

Option B: JSON Files (Default)

  • Automatic fallback if MONGODB_URI is not set
  • Good for development and testing
  • Files: pending_links.json, saved_links.json, categories.json, onboarding_data.json

5. Set Up Discord Bot

  1. Go to Discord Developer Portal
  2. Create a new application
  3. Navigate to the "Bot" section
  4. Enable these Privileged Gateway Intents:
    • Message Content Intent
    • Server Members Intent
  5. Copy your bot token and add it to .env
  6. Use this invite link (replace CLIENT_ID with your application ID):
    https://discord.com/api/oauth2/authorize?client_id=CLIENT_ID&permissions=8&scope=bot
    

6. Run the Bot

python main.py

6.1 Render Web Service (Keeps Bot Online)

If you deploy on Render as a Web Service, you must bind to the PORT that Render provides. This repo already starts a small health server in main.py, so Render can detect the open port.

Recommended settings (Render):

  1. Service Type: Web Service
  2. Start Command: python main.py
  3. Environment Variables:
    • DISCORD_TOKEN=...
    • GEMINI_API_KEY=...
  4. Health Check Path (optional): /healthz

Note on HTTPS: Render terminates HTTPS at the load balancer and forwards traffic to your app over HTTP. You do not need to serve HTTPS inside the containerโ€”binding to the PORT is sufficient.

7. Testing

Local Development Testing:

  1. Set up test MongoDB instance or use JSON file mode
  2. Post a link in any channel: https://example.com/test
  3. Bot should respond with AI analysis and Save/Ignore buttons
  4. Click buttons to test functionality
  5. Use !pendinglinks to test pending link retrieval
  6. Test auto-delete by waiting (default 5 seconds)

MongoDB Connection Test:

python test_mongo.py

8. Diagnosing Duplicate Command Execution

If you experience duplicate command execution (commands running twice), check the diagnostic logs:

After restarting the bot, look for these debug prints in the console:

  • [labour] Starting bot process. PID=<number>, TIME=<timestamp> - Shows when the bot starts
  • [labour] LinkManager.__init__ called. PID=<number> - Shows when the cog is instantiated
  • [labour] LinkManager cog added (PID=<number>) - Confirms successful registration
  • [labour] on_ready called for <BotName> PID=<number> - Shows when bot connects to Discord

Diagnosis:

  1. Multiple processes (different PIDs): If you see different PID numbers in the logs, multiple bot instances are running. Solution: Stop all instances and start only one.
  2. Duplicate registration (same PID): If you see the same PID but LinkManager.__init__ is called twice, the cog is being registered multiple times. This should not happen with the guarded add_cog() implementation.
  3. Expected behavior: You should see each diagnostic message exactly once per bot start with the same PID throughout.

โ˜๏ธ Oracle Cloud Free Tier (24ร—7) Deployment

Use this when you want the bot to stay up 24ร—7 without an HTTP port. Oracle Cloudโ€™s Always Free compute is a common option for always-on bots.

1. Create an Always Free VM

  1. Sign up at Oracle Cloud Free Tier
  2. Create a Compute Instance:
    • Image: Ubuntu 22.04
    • Shape: VM.Standard.E2.1.Micro (Always Free eligible)
  3. Download your SSH private key
  4. Open SSH (port 22) in the instanceโ€™s Networking โ†’ Security Lists

2. Connect to Your VM

ssh -i /path/to/your_private_key ubuntu@<your_public_ip>

3. Install System Packages

sudo apt update
sudo apt install -y python3 python3-venv python3-pip git

4. Clone and Configure the Bot

git clone https://github.com/yourusername/labour-bot.git
cd labour-bot
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Create your .env file:

nano .env

Add at least:

DISCORD_TOKEN=your_discord_bot_token_here
GEMINI_API_KEY=your_gemini_api_key

5. Run the Bot with systemd (Auto-Restart)

Create a service file:

sudo nano /etc/systemd/system/labour-bot.service

Paste this (update paths to your repo):

[Unit]
Description=Labour Bot (Discord)
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/labour-bot
EnvironmentFile=/home/ubuntu/labour-bot/.env
ExecStart=/home/ubuntu/labour-bot/.venv/bin/python /home/ubuntu/labour-bot/main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl daemon-reload
sudo systemctl enable labour-bot
sudo systemctl start labour-bot

Check status/logs:

sudo systemctl status labour-bot --no-pager
sudo journalctl -u labour-bot -f

6. Update the Bot Later

cd /home/ubuntu/labour-bot
git pull
source .venv/bin/activate
pip install -r requirements.txt
sudo systemctl restart labour-bot

๐ŸŽฎ Commands

Link Management Commands

Command Description Usage
!pendinglinks Review your pending links from DB !pendinglinks
!category [name] Assign category to pending link !category Computer Science
!cancel Cancel pending link save !cancel
!getlinks [category] Retrieve all links or by category !getlinks or !getlinks Python
!categories List all categories !categories
!deletelink [number] Delete a specific link !deletelink 5
!deletecategory [name] Delete category and its links !deletecategory Physics
!clearlinks Clear all links (Admin only) !clearlinks
!searchlinks [term] Search for links !searchlinks machine learning
!analyze [url] Get AI analysis of a link !analyze https://example.com
!stats Show statistics !stats
!recent Show 5 most recent links !recent

General Commands

Command Description
!help Show all commands
!help [command] Get help for specific command

๐Ÿ”ง Configuration

Customizing Categories

Edit categories.json to pre-define categories:

{
  "Computer Science": [],
  "Mathematics": [],
  "Research Papers": []
}

Customizing Server Rules

Edit server_rules.txt to set your server rules for onboarding.

Customizing Ignored Media Extensions

In main.py, modify the IGNORED_EXTENSIONS list:

IGNORED_EXTENSIONS = [
    '.gif', '.png', '.jpg', '.jpeg', '.webp', '.bmp'
]

๐Ÿ—๏ธ Architecture

File Structure

discord-link-manager-bot/
โ”œโ”€โ”€ main.py                 # Main bot code
โ”œโ”€โ”€ storage.py             # MongoDB/JSON storage adapter
โ”œโ”€โ”€ test_mongo.py          # MongoDB connection test script
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ”œโ”€โ”€ runtime.txt            # Python version
โ”œโ”€โ”€ railway.toml           # Railway configuration
โ”œโ”€โ”€ .env                   # Environment variables (not committed)
โ”œโ”€โ”€ .env.example           # Template for environment variables
โ”œโ”€โ”€ .gitignore            # Git ignore rules
โ”œโ”€โ”€ README.md             # Documentation
โ””โ”€โ”€ LICENSE               # License file

Technology Stack

  • Framework: discord.py 2.3.2
  • AI Integration: Google Gemini 2.0 Flash (Free)
  • Storage: MongoDB with JSON file fallback
  • Database: pymongo for MongoDB operations
  • Async: Python asyncio for non-blocking operations
  • UI: Discord Buttons (discord.ui.View) for interactive elements

๐Ÿ”’ Security Features

  • Phishing Detection: Pre-AI keyword scanning for suspicious URLs
  • AI Security Analysis: Google Gemini powered link safety evaluation (Safe/Suspect/Unsafe)
  • Spam Prevention: Automatic filtering of common spam patterns
  • Media Filtering: Ignores non-educational media content
  • Confirmation Flows: Double-confirmation for destructive actions

๐Ÿค Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Guidelines

  • Follow PEP 8 style guidelines
  • Add docstrings to new functions
  • Test thoroughly before submitting PR
  • Update README if adding new features

๐Ÿ› Known Issues

  • Large servers may experience rate limiting with onboarding
  • AI analysis may timeout on slow connections
  • JSON file storage has limitations for concurrent access (use MongoDB for production)

๐Ÿ“ Roadmap

  • Database integration (MongoDB with JSON fallback)
  • Interactive button UI for link management
  • Web dashboard for link management
  • Link expiration and archiving
  • Export links to various formats (CSV, PDF)
  • Advanced analytics and visualization
  • Multi-server support with isolated data
  • Collaborative categorization

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

๐Ÿ“ง Support

โš ๏ธ Disclaimer

This bot stores links and user data. Storage can be in local JSON files or MongoDB database. Ensure you comply with Discord's Terms of Service and your local data protection regulations. The AI analysis is provided as-is and should not be solely relied upon for security decisions.


Made with โค๏ธ by [RAJ ARYAN] | GitHub | Discord

About

"Discord-Link-manager-Bot, your dedicated educational companion. ๐Ÿ“š I use advanced AI to help you filter, categorize, and organize the chaos of shared links into a structured study library. Whether it's research papers, tutorials, or project resources, I'm here to ensure you never lose a vital piece of information again! ๐Ÿ’–"

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages