Skip to content

The LeetDiscord Bot by EpicBotCoders is a Discord bot designed to track LeetCode activity for specified users. It is built using Node.js and integrates with Discord.js, MongoDB, and Jest for testing. The bot allows users to monitor their LeetCode progress directly within Discord, facilitating community engagement and accountability.

License

Notifications You must be signed in to change notification settings

EpicBotCoders/leetDiscord

LeetDiscord Bot

License: MIT Contributor Covenant Security Policy PRs Welcome Node.js Version Discord.js MongoDB Jest ESLint Winston Logger GitHub last commit Test Coverage

This Discord bot tracks LeetCode activity for specified users and posts updates to Discord channels. It supports multiple servers (guilds) with per-server configurations, storing data in MongoDB Atlas.

Table of Contents

Prerequisites

Quick Start

Follow these steps to get your bot up and running:

1. Clone and Install

git clone https://github.com/mochiron-desu/leetDiscord.git
cd leetDiscord
npm install

2. Create Discord Bot

  1. Go to Discord Developer Portal
  2. Click "New Application" and give it a name
  3. Navigate to the "Bot" section
  4. Click "Add Bot"
  5. Under "Token", click "Copy" to get your bot token
  6. Important: Enable the following Privileged Gateway Intents:
    • Server Members Intent
    • Message Content Intent

3. Set Up MongoDB Atlas

  1. Create a free account at MongoDB Atlas
  2. Create a new cluster (free M0 tier is sufficient)
  3. Set up database access:
    • Create a database user with read/write permissions
    • Note down the username and password
  4. Set up network access:
    • Add your IP address (or use 0.0.0.0/0 for testing)
  5. Click "Connect" β†’ "Connect your application"
  6. Copy the connection string

4. Configure Environment Variables

Create a .env file in the root directory:

DISCORD_TOKEN=your_discord_bot_token
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/leetdiscord?retryWrites=true&w=majority
NODE_ENV=production

Replace:

  • your_discord_bot_token with the token from Discord Developer Portal
  • username:password with your MongoDB credentials
  • cluster.mongodb.net with your cluster URL

5. Invite Bot to Your Server

  1. In Discord Developer Portal, go to "OAuth2" β†’ "URL Generator"
  2. Select scopes: bot and applications.commands
  3. Select bot permissions:
    • View Channels
    • Send Messages
    • Embed Links
    • Manage Channels (for admins setting up the bot)
  4. Copy the generated URL and open it in your browser
  5. Select your server and authorize

6. Start the Bot

node index.js

You should see:

Bot is ready!
Started refreshing application (/) commands.
Successfully reloaded application (/) commands.
Bot initialization complete

7. Initial Server Configuration

In your Discord server, run these commands to get started:

  1. Set announcement channel: /setchannel #your-channel
  2. Add users to track: /adduser username @DiscordUser
  3. Set up automatic checks (optional): /managecron add hours:10 minutes:0
  4. Test it out: /check

Need help? Use /help in Discord to see all available commands!

Server Setup

When the bot joins a new server:

  1. It will automatically create initial configuration in MongoDB
  2. The bot will send a welcome message explaining how to get started
  3. Use the /setchannel command to set the announcement channel
  4. Use /adduser to start tracking LeetCode users

Available Commands

All commands are available as Discord slash commands. Type / in Discord to see the autocomplete list. Use /help to see detailed information about all commands.

Setup Commands

/setchannel #channel

Permission Required: Manage Channels πŸ”’

Set the channel where LeetCode activity announcements will be posted.

Usage Examples:

/setchannel #leetcode-updates
/setchannel #daily-coding

What it does:

  • Initializes the server configuration in the database
  • Sets the specified channel as the announcement channel
  • Sends a test message to verify bot permissions
  • Required before other commands will work properly

User Management Commands

/adduser username [discord_user]

Add a LeetCode username to the tracking list. Optionally link to a Discord user for mentions.

Permission Requirements:

  • Users can add themselves without special permissions
  • Manage Roles permission required to add other users

Usage Examples:

/adduser john_doe
/adduser alice123 @Alice
/adduser bob_coder discord_user:@BobTheCoder

Parameters:

  • username (required): The LeetCode username to track
  • discord_user (optional): Discord user to mention in updates

/removeuser username

Remove a LeetCode username from tracking.

Permission Requirements:

  • Users can remove themselves without special permissions
  • Manage Roles permission required to remove other users

Usage Examples:

/removeuser john_doe
/removeuser alice123

/listusers

Display all LeetCode users currently being tracked in this server.

Usage Example:

/listusers

Output shows:

  • LeetCode username
  • Linked Discord user (if any)

Scheduling Commands

All scheduling commands require Manage Channels permission πŸ”’

/managecron add hours minutes

Add a new automatic check time (24-hour format).

Usage Examples:

/managecron add hours:10 minutes:0    # Daily check at 10:00 AM
/managecron add hours:18 minutes:30   # Daily check at 6:30 PM
/managecron add hours:23 minutes:59   # Daily check at 11:59 PM

Parameters:

  • hours: 0-23 (24-hour format)
  • minutes: 0-59

Default Schedule: New servers start with checks at 10:00 and 18:00 UTC

/managecron remove hours minutes

Remove an existing automatic check time.

Usage Example:

/managecron remove hours:18 minutes:30

/managecron list

List all scheduled check times for this server.

Usage Example:

/managecron list

Monitoring Commands

/check

Manually trigger a check of today's LeetCode daily challenge for all tracked users.

Usage Example:

/check

What it does:

  • Fetches today's LeetCode daily challenge
  • Checks each tracked user's submission history
  • Posts results to the configured announcement channel
  • Shows who completed the challenge and who hasn't
  • Includes problem details (difficulty, tags, acceptance rate)

Information Commands

/botinfo

Display information about the bot and link to the GitHub repository.

Usage Example:

/botinfo

/help

Display a comprehensive help message with all commands, usage examples, and a quick start guide.

Usage Example:

/help

Notification Commands

/telegram connect

Link your Telegram account to receive notifications about incomplete daily challenges.

Usage Example:

/telegram connect

What it does:

  • Generates a unique link to the Telegram bot
  • Links your Discord user to your Telegram account
  • Enables notifications for daily challenge reminders

/telegram status

Check your Telegram connection status.

Usage Example:

/telegram status

/telegram toggle

Enable or disable Telegram notifications.

Usage Example:

/telegram toggle

Command Workflow

Understanding how commands interact with each other:

graph TD
    A[Bot Joins Server] --> B[/setchannel]
    B --> C{Guild Configured}
    C -->|Yes| D[/adduser]
    C -->|Yes| E[/managecron]
    D --> F[Users Tracked]
    E --> G[Schedule Set]
    F --> H[/check]
    G --> H
    H --> I[Results Posted]
    I --> J[MongoDB Update]
    
    style B fill:#ffd700
    style D fill:#90EE90
    style E fill:#87CEEB
    style H fill:#FFB6C1
Loading

Flow Explanation:

  1. Initial Setup (/setchannel)

    • Creates guild configuration in MongoDB
    • Sets announcement channel
    • Enables all other commands
  2. User Management (/adduser, /removeuser)

    • Requires configured guild
    • Stores user mappings in database
    • Links LeetCode accounts to Discord users
  3. Scheduling (/managecron)

    • Sets up automated checks using cron jobs
    • Multiple check times can be configured
    • Automatically triggers /check functionality
  4. Monitoring (/check)

    • Can be triggered manually or automatically
    • Queries LeetCode GraphQL API for:
      • Today's daily challenge
      • User submission history
    • Checks against MongoDB for duplicate tracking
    • Posts formatted embed to announcement channel
    • Records submissions in database

Data Flow:

  • LeetCode API β†’ Bot β†’ MongoDB β†’ Discord Channel
  • Cached API responses for performance
  • Submission tracking prevents duplicates

Features

  • Multi-server support with independent configurations
  • MongoDB Atlas integration for reliable data storage
  • Per-server announcement channels
  • Automated welcome message with setup instructions
  • Permission-based command system:
    • Users can add/remove themselves
    • Admins can manage all users
    • Channel management requires "Manage Channels" permission
  • Optional Discord user mentions when reporting challenge status
  • Flexible cron job management for check schedules
  • Detailed problem information in status updates:
    • Problem difficulty
    • Topic tags
    • Acceptance rate
    • Direct link to problem
  • Complete submission tracking:
    • Daily challenge completion history
    • Submission timestamps
    • Problem difficulty tracking
    • Duplicate submission prevention
    • Built-in retry and error handling
  • Robust timestamp handling:
    • Support for Unix timestamps
    • Support for ISO string dates
    • Fallback handling for invalid dates
  • Permission handling:
    • Automatic permission checks
    • Guild owner notifications for permission issues
    • Detailed error feedback
  • Winston-based logging system with:
    • Error tracking
    • Warning notifications
    • Debug information
    • Activity logging
  • Automated user tracking and status updates

Environment Variables

Variable Description
DISCORD_TOKEN Your Discord bot token
MONGODB_URI MongoDB Atlas connection string
NODE_ENV Set to 'production' for production logging levels

Security

For details about our security practices and how to report security issues, please see our Security Policy.

Error Handling

  • The bot includes comprehensive error logging
  • All errors are logged to logs/error.log
  • General activity is logged to logs/combined.log
  • Console output includes colorized logging for better visibility

Data Migration

If you're upgrading from a previous version that used config.json:

  1. The migration script will automatically:
    • Move guild configurations to MongoDB
    • Create a backup of your config.json as config.json.bak
    • Update config.json to only contain the bot token
  2. After migration, update your environment variables in .env

Contributing

We love contributions! Please see our Contributing Guide for details on how to:

  • Set up your development environment
  • Run tests
  • Submit pull requests
  • Report bugs
  • Propose new features

Code of Conduct

We are committed to fostering an open and welcoming environment. Please read and follow our Code of Conduct.

Security

For details about our security practices and how to report security issues, please see our Security Policy.

Testing

The project includes a comprehensive test suite using Jest. To run the tests:

npm test

Test Coverage

Tests cover all major functionality including:

  • DailySubmission model validation
  • Timestamp parsing and handling
  • Permission checks and error handling
  • API interactions and response handling
  • Database operations
  • Discord message handling

The test suite uses:

  • mongodb-memory-server for database testing
  • axios-mock-adapter for API mocking
  • Jest mocks for Discord.js interactions
  • Winston logger mocking
  • Comprehensive assertion coverage

Test coverage reports are available in the coverage/ directory after running tests.

Running Specific Tests

Run a specific test suite:

npm test -- apiUtils

Watch mode for development:

npm run test:watch

Generate coverage report:

npm run test:coverage

License

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

Changelog

v2.2.0 (2026-02-07)

  • πŸ”” Telegram Integration:
    • Connect Telegram account for personal notifications
    • Receive reminders for incomplete daily challenges
    • Manage notification preferences
  • πŸ“Š Enhanced Statistics:
    • Added /leetstats command for detailed user logic
    • Support for server-wide statistics view
    • Track streaks, active days, and more
  • ℹ️ Dynamic Help Command:
    • Help strings are now dynamically generated from command definitions
    • Always up-to-date with available commands
  • πŸ› Bug Fixes:
    • Improved error handling for unconfigured guilds
    • Fixed issues with Telegram linking

v2.1.0 (2025-05-04)

  • ✨ Added submission tracking with MongoDB
  • πŸŽ‰ Added welcome message when bot joins a server
  • βž• Added /botinfo command for quick bot information access
  • πŸ”„ Improved timestamp handling with support for:
    • Unix timestamps (seconds/milliseconds)
    • ISO string dates
    • Fallback handling for invalid dates
  • πŸ”’ Enhanced permission handling:
    • Automatic permission checks before sending messages
    • Guild owner notifications for permission issues
    • Detailed error feedback
  • πŸ§ͺ Added comprehensive test coverage:
    • MongoDB integration tests
    • Timestamp parsing tests
    • Permission handling tests
    • API interaction mocks
  • πŸ“ Improved error logging and debugging
  • ⚑️ Added duplicate submission prevention
  • πŸš€ Added retry mechanisms for API failures

v2.0.0 (2025-05-02)

  • πŸŽ‰ Migrated from JSON file storage to MongoDB Atlas
  • ✨ Added flexible cron job management with /managecron command
  • πŸ”„ Enhanced status updates with detailed problem information
  • πŸ“ Improved logging system with Winston
  • πŸ”’ Moved sensitive data to environment variables
  • πŸ› Fixed user tracking and removal issues
  • πŸš€ Improved error handling and interaction responses
  • πŸ“Š Added debug logging for better troubleshooting

v1.0.0

  • Initial release with JSON-based configuration
  • Basic LeetCode activity tracking
  • Multi-server support
  • User management commands
  • Scheduled checks

About

The LeetDiscord Bot by EpicBotCoders is a Discord bot designed to track LeetCode activity for specified users. It is built using Node.js and integrates with Discord.js, MongoDB, and Jest for testing. The bot allows users to monitor their LeetCode progress directly within Discord, facilitating community engagement and accountability.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •