Discord-based cloud storage solution for file compression, segmentation, and backup using Discord as a backend
npm install discord-dcloud
Local File/Folder
ā
Compression (LZMA2)
ā
Segmentation (8MB chunks)
ā
Upload to Discord Bot
ā
Store in Forum Threads
ā
Metadata Tracking (JSON)
`
$3
DCloud acts as a bridge between your local file system and Discord servers, enabling:
- šļø Compression: Automatic file/folder compression using LZMA2 algorithm with 512MB dictionary
- āļø Segmentation: Intelligent splitting of large files into manageable 8MB parts
- š¤ Upload: Fully automated uploading to Discord forum threads via bot
- š„ Retrieval: Seamless download and restore with automatic cleanup
- š Metadata: JSON-based tracking for file integrity and recovery
---
ā” Quick Start
$3
`bash
npm install discord-dcloud
`
$3
`bash
git clone https://github.com/NeelFrostrain/DCloud.git
cd DCloud
npm install
`
$3
- Create a Discord bot at Discord Developer Portal
- Get your bot token, server ID, and forum channel ID
- Add bot to your server with proper permissions
$3
Edit src/index.ts:
`typescript
const TOKEN = "YOUR_BOT_TOKEN";
const CHANNEL_ID = "YOUR_FORUM_CHANNEL_ID";
const GUILD_ID = "YOUR_SERVER_ID";
`
$3
`bash
Development mode (with auto-reload)
npm run dev
Or production mode
npm run build && npm start
`
---
⨠Features
| Feature | Description |
| ------------------------------ | ------------------------------------------------------------- |
| šļø Advanced Compression | LZMA2 algorithm with 512MB dictionary for maximum compression |
| āļø Smart Segmentation | Automatic 8MB chunking for Discord compatibility |
| š¤ Discord Bot Integration | Full Discord.js v14 support with forum thread management |
| š Metadata Tracking | JSON-based metadata for file integrity and recovery |
| ā” Concurrent Uploads | Parallel upload handling for optimal performance |
| š„ Full Restoration | Complete download and extraction pipeline |
| ā
TypeScript | Fully typed codebase with strict type checking |
| šØ Rich Logging | Color-coded console output with Chalk |
| š”ļø Error Handling | Comprehensive error management and recovery |
| š¦ Production Ready | Optimized for production use with proper cleanup |
---
š¦ Prerequisites
$3
| Requirement | Version | Note |
| -------------- | ----------- | ------------------------------------------ |
| Node.js | ā„ 18.0.0 | Runtime environment |
| npm | ā„ 9.0.0 | Package manager |
| TypeScript | ā„ 5.0 | Peer dependency (required for development) |
| Disk Space | 500MB+ | For temporary files during compression |
| RAM | 2GB minimum | 4GB+ recommended |
$3
- Discord Server: Admin access to create forum channels
- Discord Bot: Valid bot token with proper permissions
- 7-Zip: Bundled via 7zip-bin package (auto-installed)
$3
Your bot requires these permissions:
`
PERMISSIONS NEEDED:
ā Send Messages
ā Create Public Threads
ā Send Messages in Threads
ā Embed Links
ā Attach Files
ā Read Message History
`
$3
| OS | Status | Notes |
| ----------- | ------------------ | ------------------------------------------ |
| Windows | ā
Fully Supported | Recommended |
| macOS | ā
Fully Supported | Requires p7zip-full |
| Linux | ā
Fully Supported | Install: sudo apt-get install p7zip-full |
---
š Installation
$3
`bash
git clone https://github.com/NeelFrostrain/DCloud.git
cd DCloud
`
$3
`bash
npm install
`
This installs:
- discord.js v14.25.1 - Discord bot framework
- 7zip-bin v5.2.0 - 7-Zip binary
- chalk v5.6.2 - Terminal styling
- Dev Tools - ESLint, TypeScript, Nodemon
$3
`bash
Check TypeScript compilation
npm run type-check
Lint code
npm run lint
Try building
npm run build
`
$3
---
āļø Configuration
$3
#### 1. Create Discord Application
1. Go to Discord Developer Portal
2. Click "New Application"
3. Enter name: DCloud Bot (or your preference)
4. Accept Terms and Create
#### 2. Create Bot User
1. Navigate to "Bot" section
2. Click "Add Bot"
3. Click "Reset Token" to copy bot token
4. ā ļø Keep this token secret! Never commit to git
#### 3. Configure Bot Permissions
1. Go to "OAuth2" ā "URL Generator"
2. Select Scopes: bot
3. Select Permissions:
- ā Send Messages
- ā Create Public Threads
- ā Send Messages in Threads
- ā Embed Links
- ā Attach Files
- ā Read Message History
4. Copy the generated URL
#### 4. Add Bot to Server
1. Open the OAuth2 URL in your browser
2. Select your Discord server
3. Click "Authorize"
4. Complete the CAPTCHA
#### 5. Get Required IDs
Method 1: Developer Mode (Easiest)
1. Open Discord User Settings ā Advanced
2. Enable "Developer Mode"
3. Right-click server name ā "Copy Server ID" (Server ID)
4. Right-click forum channel ā "Copy Channel ID" (Forum Channel ID)
Method 2: Discord API
Use Discord Server Info Bot or similar
$3
#### Option A: Direct in Code (Development)
Edit src/index.ts:
`typescript
import { DCloud } from "./classes/dCloud";
const TOKEN = "MTQxODYyMjg0MDE4NTQyMTgzNg..."; // Bot token
const CHANNEL_ID = "1465235994243502162"; // Forum channel ID
const GUILD_ID = "1316439358609297418"; // Server ID
const dCloud = DCloud({
FORUM_CHANNEL_ID: CHANNEL_ID,
TOKEN: TOKEN,
SERVER_ID: GUILD_ID,
});
await dCloud.init();
`
#### Option B: Environment Variables (Production)
Create .env file:
`bash
DISCORD_TOKEN=YOUR_BOT_TOKEN
DISCORD_SERVER_ID=YOUR_SERVER_ID
DISCORD_FORUM_CHANNEL_ID=YOUR_FORUM_CHANNEL_ID
`
Update src/index.ts:
`typescript
import dotenv from "dotenv";
dotenv.config();
const dCloud = DCloud({
TOKEN: process.env.DISCORD_TOKEN!,
SERVER_ID: process.env.DISCORD_SERVER_ID!,
FORUM_CHANNEL_ID: process.env.DISCORD_FORUM_CHANNEL_ID!,
});
`
$3
Test your configuration:
`bash
npm run dev
`
Expected output:
`
[Bot] [Status]: Logged in as DCloud#1234
[Bot] [Guild]: Connected to Server: MyServer
[Bot] [Channel]: Target Forum: #uploads
`
If you see errors, review the Troubleshooting section.
---
š Usage
$3
`typescript
import { DCloud } from "@discord/dcloud";
const dCloud = DCloud({
FORUM_CHANNEL_ID: "1465235994243502162",
TOKEN: "YOUR_BOT_TOKEN",
SERVER_ID: "1316439358609297418",
});
// Initialize the bot
await dCloud.init();
// Upload a file
const result = await dCloud.upload("C:\\path\\to\\file.zip");
console.log("Upload complete:", result);
`
$3
`typescript
import { DCloud } from "./src/classes/dCloud";
const dCloud = DCloud({
FORUM_CHANNEL_ID: "1465235994243502162",
TOKEN: "YOUR_BOT_TOKEN",
SERVER_ID: "1316439358609297418",
});
// Initialize the bot
await dCloud.init();
// Upload a file
const result = await dCloud.upload("C:\\path\\to\\file.zip");
console.log("Upload complete:", result);
`
`typescript
// Download using metadata URL
await dCloud.downloader(
"https://cdn.discordapp.com/attachments/.../metadata.json",
"C:\\output\\path",
);
console.log("Download and extraction complete!");
`
$3
#### 1. Development Mode (Auto-reload)
`bash
npm run dev
`
Watches for file changes and automatically restarts.
#### 2. Production Mode (Compiled)
`bash
npm run build
npm start
`
Compiles TypeScript to JavaScript and runs it.
#### 3. Type Check Only
`bash
npm run type-check
`
Validates TypeScript without emitting files.
---
š API Documentation
$3
Main class for file upload/download operations.
#### Constructor
`typescript
DCloud(config: ICloudBot): DCloudClass
`
Parameters:
- config.TOKEN: Discord bot token (string)
- config.SERVER_ID: Discord guild/server ID (string)
- config.FORUM_CHANNEL_ID: Target forum channel ID (string)
#### Methods
##### init(): Promise
Initializes the bot and connects to Discord.
`typescript
await dCloud.init();
`
##### upload(filePath: string): Promise
Uploads a file or directory to Discord.
Parameters:
- filePath: Absolute path to file or directory
Returns: Upload result with metadata URL
Example:
`typescript
const result = await dCloud.upload("C:\\files\\mydata.zip");
`
Process Flow:
1. Validates input path
2. Initializes Discord thread with file info
3. Compresses file with LZMA2 (8MB segments)
4. Uploads segments to Discord
5. Generates and uploads metadata.json
6. Cleans up temporary files
7. Returns metadata URL
##### downloader(metadataUrl: string, outputPath: string): Promise
Downloads and restores files from Discord.
Parameters:
- metadataUrl: URL to metadata.json file
- outputPath: Directory to save restored files
Example:
`typescript
await dCloud.downloader(
"https://cdn.discordapp.com/attachments/.../metadata.json",
"C:\\restored\\",
);
`
Process Flow:
1. Fetches metadata.json
2. Creates directory structure
3. Downloads all archive segments
4. Extracts using 7-Zip
5. Cleans up temporary files
6. Completes restoration
$3
Handles Discord bot operations and thread management.
#### Methods
##### Init(): Promise
Initializes the Discord bot connection.
##### IsBotOnline(): boolean
Checks if bot is connected and ready.
$3
#### ICloudBot
`typescript
interface ICloudBot {
TOKEN: string; // Discord bot token
SERVER_ID: string; // Guild/server ID
FORUM_CHANNEL_ID: string; // Forum channel ID
}
`
#### ICompressor
`typescript
interface ICompressor {
originalName: string; // Original file/folder name
totalSize: string; // Size in MB
createdAt: string; // Creation timestamp
parts: {
name: string; // Segment filename
url: string; // Discord CDN URL
}[];
}
`
#### ICompressorResult
`typescript
interface ICompressorResult {
originalName: string; // Original file/folder name
totalSize: string; // Total size in MB
createdAt: string; // Creation timestamp
metadata: string; // Metadata.json URL
}
`
---
š Project Structure
`
DCloud/
āāā src/
ā āāā classes/
ā ā āāā cloudBot.ts # Discord bot management
ā ā āāā dCloud.ts # Main upload/download logic
ā āāā interface/
ā ā āāā index.ts # TypeScript interfaces
ā āāā utils/
ā ā āāā 7zip.ts # 7-Zip compression utilities
ā ā āāā lib.ts # Helper functions
ā āāā index.ts # Entry point & examples
āāā dist/ # Compiled JavaScript (auto-generated)
āāā node_modules/ # Dependencies (auto-generated)
āāā eslint.config.ts # ESLint rules
āāā tsconfig.json # TypeScript configuration
āāā package.json # Dependencies & npm scripts
āāā index.d.ts # Public API type definitions
āāā README.md # This documentation
`
$3
| Directory | Purpose |
| ------------------ | ---------------------------------- |
| src/ | TypeScript source code |
| src/classes/ | Core DCloud and CloudBot classes |
| src/interface/ | Type definitions and interfaces |
| src/utils/ | Utility functions (7-Zip, helpers) |
| dist/ | Compiled JavaScript output |
---
š Scripts & Commands
$3
| Command | Purpose | Usage |
| -------------------- | ------------------------ | -------------------- |
| npm run dev | Start with auto-reload | npm run dev |
| npm run build | Compile TypeScript | npm run build |
| npm run type-check | Check types without emit | npm run type-check |
| npm run lint | Run ESLint | npm run lint |
$3
| Command | Purpose | Note |
| --------------- | ---------------------- | ----------------------------------- |
| npm start | Build and run | Compiles and executes compiled code |
| npm run build | TypeScript compilation | Creates dist/ folder |
$3
`bash
Development workflow
npm install # Install dependencies
npm run dev # Start development server
Before committing
npm run lint # Check code quality
npm run type-check # Verify types
Production deployment
npm run build # Compile code
npm start # Run compiled version
`
---
š§ Development
$3
#### ESLint Configuration
The project uses ESLint with TypeScript support:
`bash
npm run lint
`
Config file: eslint.config.ts
#### TypeScript Validation
Verify types and compilation:
`bash
npm run type-check # Check types without emitting
npm run build # Full compilation to JavaScript
`
$3
1. Write Code: Create TypeScript files in src/
2. Test Locally: Use npm run dev for auto-reload testing
3. Validate: Run npm run type-check to check types
4. Lint: Run npm run lint to check code quality
5. Build: Run npm run build to verify compilation
6. Test Complete Flow: Manually test upload/download
7. Commit: Push changes once verified
$3
#### Step 1: Define Types
Add interfaces to src/interface/index.ts:
`typescript
export interface IMyFeature {
name: string;
value: number;
}
`
#### Step 2: Create Utilities
Add functions to src/utils/:
`typescript
export function myUtility(input: string): string {
return input.toUpperCase();
}
`
#### Step 3: Add Methods
Update classes in src/classes/:
`typescript
public async myMethod(param: string): Promise {
// Implementation
}
`
#### Step 4: Update Public API
Export in index.d.ts:
`typescript
export { myUtility } from "./src/utils/lib";
`
---
š Troubleshooting
$3
Problem: "Could not find server with ID"
Solution:
- Verify your SERVER_ID is correct
- Ensure the bot is invited to the server
- Check bot permissions in server settings
Problem: "Channel ID provided is not a Forum Channel"
Solution:
- Verify you're using a forum channel, not a regular channel
- Right-click the channel in Discord to confirm it's a forum
- Get the correct channel ID
$3
Problem: "File not found at path"
Solution:
- Use absolute paths (e.g., C:\\Users\\...)
- Verify the file exists before uploading
- Check file permissions (must be readable)
Problem: "Bot is not online"
Solution:
- Call await dCloud.init() before uploading
- Verify bot token is correct and still valid
- Check bot permissions in Discord server
$3
Problem: "7-Zip binary not found"
Solutions:
- Reinstall dependencies: npm install
- Ensure 7zip-bin package is properly installed
- On Linux, install p7zip: sudo apt-get install p7zip-full
- On macOS: brew install p7zip
Problem: "Input path does not exist"
Solutions:
- Verify file path is absolute and correct
- Check file permissions (must be readable)
- Use forward slashes or escaped backslashes in paths
$3
Problem: "FATAL ERROR: CALL_AND_RETRY_LAST"
Solutions:
- Increase Node.js memory limit:
`bash
node --max-old-space-size=4096 dist/index.js
`
- Reduce file size being compressed
- Monitor system resources and close unnecessary applications
Problem: Slow uploads to Discord
Solutions:
- Check internet connection speed
- Add delays between uploads: setTimeout(...)
- Use exponential backoff for retries
- Consider uploading during off-peak hours
$3
Problem: "429 Too Many Requests"
Causes: Discord API rate limiting (20 requests/sec per channel)
Solutions:
- Add delays between file uploads
- Implement exponential backoff retry logic:
`typescript
let retries = 0;
while (retries < 3) {
try {
await dCloud.upload(filePath);
break;
} catch (e) {
await new Promise((r) => setTimeout(r, Math.pow(2, retries) * 1000));
retries++;
}
}
`
- Split uploads across multiple bot instances
---
š Performance & Benchmarks
$3
| Metric | Value |
| --------------------- | ----------------------------- |
| Algorithm | LZMA2 with 512MB dictionary |
| Compression Ratio | 40-70% (file type dependent) |
| Speed | ~10-50 MB/min (CPU dependent) |
| Dictionary Size | 512MB (maximum) |
$3
| Metric | Value |
| ---------------------- | ------------------------------------- |
| Discord Rate Limit | 20 requests/sec per channel |
| Typical Speed | 50-200 MB/hour |
| Segment Size | 8MB (safe margin below Discord limit) |
| Bottleneck | Discord API rate limiting |
$3
| Category | Best For | Avoid |
| ------------- | --------------------------------------- | ---------------------------------- |
| Text | Source code, logs, documents | Already compressed files |
| Media | High-quality images, uncompressed video | MP4, JPG, PNG (already compressed) |
| Archives | ZIP/RAR before uploading | Don't double-compress |
| Databases | Raw database files, backups | Encrypted archives |
- Poor for: Already compressed files (zip, mp4, jpg)
---
š Example Workflow
$3
`typescript
import { DCloud } from "./src/classes/dCloud.js";
import fs from "fs";
async function uploadExample() {
const dCloud = DCloud({
TOKEN: process.env.DISCORD_TOKEN || "YOUR_TOKEN",
SERVER_ID: process.env.DISCORD_SERVER_ID || "YOUR_SERVER_ID",
FORUM_CHANNEL_ID: process.env.DISCORD_FORUM_CHANNEL_ID || "YOUR_FORUM_ID",
});
try {
// Step 1: Initialize bot connection
console.log("š¤ Initializing bot...");
await dCloud.init();
// Step 2: Upload file
console.log("š¤ Starting upload...");
const result = await dCloud.upload("C:\\files\\backup.zip");
// Step 3: Display results
console.log("ā
Upload successful!");
console.log(š¦ Name: ${result.originalName});
console.log(š Size: ${result.totalSize});
console.log(š Metadata: ${result.metadata});
// Step 4: Save metadata URL for later
fs.writeFileSync("upload_metadata.json", JSON.stringify(result, null, 2));
console.log("š¾ Metadata saved to upload_metadata.json");
} catch (error) {
console.error("ā Upload failed:", error);
}
}
uploadExample();
`
$3
`typescript
import { DCloud } from "discord-dcloud";
async function downloadExample() {
const dCloud = DCloud({
TOKEN: process.env.DISCORD_TOKEN || "YOUR_TOKEN",
SERVER_ID: process.env.DISCORD_SERVER_ID || "YOUR_SERVER_ID",
FORUM_CHANNEL_ID: process.env.DISCORD_FORUM_CHANNEL_ID || "YOUR_FORUM_ID",
});
try {
// Step 1: Initialize bot
console.log("š¤ Initializing bot...");
await dCloud.init();
// Step 2: Download and restore
console.log("š„ Starting download...");
await dCloud.downloader(
"https://cdn.discordapp.com/attachments/.../metadata.json",
"C:\\restored\\",
);
console.log("ā
Download and extraction complete!");
console.log("š Files restored to C:\\restored\\");
} catch (error) {
console.error("ā Download failed:", error);
}
}
downloadExample();
`
---
š Additional Resources
$3
- Applications
- Bot Documentation
- Gateway Intents
$3
- Discord.js Documentation
- 7-Zip Documentation
- Node.js Child Process
---
š License
This project is marked as private. Please contact the author for licensing information.
---
š¤ Author
Neel Frostrain (@NeelFrostrain)
- GitHub: NeelFrostrain
- Repository: DCloud
---
š¤ Contributing
Contributions are welcome! Here's how to contribute:
1. Fork the repository
2. Create a feature branch: git checkout -b feature/amazing-feature
3. Commit changes: git commit -m 'Add amazing feature'
4. Push to branch: git push origin feature/amazing-feature
5. Open a Pull Request
$3
- Write in TypeScript
- Follow existing code style (use npm run lint)
- Test all changes locally
- Update documentation as needed
- Include meaningful commit messages
---
ā FAQ
$3
Q: Is my data safe on Discord?
A: Data is encrypted via Discord's HTTPS connections. However, Discord can theoretically access encrypted messages. For sensitive data, consider additional encryption.
Q: What's the maximum file size I can upload?
A: Theoretical limit depends on Discord storage. Each bot account can upload ~5GB before approaching limits. Use multiple bot accounts for larger backups.
Q: Can I use multiple bot instances?
A: Yes! You can scale horizontally by deploying multiple bot instances across different Discord servers.
Q: How long do uploaded files stay on Discord?
A: As long as the Discord message exists. Discord stores messages indefinitely unless deleted. Your responsibility is to maintain backup URLs.
$3
Q: Can I use different compression algorithms?
A: Currently, LZMA2 is hardcoded. You can modify src/utils/7zip.ts to support other algorithms (PPMd, BZip2, etc.).
Q: How do I reduce upload time?
A: Options:
1. Compress pre-upload (though files are already compressed)
2. Use multiple bot instances
3. Increase Discord API request limits if possible
4. Optimize network connection
Q: Can I restore files partially?
A: No, the current implementation requires all segments. You must restore complete archives.
Q: Does DCloud support streaming uploads?
A: No, currently uses buffer-based uploads. Streaming support could be added as a future feature.
$3
Q: Bot is not responding?
A: Check:
1. Bot token is correct
2. Bot is invited to server
3. Forum channel exists and bot has access
4. Internet connection is stable
Q: Uploads are very slow?
A: Causes and solutions:
- Network: Check internet speed
- CPU: Compression is CPU-intensive
- Discord Rate Limit: Add delays between uploads
- Large Files: Break into smaller chunks before uploading
Q: Can I cancel an upload in progress?
A: Not gracefully in the current version. You'd need to kill the process. Consider adding cancellation tokens in future versions.
---
š Known Limitations
- ā ļø No partial restoration (must restore entire archives)
- ā ļø Single-threaded uploads (can be optimized)
- ā ļø No built-in encryption (Discord HTTPS provides some protection)
- ā ļø Metadata URLs may expire if Discord messages are deleted
- ā ļø No support for incremental backups (only full backups)
---
š Future Enhancements
Planned features for future versions:
- [ ] Incremental backup support
- [ ] Built-in encryption layer
- [ ] Progress tracking UI
- [ ] Scheduled automatic backups
- [ ] Multi-threaded uploads
- [ ] Compression algorithm selection
- [ ] WebUI dashboard
- [ ] REST API interface
---
š Support
$3
1. Check Troubleshooting section
2. Review existing GitHub Issues
3. Create a new issue with:
- Error message and logs
- Steps to reproduce
- System information (OS, Node.js version)
- DCloud version
$3
When reporting bugs, include:
- Full error stack trace
- Console output
- File/folder being uploaded
- System specifications
---
Made with ā¤ļø for the Discord community
Last Updated: January 27, 2026
Version: 0.1.0
To install dependencies:
`bash
npm install
`
To run:
`bash
npm start
`
---
š Changelog
$3
#### New Features
- Metadata File Attachments: Metadata now sent as metadata.json file attachment instead of message code blocks
- Stream-Based Downloads: Improved memory efficiency for large file downloads
- Dual Metadata Support: Downloader handles both new file-based and legacy metadata formats
#### Improvements
- Refactored upload method with improved error handling and logging
- Added ensureFileReady() helper for reliable file status checking
- Added cleanupFolder() for non-blocking background cleanup
- Improved 7zip compression parameters with precise byte values
- Better error messages and consistent formatting throughout codebase
- Removed axios dependency (migrated to native fetch API)
#### Changes
- Version Bump: 0.0.8 ā 0.1.0
- Breaking Change: initializeNewChannel() now requires inputPath parameter
- Dependencies Removed: axios and all transitive dependencies (axios, follow-redirects, form-data, etc.)
#### Bug Fixes
- Fixed metadata handling in downloader to match Restore() function requirements
- Improved file stability detection before upload
- Better error propagation in async flows
---
š Changelog & Release Notes
$3
#### š New Features
- Metadata File Attachments: Metadata now sent as metadata.json file attachment instead of message code blocks
- More reliable delivery
- Avoids Discord's 2000-character message limit
- Cleaner Discord interface
- Stream-Based Downloads: Improved memory efficiency for large file downloads
- Lower RAM footprint
- Better performance on constrained systems
- Dual Metadata Support: Downloader handles both new file-based and legacy metadata formats
- Seamless transitions between versions
- Backwards compatible
#### ⨠Improvements
- Refactored upload method with improved error handling and logging
- Added ensureFileReady() helper for reliable file status checking
- Polls file every 250ms until stable
- Prevents uploading incomplete files
- Added cleanupFolder() for non-blocking background cleanup
- 2-second delay to release file handles
- Doesn't block function returns
- Improved 7zip compression parameters with precise byte values
- Changed from -v8m to -v8388608 (8MB in bytes)
- More reliable segment sizing
- Better error messages and consistent formatting throughout codebase
- Removed axios dependency (migrated to native fetch API)
- Package size reduced by ~50KB
- Fewer security vulnerabilities
#### ā ļø Breaking Changes
- initializeNewChannel() signature changed
`typescript
// Before
initializeNewChannel(fileName: string)
// After
initializeNewChannel(fileName: string, inputPath: string)
`
Impact: Only if you called this method directly
Workaround: Use upload() method instead (handles it internally)
#### š¦ Dependencies Removed
- axios - HTTP client (replaced with native fetch)
- follow-redirects
- form-data
- asynckit
- combined-stream
- mime-types
- mime-db
#### š Bug Fixes
- Fixed metadata handling in downloader to match Restore() function requirements
- Improved file stability detection before upload
- Better error propagation in async flows
#### š Statistics
| Metric | Value |
| ---------------------- | ----------- |
| Lines Added | 235 |
| Lines Removed | 151 |
| Net Change | +84 lines |
| Files Modified | 7 |
| Compilation Status | ā No errors |
| Package Size Reduction | ~50KB |
---
š§ Technical Details
$3
#### ensureFileReady(filePath: string): Promise
Ensures 7zip has finished writing the file before upload.
`typescript
private async ensureFileReady(filePath: string): Promise {
// Polls every 250ms
// Waits for file size stability (2 consecutive equal sizes)
// Minimum file size: > 0 bytes
}
`
Purpose: Prevent uploading incomplete files
Polling Interval: 250ms
Stability Threshold: 2 consecutive equal file sizes
#### cleanupFolder(folderPath: string): Promise
Removes temporary files without blocking return.
`typescript
private async cleanupFolder(folderPath: string) {
// 2-second delay to release file handles
// Recursive directory removal
// Silent failure (doesn't throw)
}
`
Purpose: Clean up TempOutput directory
Delay: 2 seconds (allows file handles to be released)
Error Handling: Silent failure (cleanup not critical)
$3
Upload Process:
1. Compress files to 8MB segments
2. Upload segments to Discord
3. Create metadata.json with upload metadata
4. Send metadata.json as file attachment
5. Clean up temporary files
Format:
`json
{
"originalName": "filename.ext",
"totalSize": "150.50 MB",
"createdAt": "1/27/2026, 10:30:45 AM",
"parts": [
{
"name": "filename.7z.001",
"url": "https://discord.com/channels/..."
}
]
}
`
$3
1. Parse Metadata: Supports both attachment and legacy formats
2. Create Directory: With proper folder naming
3. Save Metadata: Write to disk (required by Restore)
4. Download Parts: Stream-based using pipeline()
5. Reassemble: Call Restore() with metadata
6. Cleanup: Remove parts and metadata.json
---
š Migration Guide (v0.0.8 ā v0.1.0)
$3
`bash
Update to v0.1.0
npm install
That's it! Your existing code still works
`
$3
If you extended DCloudClass, update any direct calls to initializeNewChannel():
`typescript
// ā Old way (no longer works)
const thread = await dcloud.initializeNewChannel(filename);
// ā
New way
const thread = await dcloud.initializeNewChannel(filename, filepath);
// ā
Alternative (recommended)
const result = await dcloud.upload(filepath);
`
$3
- Old Format: metadata.json code block in Discord message
- New Format: metadata.json file attachment
- Downloads: Both formats supported automatically ā
---
ā
Testing Recommendations
$3
- [ ] ensureFileReady() with different file sizes
- [ ] cleanupFolder() with missing files
- [ ] Metadata serialization/deserialization
$3
- [ ] Upload small file (< 8MB)
- [ ] Upload medium file (50-100MB)
- [ ] Upload folder with multiple files
- [ ] Download with new metadata format
- [ ] Download with legacy metadata format
- [ ] Partial failure recovery
$3
- [ ] File locked by another process
- [ ] Disk space exhausted
- [ ] Discord API rate limiting
- [ ] Network interruption during upload
- [ ] Corrupted metadata.json
---
š”ļø Security Notes
$3
- ā
No breaking security changes
- ā
Removed axios (fewer dependencies = smaller attack surface)
- ā
Native fetch API used (built-in security)
$3
- Keep bot token in .env file
- Don't commit sensitive credentials
- Use Discord OAuth2 for production deployments
- Regularly update dependencies
---
š Troubleshooting
$3
Problem: "Metadata message was null"
- Cause: Discord API error when sending message
- Solution: Check bot permissions, Discord API status
Problem: "File not found at path"
- Cause: Input path doesn't exist or is inaccessible
- Solution: Verify path exists and is readable
Problem: "7zip binary not found"
- Cause: 7zip-bin not properly installed
- Solution: Reinstall: npm install --save 7zip-bin
Problem: "No parts were generated"
- Cause: Compression failed or produced no output
- Solution: Check file permissions, available disk space
$3
Enable detailed logging:
`typescript
const dcloud = DCloud({
TOKEN: "your-token",
SERVER_ID: "your-server",
FORUM_CHANNEL_ID: "your-channel",
});
// All errors logged with chalk colors
// Check console for detailed output
`
---
š API Documentation
$3
#### DCloudClass
Main class for file operations.
`typescript
constructor(config: ICloudBot)
`
Methods:
- init(): Promise - Initialize bot connection
- upload(inputPath: string): Promise - Upload file/folder
- downloader(messageLink: string, output: string): Promise - Download file
#### CloudBotClass
Handles Discord bot operations.
`typescript
extends Client
`
Methods:
- Init(): Promise - Login to Discord
- IsBotOnline(): boolean - Check connection status
- initializeNewThread(name: string, msg: EmbedBuilder): Promise - Create forum thread
- sendToForumChannel(filePath: string, fileName: string): Promise - Upload file to thread
$3
`typescript
interface ICloudBot {
TOKEN: string;
SERVER_ID: string;
FORUM_CHANNEL_ID: string;
}
interface ICompressor {
originalName: string;
totalSize: string;
createdAt: string;
parts: Array<{ name: string; url: string }>;
}
interface ICompressorResult {
originalName: string;
totalSize: string;
createdAt: string;
metadata: string;
}
`
---
š Learning Resources
$3
1. Read the Quick Start section
2. Review Features
3. Check Configuration
$3
1. Understand Project Structure
2. Review API Documentation
3. Explore source code in src/
$3
1. Read the Development section
2. Review Technical Details
3. Run tests before submitting PRs
---
š¤ Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests and linting
5. Submit a pull request
$3
`bash
Install dependencies
npm install
Development mode (with auto-reload)
npm run dev
Build
npm run build
Lint code
npm run lint
Type check
npm run type-check
Run compiled version
npm start
``