Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+235 -175
View File
@@ -1,190 +1,250 @@
---
description: This rule provides best practices and coding standards for developing applications with the discord-api library. It covers code organization, performance, security, testing, and common pitfalls to ensure robust and maintainable Discord integrations.
globs: *.js,*.ts,*.jsx,*.tsx,*.py,*.cs
description: Definitive guidelines for building robust, scalable, and compliant Discord applications using the discord-api, emphasizing REST over Gateway, strong typing, and modern interaction patterns.
globs: **/*
---
## 1. Code Organization and Structure
# discord-api Best Practices
- **Directory Structure:**
- `src/`: Contains the main source code of your bot or application.
- `commands/`: Houses individual command modules, each in its own file or subdirectory.
- `events/`: Stores event handlers for Discord events (e.g., message creation, member join).
- `models/`: Defines data models and schemas (if applicable).
- `services/`: Contains reusable services or utilities (e.g., database connections, API wrappers).
- `config/`: Configuration files (e.g., API keys, bot token).
- `utils/`: Utility functions and helper modules.
- `tests/`: Unit and integration tests.
- `docs/`: Documentation for your bot or application.
- `scripts/`: Automation scripts (e.g., deployment, database setup).
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- Commands: `command_name.js`, `command_name.ts` or `command_name/index.js` for command directories.
- Events: `event_name.js`, `event_name.ts`.
- Models: `model_name.js`, `model_name.ts`.
- Services: `service_name.js`, `service_name.ts`.
- Configuration files: `config.json`, `config.js`, `config.ts`.
- **Module Organization:**
- Break down your bot logic into smaller, reusable modules.
- Use ES modules ( `import/export` in JavaScript/TypeScript) or equivalent module systems in other languages to manage dependencies.
- Avoid circular dependencies between modules.
- **Component Architecture:**
- **Command Handlers:** Create a dedicated module to handle command parsing, validation, and execution.
- **Event Emitters:** Use event emitters to decouple event handling logic from the core bot logic.
- **Service Layer:** Abstract external services (e.g., databases, APIs) behind a service layer.
- **Configuration Management:** Use a configuration management library to handle application settings.
- **Code Splitting:**
- Use dynamic imports to load command modules or event handlers on demand, reducing startup time.
- Bundle your code using tools like Webpack, Parcel, or Rollup to optimize bundle size.
- If applicable, use lazy loading for components or modules that are not immediately needed.
Building Discord applications requires adherence to specific patterns for reliability and compliance. This guide outlines the essential practices for our team.
## 2. Common Patterns and Anti-patterns
## 1. API Interaction: REST First, Gateway for Events
- **Design Patterns:**
- **Command Pattern:** Encapsulate commands as objects, allowing for flexible command management.
- **Observer Pattern:** Use event emitters to decouple event sources from event listeners.
- **Singleton Pattern:** Implement singleton instances for database connections or other shared resources.
- **Factory Pattern:** Create factories for creating Discord API objects (e.g., messages, embeds).
- **Recommended Approaches:**
- Use a command framework (e.g., discord.js commands) to streamline command creation and handling.
- Utilize Discord's rate limiting mechanisms effectively.
- Implement robust error handling and logging.
- Store sensitive information (e.g., API keys, bot token) in environment variables.
- **Anti-patterns and Code Smells:**
- **Global State:** Avoid using global variables to store bot state, as it can lead to unexpected behavior.
- **Hardcoding:** Do not hardcode configuration values or API keys in your code.
- **Nested Callbacks:** Avoid deeply nested callbacks, which can make your code difficult to read and maintain. Use async/await or promises instead.
- **Ignoring Errors:** Always handle errors properly and log them for debugging.
- **Over-Complicating:** Keep your code as simple as possible while still meeting the requirements.
- **State Management:**
- Use a dedicated state management library (e.g., Redux, Zustand) for complex bot state.
- Store persistent data in a database (e.g., MongoDB, PostgreSQL).
- Implement caching to improve performance.
- **Error Handling:**
- Use try-catch blocks to handle potential errors.
- Log errors to a file or service for debugging.
- Implement retry mechanisms for transient errors.
- Use Discord's error events to catch API errors.
- Send user-friendly error messages to users in the Discord channel.
Always prefer the HTTP REST API for creating, updating, or deleting resources. The Gateway is exclusively for receiving real-time events. This minimizes rate-limit issues and simplifies scaling.
## 3. Performance Considerations
❌ **BAD: Using Gateway for resource modification**
```typescript
// Don't send messages or modify roles via Gateway opcodes directly
// This is an oversimplification, but illustrates the anti-pattern
gateway.send({ op: GatewayOpcodes.MessageCreate, d: { channel_id: '...', content: '...' } });
```
- **Optimization Techniques:**
- Use efficient data structures and algorithms.
- Cache frequently accessed data.
- Optimize database queries.
- Use asynchronous operations to avoid blocking the main thread.
- Shard your bot to distribute the load across multiple processes.
- **Memory Management:**
- Avoid memory leaks by properly releasing resources.
- Use garbage collection to reclaim unused memory.
- Be mindful of large data structures that can consume a lot of memory.
- **Rendering Optimization:**
- Optimize image sizes and formats.
- Use lazy loading for images and other media.
- Consider using optimized libraries for generating images or videos.
- **Bundle Size Optimization:**
- Use tree shaking to remove unused code from your bundle.
- Minify your code to reduce bundle size.
- Compress your bundle using Gzip or Brotli.
- **Lazy Loading:**
- Load command modules and event handlers on demand.
- Load images and other media only when they are needed.
✅ **GOOD: Using REST for resource modification**
```typescript
import { Routes, REST } from 'discord-api-types/v10';
## 4. Security Best Practices
const rest = new REST().setToken(process.env.DISCORD_BOT_TOKEN!);
- **Common Vulnerabilities:**
- **Code Injection:** Prevent code injection vulnerabilities by validating user input and avoiding the use of `eval()` or similar functions.
- **Cross-Site Scripting (XSS):** If your bot interacts with websites or web applications, prevent XSS vulnerabilities by sanitizing user input and escaping output.
- **SQL Injection:** If your bot interacts with a database, prevent SQL injection vulnerabilities by using parameterized queries or an ORM.
- **Denial of Service (DoS):** Protect your bot from DoS attacks by implementing rate limiting and input validation.
- **Unauthorized Access:** Secure your bot's API endpoints and data by implementing authentication and authorization.
- **Input Validation:**
- Validate all user input to prevent malicious or invalid data from being processed.
- Use regular expressions or other validation techniques to enforce data types and formats.
- Sanitize user input to remove potentially harmful characters or code.
- **Authentication and Authorization:**
- Use a secure authentication mechanism to verify the identity of users.
- Implement authorization policies to control access to resources and functionality.
- Use role-based access control (RBAC) to manage user permissions.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms to protect API keys, bot tokens, and other credentials.
- Implement data loss prevention (DLP) measures to prevent sensitive data from being leaked.
- **Secure API Communication:**
- Use HTTPS to encrypt communication with the Discord API.
- Verify the server certificate to prevent man-in-the-middle attacks.
- Use secure API keys or tokens to authenticate with the Discord API.
// Always specify the API version (v10 as of 2025)
await rest.post(Routes.channelMessages('12345'), {
body: { content: 'Hello via REST!' },
});
```
## 5. Testing Approaches
## 2. Strong Typing with `discord-api-types`
- **Unit Testing:**
- Write unit tests for individual components and modules.
- Use mocking or stubbing to isolate components from external dependencies.
- Test edge cases and error conditions.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components.
- Test the bot's integration with the Discord API.
- Use a test Discord server to run integration tests.
- **End-to-End Testing:**
- Write end-to-end tests to verify the entire bot workflow.
- Simulate user interactions to test the bot's functionality.
- Use a testing framework to automate end-to-end tests.
- **Test Organization:**
- Organize your tests into separate directories for unit tests, integration tests, and end-to-end tests.
- Use descriptive test names to indicate the purpose of each test.
- Follow a consistent naming convention for test files.
- **Mocking and Stubbing:**
- Use mocking libraries to create mock objects that simulate the behavior of external dependencies.
- Use stubbing to replace real dependencies with simplified versions for testing purposes.
Ensure all API payloads conform to Discord's official types. This prevents runtime errors and future-proofs against API changes.
## 6. Common Pitfalls and Gotchas
❌ **BAD: Untyped payloads**
```typescript
// Prone to typos and API changes breaking at runtime
const messagePayload = {
channel_id: '123',
content: 'Untyped message',
};
```
- **Frequent Mistakes:**
- **Rate Limiting:** Failing to handle Discord API rate limits properly.
- **Incorrect Intents:** Not specifying the correct gateway intents for your bot.
- **Asynchronous Operations:** Not properly handling asynchronous operations, leading to race conditions or unexpected behavior.
- **Data Serialization:** Incorrectly serializing or deserializing data when interacting with the API.
- **Privileged Intents:** Not understanding the requirements for using privileged intents (e.g., presence, guild members, message content).
- **Edge Cases:**
- Handling large guilds with many members or channels.
- Dealing with unexpected API errors or outages.
- Handling different user locales and languages.
- Managing concurrency and race conditions.
- **Version-Specific Issues:**
- Being aware of breaking changes between different versions of the discord-api library.
- Using deprecated features or APIs.
- Ensuring compatibility with different versions of Node.js or other dependencies.
- **Compatibility Concerns:**
- Ensuring compatibility with different operating systems and platforms.
- Avoiding conflicts with other libraries or dependencies.
- Testing the bot on different Discord clients (e.g., web, desktop, mobile).
- **Debugging Strategies:**
- Use logging to track the bot's execution flow and identify errors.
- Use a debugger to step through the code and inspect variables.
- Use Discord's developer tools to inspect API requests and responses.
- Test your code thoroughly and write unit tests to catch errors early.
✅ **GOOD: Typed payloads**
```typescript
import { APIChannel, APIMessage } from 'discord-api-types/v10';
## 7. Tooling and Environment
const channel: APIChannel = await rest.get(Routes.channel('123'));
const messagePayload: APIMessage = {
channel_id: channel.id,
content: 'Typed message!',
// ... other required fields
};
```
- **Recommended Development Tools:**
- **IDE:** Visual Studio Code, IntelliJ IDEA, or other IDE with support for JavaScript/TypeScript.
- **Package Manager:** npm or yarn for managing dependencies.
- **Debugging Tools:** Node.js debugger or Chrome DevTools.
- **Linting Tools:** ESLint or JSHint for enforcing coding standards.
- **Formatting Tools:** Prettier for automatically formatting code.
- **Build Configuration:**
- Use a build tool like Webpack, Parcel, or Rollup to bundle your code.
- Configure your build process to minify and compress your code.
- Use environment variables to configure your build process.
- **Linting and Formatting:**
- Use ESLint or JSHint to enforce coding standards.
- Use Prettier to automatically format your code.
- Configure your editor to automatically run linters and formatters on save.
- **Deployment Best Practices:**
- Use a process manager like PM2 or systemd to keep your bot running.
- Deploy your bot to a cloud platform like Heroku, AWS, or Google Cloud.
- Use a reverse proxy like Nginx or Apache to handle incoming requests.
- Monitor your bot's performance and health.
- **CI/CD Integration:**
- Use a CI/CD platform like GitHub Actions, GitLab CI, or CircleCI to automate your build, test, and deployment process.
- Run unit tests and integration tests as part of your CI/CD pipeline.
- Automate the deployment process to reduce manual effort and errors.
## 3. Rate Limit Handling: Exponential Back-off
Discord's API is heavily rate-limited. Implement robust exponential back-off with jitter to handle `429 Too Many Requests` responses gracefully.
❌ **BAD: Ignoring rate limits or simple retries**
```typescript
try {
await rest.post(Routes.channelMessages('...'), { body: { content: '...' } });
} catch (error: any) {
if (error.status === 429) {
console.warn('Rate limited! Retrying immediately...');
await rest.post(Routes.channelMessages('...'), { body: { content: '...' } }); // Will likely fail again
}
}
```
✅ **GOOD: Exponential back-off with `Retry-After`**
```typescript
import { setTimeout } from 'node:timers/promises';
async function makeRequestWithRetry(requestFn: () => Promise<any>, retries = 5, delay = 1000): Promise<any> {
try {
return await requestFn();
} catch (error: any) {
if (error.status === 429 && retries > 0) {
const retryAfter = (error.headers?.get('Retry-After') ? parseInt(error.headers.get('Retry-After')!) * 1000 : delay) + Math.random() * 500;
console.warn(`Rate limited. Retrying in ${retryAfter}ms. Retries left: ${retries}`);
await setTimeout(retryAfter);
return makeRequestWithRetry(requestFn, retries - 1, delay * 2);
}
throw error;
}
}
await makeRequestWithRetry(() => rest.post(Routes.channelMessages('...'), { body: { content: '...' } }));
```
## 4. Secure Token Management
Never hardcode or commit bot tokens. Use environment variables or a secure secret management system.
❌ **BAD: Hardcoded token**
```typescript
const rest = new REST().setToken('YOUR_SUPER_SECRET_TOKEN_HERE');
```
✅ **GOOD: Environment variable**
```typescript
// Ensure DISCORD_BOT_TOKEN is set in your environment
const rest = new REST().setToken(process.env.DISCORD_BOT_TOKEN!);
```
## 5. Gateway Intents: Request Only What's Needed
Specify only the Gateway Intents your bot genuinely requires. Over-requesting intents can lead to verification denial and unnecessary resource consumption.
❌ **BAD: Requesting all intents or privileged intents without justification**
```typescript
// Don't request all intents if you only need MESSAGE_CREATE
const client = new Client({ intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent, // Privileged, requires justification
// ... many more
]});
```
✅ **GOOD: Minimal, justified intents**
```typescript
import { Client, GatewayIntentBits } from 'discord.js'; // Or your chosen library
const client = new Client({ intents: [
GatewayIntentBits.Guilds, // For guild-related events
GatewayIntentBits.GuildMessages, // For message events in guilds
GatewayIntentBits.MessageContent, // ONLY if you process message content (privileged)
]});
```
## 6. Modern UI: Slash Commands & Message Components
Prioritize Application Commands (slash commands) and Message Components (buttons, select menus) for user interaction. Text commands are largely deprecated for new features.
❌ **BAD: Relying solely on prefix commands**
```typescript
// This approach is outdated for new features
client.on('messageCreate', message => {
if (message.content.startsWith('!mycommand')) {
// ...
}
});
```
✅ **GOOD: Registering and handling slash commands**
```typescript
import { ApplicationCommandType, Routes, REST } from 'discord-api-types/v10';
const commands = [{
name: 'ping',
description: 'Replies with Pong!',
type: ApplicationCommandType.ChatInput,
}];
const rest = new REST().setToken(process.env.DISCORD_BOT_TOKEN!);
// Register commands globally or per guild
await rest.put(Routes.applicationCommands(process.env.DISCORD_CLIENT_ID!), { body: commands });
// Handle interactionCreate event for slash commands
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
```
## 7. Code Organization: Modular and Testable
Structure your bot into modular, testable components (e.g., separate files for commands, events, services). This improves maintainability and allows for easier testing.
❌ **BAD: Monolithic bot file**
```typescript
// bot.ts
client.on('ready', () => { /* ... */ });
client.on('messageCreate', () => { /* ... */ });
// ... all logic in one file
```
✅ **GOOD: Modular structure**
```typescript
// src/bot.ts
import { Client } from 'discord.js';
import { registerCommands } from './commands';
import { registerEvents } from './events';
const client = new Client({ intents: [...] });
registerCommands(client);
registerEvents(client);
client.login(process.env.DISCORD_BOT_TOKEN);
// src/commands/index.ts
export function registerCommands(client: Client) {
// Load and register command handlers
}
// src/events/index.ts
export function registerEvents(client: Client) {
// Load and register event handlers
}
```
## 8. Data Storage: Use Databases
For persistent data, always use a proper database (SQL or NoSQL). Avoid JSON files for anything beyond simple configuration. JSON files are inefficient for frequent writes and concurrent access.
❌ **BAD: Storing user data in JSON files**
```typescript
// user_data.json
// { "userId": { "points": 100, "level": 5 } }
// This rewrites the entire file on every change, inefficient and error-prone
```
✅ **GOOD: Using a database**
```typescript
// Example with a simple ORM/ODM (e.g., Prisma, Mongoose, SQLAlchemy)
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function updateUserPoints(userId: string, points: number) {
await prisma.user.upsert({
where: { id: userId },
update: { points: { increment: points } },
create: { id: userId, points: points, level: 1 },
});
}
```
## 9. Game SDK & Rich Presence: Modern Approach
The original Game SDK is archived. For new game integrations, prioritize the Discord Social SDK. If using the legacy Game SDK, rely on its "stub" libraries to ensure compatibility. For Rich Presence, keep strings concise, actionable, and utilize all available fields for maximum impact.
❌ **BAD: Long, uninformative Rich Presence strings**
```typescript
// "Playing a very long game of my favorite game with my friends and having a great time"
```
✅ **GOOD: Concise and actionable Rich Presence**
```typescript
// "Playing [Game Name]"
// "In a party with 3 others"
// "Elapsed: 00:15:30"
// "Join Game" button
```