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.
- LeetDiscord Bot
- Node.js (v14 or higher)
- A Discord bot token (from Discord Developer Portal)
- MongoDB Atlas account (free tier works fine)
Follow these steps to get your bot up and running:
git clone https://github.com/mochiron-desu/leetDiscord.git
cd leetDiscord
npm install- Go to Discord Developer Portal
- Click "New Application" and give it a name
- Navigate to the "Bot" section
- Click "Add Bot"
- Under "Token", click "Copy" to get your bot token
- Important: Enable the following Privileged Gateway Intents:
- Server Members Intent
- Message Content Intent
- Create a free account at MongoDB Atlas
- Create a new cluster (free M0 tier is sufficient)
- Set up database access:
- Create a database user with read/write permissions
- Note down the username and password
- Set up network access:
- Add your IP address (or use
0.0.0.0/0for testing)
- Add your IP address (or use
- Click "Connect" β "Connect your application"
- Copy the connection string
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=productionReplace:
your_discord_bot_tokenwith the token from Discord Developer Portalusername:passwordwith your MongoDB credentialscluster.mongodb.netwith your cluster URL
- In Discord Developer Portal, go to "OAuth2" β "URL Generator"
- Select scopes:
botandapplications.commands - Select bot permissions:
- View Channels
- Send Messages
- Embed Links
- Manage Channels (for admins setting up the bot)
- Copy the generated URL and open it in your browser
- Select your server and authorize
node index.jsYou should see:
Bot is ready!
Started refreshing application (/) commands.
Successfully reloaded application (/) commands.
Bot initialization complete
In your Discord server, run these commands to get started:
- Set announcement channel:
/setchannel #your-channel - Add users to track:
/adduser username @DiscordUser - Set up automatic checks (optional):
/managecron add hours:10 minutes:0 - Test it out:
/check
Need help? Use /help in Discord to see all available commands!
When the bot joins a new server:
- It will automatically create initial configuration in MongoDB
- The bot will send a welcome message explaining how to get started
- Use the
/setchannelcommand to set the announcement channel - Use
/adduserto start tracking LeetCode users
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.
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
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 trackdiscord_user(optional): Discord user to mention in updates
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
Display all LeetCode users currently being tracked in this server.
Usage Example:
/listusers
Output shows:
- LeetCode username
- Linked Discord user (if any)
All scheduling commands require Manage Channels permission π
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
Remove an existing automatic check time.
Usage Example:
/managecron remove hours:18 minutes:30
List all scheduled check times for this server.
Usage Example:
/managecron list
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)
Display information about the bot and link to the GitHub repository.
Usage Example:
/botinfo
Display a comprehensive help message with all commands, usage examples, and a quick start guide.
Usage Example:
/help
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
Check your Telegram connection status.
Usage Example:
/telegram status
Enable or disable Telegram notifications.
Usage Example:
/telegram toggle
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
Flow Explanation:
-
Initial Setup (
/setchannel)- Creates guild configuration in MongoDB
- Sets announcement channel
- Enables all other commands
-
User Management (
/adduser,/removeuser)- Requires configured guild
- Stores user mappings in database
- Links LeetCode accounts to Discord users
-
Scheduling (
/managecron)- Sets up automated checks using cron jobs
- Multiple check times can be configured
- Automatically triggers
/checkfunctionality
-
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
- 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
| Variable | Description |
|---|---|
| DISCORD_TOKEN | Your Discord bot token |
| MONGODB_URI | MongoDB Atlas connection string |
| NODE_ENV | Set to 'production' for production logging levels |
For details about our security practices and how to report security issues, please see our Security Policy.
- 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
If you're upgrading from a previous version that used config.json:
- 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
- After migration, update your environment variables in .env
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
We are committed to fostering an open and welcoming environment. Please read and follow our Code of Conduct.
For details about our security practices and how to report security issues, please see our Security Policy.
The project includes a comprehensive test suite using Jest. To run the tests:
npm testTests 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.
Run a specific test suite:
npm test -- apiUtilsWatch mode for development:
npm run test:watchGenerate coverage report:
npm run test:coverageThis project is licensed under the MIT License - see the LICENSE file for details.
- π Telegram Integration:
- Connect Telegram account for personal notifications
- Receive reminders for incomplete daily challenges
- Manage notification preferences
- π Enhanced Statistics:
- Added
/leetstatscommand for detailed user logic - Support for server-wide statistics view
- Track streaks, active days, and more
- Added
- βΉοΈ 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
- β¨ 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
- π 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
- Initial release with JSON-based configuration
- Basic LeetCode activity tracking
- Multi-server support
- User management commands
- Scheduled checks