Sending Documents via Telegram Bot
Master automated document delivery with PDFs, Word, Excel files using Telegram Bot API
Supported Document Types
Telegram Bot API supports a wide range of document formats for automated delivery. Each file type has specific handling requirements and optimization strategies for best performance.
PDF Documents
Max: 2GB
Portable Document Format files maintain formatting across platforms.
Microsoft Office
Max: 2GB
Word, Excel, PowerPoint files for business communication.
Data & Archives
Max: 2GB
Compressed files and data formats for bulk distribution.
Document Automation Benefits
- Instant document delivery at scale
- Preserve original formatting and quality
- Automated business report distribution
- Secure file sharing with tracking
Bot Setup & API Configuration
1. Create Document Bot
Setup Bot with BotFather
# Create bot for document automation 1. Message @BotFather in Telegram 2. Send: /newbot 3. Bot name: "Document Delivery Bot" 4. Username: "your_document_bot" 5. Save token: 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
Configure Bot Permissions
# Essential bot commands for document handling /setcommands to @BotFather send_pdf - Send PDF document send_doc - Send Office document send_file - Send any file type list_files - View available documents help - Get usage instructions
2. API Endpoint Configuration
sendDocument API Method
POST https://api.telegram.org/bot<TOKEN>/sendDocument Required Parameters: - chat_id: Target chat or user ID - document: File to send (multipart/form-data or file_id) Optional Parameters: - caption: Document description (up to 1024 characters) - parse_mode: HTML or Markdown formatting - reply_to_message_id: Reply to specific message - disable_notification: Silent sending
Implementation Guide
Node.js Implementation
const FormData = require('form-data');
const fs = require('fs');
const fetch = require('node-fetch');
async function sendDocument(chatId, filePath, caption) {
const form = new FormData();
form.append('chat_id', chatId);
form.append('document', fs.createReadStream(filePath));
form.append('caption', caption);
const response = await fetch(
`https://api.telegram.org/bot${BOT_TOKEN}/sendDocument`,
{ method: 'POST', body: form }
);
return response.json();
}
// Usage example
await sendDocument(
'123456789',
'./reports/monthly_report.pdf',
'📊 Monthly Sales Report - August 2025'
);Python Implementation
import requests
import os
def send_document(chat_id, file_path, caption=""):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
with open(file_path, 'rb') as file:
files = {'document': file}
data = {
'chat_id': chat_id,
'caption': caption,
'parse_mode': 'HTML'
}
response = requests.post(url, files=files, data=data)
return response.json()
# Usage example
result = send_document(
chat_id='123456789',
file_path='./docs/invoice_2025_08.pdf',
caption='🧾 <b>Invoice #2025-08-001</b>\nPayment due: Sept 15'
)Batch Document Sending
// Advanced batch processing with rate limiting
class DocumentBatchSender {
constructor(botToken) {
this.botToken = botToken;
this.queue = [];
this.processing = false;
this.rateLimitDelay = 1000; // 1 second between requests
}
addToQueue(chatId, filePath, caption) {
this.queue.push({ chatId, filePath, caption });
if (!this.processing) this.processQueue();
}
async processQueue() {
this.processing = true;
while (this.queue.length > 0) {
const { chatId, filePath, caption } = this.queue.shift();
try {
await this.sendDocument(chatId, filePath, caption);
console.log(`✅ Sent: ${filePath} to ${chatId}`);
} catch (error) {
console.error(`❌ Failed: ${filePath}`, error);
// Implement retry logic here
}
// Rate limiting delay
await new Promise(resolve => setTimeout(resolve, this.rateLimitDelay));
}
this.processing = false;
}
}Performance & Optimization
File Size Optimization
- •Use file_id Caching: Store file_id after first upload to avoid re-uploading
- •Concurrent Uploads: Send to multiple chats simultaneously with proper rate limiting
- •CDN Integration: Pre-upload to Telegram servers, then use file_id for instant delivery
- •Queue Management: Process documents in background queues to avoid blocking
File ID Caching Strategy
// Efficient file caching system
class TelegramFileCache {
constructor() {
this.cache = new Map(); // In production, use Redis/Database
}
async sendCachedDocument(chatId, filePath, caption) {
const cacheKey = `file:${filePath}`;
let fileId = this.cache.get(cacheKey);
if (!fileId) {
// First time upload - store file_id for future use
const result = await this.uploadDocument(chatId, filePath, caption);
fileId = result.document.file_id;
this.cache.set(cacheKey, fileId);
return result;
} else {
// Use cached file_id for instant delivery
return this.sendByFileId(chatId, fileId, caption);
}
}
async sendByFileId(chatId, fileId, caption) {
const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendDocument`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
document: fileId,
caption: caption
})
});
return response.json();
}
}Best Practices
✅ Do's
- ✓ Validate file existence before sending
- ✓ Add meaningful captions with metadata
- ✓ Implement progress tracking for large files
- ✓ Use thumbnail generation for document previews
- ✓ Log successful deliveries with timestamps
- ✓ Sanitize filenames to avoid conflicts
❌ Don'ts
- ✗ Send documents without user consent
- ✗ Ignore file size limits (2GB max)
- ✗ Upload same file repeatedly without caching
- ✗ Send sensitive documents without encryption
- ✗ Block main thread during large uploads
- ✗ Forget to handle API rate limits
Specific Document Type Handling
📄 PDF Documents
Best Practices
- • Keep file size under 50MB for fast delivery
- • Add descriptive captions with page count
- • Use PDF/A format for long-term archival
- • Generate thumbnails for preview
Code Example
// PDF with metadata await sendDocument(chatId, 'report.pdf', '📋 <b>Q3 Financial Report</b>\n' + '📅 Period: Jul-Sep 2025\n' + '📊 Pages: 24 | Size: 2.1MB' );
📊 Excel & Office Files
Optimization Tips
- • Use .xlsx format for better compression
- • Remove unused worksheets and data
- • Compress embedded images and charts
- • Include sheet count in caption
Code Example
// Excel with details await sendDocument(chatId, 'sales_data.xlsx', '📈 <b>Sales Dashboard</b>\n' + '🗓️ Updated: Aug 24, 2025\n' + '📋 Sheets: 5 | Records: 1,247' );
🗜️ Archives & Compressed Files
Archive Strategies
- • Use ZIP for multiple related documents
- • Password protect sensitive archives
- • Include manifest/readme files
- • Test archive integrity before sending
Code Example
// Archive with inventory await sendDocument(chatId, 'project_files.zip', '📦 <b>Project Package</b>\n' + '📁 Contains: 12 files\n' + '🔐 Password: proj2025' );
Advanced Document Automation
Dynamic Document Generation & Sending
const PDFDocument = require('pdfkit');
const fs = require('fs');
async function generateAndSendReport(chatId, data) {
const filename = `report_${Date.now()}.pdf`;
const doc = new PDFDocument();
// Generate PDF with dynamic data
doc.pipe(fs.createWriteStream(filename));
doc.fontSize(20).text('Sales Report', 100, 100);
doc.fontSize(12).text(`Generated: ${new Date().toLocaleDateString()}`, 100, 130);
// Add data tables, charts, etc.
data.forEach((item, index) => {
doc.text(`${item.name}: ${item.value}`, 100, 160 + (index * 20));
});
doc.end();
// Wait for PDF generation to complete
return new Promise((resolve) => {
doc.on('end', async () => {
// Send generated document
const result = await sendDocument(
chatId,
filename,
`📊 <b>Automated Report</b>\n🕐 Generated: ${new Date().toLocaleString()}`
);
// Clean up temporary file
fs.unlinkSync(filename);
resolve(result);
});
});
}📋 Document Templates
Create reusable document templates for automated generation.
- • Invoice templates with dynamic data
- • Report templates with charts
- • Certificate generation
- • Contract automation
🔄 Scheduled Document Delivery
Combine with scheduling for automated document distribution.
- • Daily reports at 9 AM
- • Weekly summaries on Friday
- • Monthly invoices on 1st
- • Event-triggered documents
Frequently Asked Questions
What's the maximum file size for documents in Telegram?▼
Telegram supports up to 2GB file size for documents. Files are automatically compressed for faster delivery but maintain their original format.
Can I send password-protected documents?▼
Yes, Telegram can send password-protected files. However, recipients will need the password to open them. The bot doesn't decrypt files.
How to maintain document quality during automation?▼
Use sendDocument API method instead of sendPhoto for PDFs/documents. This preserves the original file without compression.
Can I track document delivery status?▼
Yes, the Telegram Bot API returns message_id and delivery confirmation. You can store these for tracking and analytics.
How to handle large batch document sends?▼
Implement rate limiting (20 messages/minute to groups, 30/second to individual users) and use queue systems for large batches.
Ready to automate document delivery?
Start sending PDFs, Excel files, and documents automatically. Scale your business communication with intelligent file management.