Sending Images & VideosAutomatically in Telegram
Master automated image and video delivery in Telegram with perfect bot setup, smart compression optimization, format handling, and efficient batch processing strategies for seamless media workflows.

Bot Setup & Configuration
Setting up your Telegram bot for media automation requires proper API configuration, endpoint setup, and handling for different media types. Follow this comprehensive setup process for optimal performance.
Basic Bot Creation & API Setup
Create your bot and configure the essential API endpoints for media sending.
- 1Message @BotFather on Telegram and use /newbot command
- 2Choose a unique name and username for your media bot
- 3Save the bot token securely (format: 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11)
- 4Test API access with a simple sendMessage call
- 5Configure webhook or polling based on your infrastructure needs
Media API Endpoints Configuration
Set up the specific endpoints for different media types and processing workflows.
- 1Configure sendPhoto endpoint for compressed image sending
- 2Set up sendVideo endpoint for video delivery with automatic compression
- 3Implement sendDocument for uncompressed media files
- 4Configure sendMediaGroup for album/batch sending (up to 10 media items)
- 5Add error handling for file size limits and unsupported formats
Infrastructure & Performance Setup
Optimize your bot infrastructure for high-volume media processing and delivery.
- 1Set up proper rate limiting (20 messages/minute, 30 messages/second to groups)
- 2Configure file upload/download mechanisms with resume capability
- 3Implement queue system for batch media processing
- 4Add monitoring and logging for delivery success/failure tracking
- 5Set up CDN integration for faster media delivery (optional)
Image Formats & Optimization
Understanding Telegram's image handling is crucial for optimal delivery. Different formats have different compression behaviors, size limits, and use cases.
Supported Image Formats
JPEG/JPG
Best for photos with good compression ratio
PNG
Ideal for graphics, logos, transparency
WebP
Modern format, excellent compression
GIF
Animated images, simple graphics
Compression Optimization
- Pre-compress images to 1920x1080 for photos
- Use WebP format for 25-35% smaller file sizes
- Send as document to preserve original quality
- Optimize JPEG quality to 85-90% for best balance
Common Pitfalls
- PNG transparency lost when sent as photo
- Large images auto-compressed, reducing quality
- HEIC/HEIF formats not supported natively
- Animated GIFs may lose frames with compression
Video Processing & Compression
Telegram provides excellent video handling capabilities with automatic compression, format conversion, and streaming support. Learn how to optimize your video delivery for the best user experience.
Video Format Support & Optimization
MP4 (H.264)
Most compatible, automatic compression
AVI
Older format, larger file sizes
MOV
Apple format, good quality
WebM
Modern web format, excellent compression
Video Optimization Tips
- Use H.264 codec for best compatibility
- Aim for 1080p or lower resolution
- Keep bitrate under 2 Mbps for faster upload
- Use AAC audio codec for better compression
- Pre-generate thumbnails for faster preview
FFmpeg Compression Script
# Optimize video for Telegram ffmpeg -i input.mp4 \ -c:v libx264 \ -preset medium \ -crf 23 \ -maxrate 2M \ -bufsize 4M \ -vf "scale=1920:1080:force_original_aspect_ratio=decrease" \ -c:a aac \ -b:a 128k \ output.mp4
Batch Processing & Media Albums
Telegram's sendMediaGroup endpoint allows you to send up to 10 images or videos as a single album. This is perfect for batch processing and creating cohesive media presentations.
Media Album Implementation
Album Structure
// Media group array structure
const mediaGroup = [
{
type: 'photo',
media: 'attach://photo1',
caption: 'First image caption'
},
{
type: 'video',
media: 'attach://video1',
caption: 'Video description'
},
{
type: 'photo',
media: 'attach://photo2'
}
];Best Practices
- Maximum 10 media items per album
- Mix photos and videos in same album
- Only first item can have caption
- Use consistent aspect ratios
Code Examples
Python Implementation
import requests
import os
from pathlib import Path
class TelegramMediaBot:
def __init__(self, token):
self.token = token
self.base_url = f"https://api.telegram.org/bot{token}"
def send_image(self, chat_id, image_path, caption=None, as_document=False):
"""Send image with optional compression control"""
endpoint = "sendDocument" if as_document else "sendPhoto"
file_field = "document" if as_document else "photo"
with open(image_path, 'rb') as photo:
files = {file_field: photo}
data = {'chat_id': chat_id}
if caption:
data['caption'] = caption
response = requests.post(f"{self.base_url}/{endpoint}",
files=files, data=data)
return response.json()
def send_video(self, chat_id, video_path, caption=None, duration=None):
"""Send video with optional metadata"""
with open(video_path, 'rb') as video:
files = {'video': video}
data = {'chat_id': chat_id}
if caption:
data['caption'] = caption
if duration:
data['duration'] = duration
response = requests.post(f"{self.base_url}/sendVideo",
files=files, data=data)
return response.json()
def send_media_album(self, chat_id, media_files):
"""Send multiple media files as album"""
media_group = []
files = {}
for i, (file_path, media_type, caption) in enumerate(media_files):
attach_name = f"media{i}"
files[attach_name] = open(file_path, 'rb')
media_item = {
'type': media_type, # 'photo' or 'video'
'media': f'attach://{attach_name}'
}
if caption and i == 0: # Only first item can have caption
media_item['caption'] = caption
media_group.append(media_item)
data = {
'chat_id': chat_id,
'media': str(media_group).replace("'", '"')
}
try:
response = requests.post(f"{self.base_url}/sendMediaGroup",
files=files, data=data)
return response.json()
finally:
# Close all file handles
for file_handle in files.values():
file_handle.close()
# Usage example
bot = TelegramMediaBot(os.environ['BOT_TOKEN'])
chat_id = os.environ['CHAT_ID']
# Send single image
bot.send_image(chat_id, 'photo.jpg', 'Beautiful sunset! 🌅')
# Send video
bot.send_video(chat_id, 'video.mp4', 'Check out this demo!', duration=30)
# Send media album
media_files = [
('image1.jpg', 'photo', 'Album caption here'),
('video1.mp4', 'video', None),
('image2.png', 'photo', None)
]
bot.send_media_album(chat_id, media_files)Node.js Implementation
import fs from 'fs';
import FormData from 'form-data';
import fetch from 'node-fetch';
class TelegramMediaBot {
constructor(token) {
this.token = token;
this.baseUrl = `https://api.telegram.org/bot${token}`;
}
async sendImage(chatId, imagePath, caption = null, asDocument = false) {
const endpoint = asDocument ? 'sendDocument' : 'sendPhoto';
const fieldName = asDocument ? 'document' : 'photo';
const form = new FormData();
form.append('chat_id', chatId);
form.append(fieldName, fs.createReadStream(imagePath));
if (caption) form.append('caption', caption);
const response = await fetch(`${this.baseUrl}/${endpoint}`, {
method: 'POST',
body: form
});
return response.json();
}
async sendVideo(chatId, videoPath, caption = null, options = {}) {
const form = new FormData();
form.append('chat_id', chatId);
form.append('video', fs.createReadStream(videoPath));
if (caption) form.append('caption', caption);
if (options.duration) form.append('duration', options.duration);
if (options.width) form.append('width', options.width);
if (options.height) form.append('height', options.height);
const response = await fetch(`${this.baseUrl}/sendVideo`, {
method: 'POST',
body: form
});
return response.json();
}
async sendMediaAlbum(chatId, mediaFiles) {
const form = new FormData();
const mediaGroup = [];
mediaFiles.forEach((file, index) => {
const attachName = `media${index}`;
form.append(attachName, fs.createReadStream(file.path));
const mediaItem = {
type: file.type, // 'photo' or 'video'
media: `attach://${attachName}`
};
if (file.caption && index === 0) {
mediaItem.caption = file.caption;
}
mediaGroup.push(mediaItem);
});
form.append('chat_id', chatId);
form.append('media', JSON.stringify(mediaGroup));
const response = await fetch(`${this.baseUrl}/sendMediaGroup`, {
method: 'POST',
body: form
});
return response.json();
}
}
// Usage example
const bot = new TelegramMediaBot(process.env.BOT_TOKEN);
const chatId = process.env.CHAT_ID;
// Send optimized image
await bot.sendImage(chatId, './optimized-photo.webp', 'Auto-compressed image 📸');
// Send high-quality video
await bot.sendVideo(chatId, './demo-video.mp4', 'Product demo video', {
duration: 45,
width: 1920,
height: 1080
});
// Send media album
const mediaFiles = [
{ path: './image1.jpg', type: 'photo', caption: 'Album showcase' },
{ path: './video1.mp4', type: 'video' },
{ path: './image2.png', type: 'photo' }
];
await bot.sendMediaAlbum(chatId, mediaFiles);Advanced Media Features
Scheduled Media
Combine media sending with scheduling for automated campaigns.
- • Time-based media delivery
- • Recurring image/video posts
- • Timezone-aware scheduling
- • Campaign automation
Smart Compression
Automatically optimize media based on content type and target quality.
- • Content-aware compression
- • Format conversion automation
- • Quality vs size optimization
- • Batch processing pipelines
Performance Optimization
Maximize delivery speed and reliability with advanced techniques.
- • Parallel upload processing
- • CDN integration strategies
- • Retry logic implementation
- • Progress tracking systems
Practical Implementation Examples
Bash Script for Bulk Image Sending
#!/bin/bash
# bulk-image-sender.sh
BOT_TOKEN="YOUR_BOT_TOKEN"
CHAT_ID="YOUR_CHAT_ID"
IMAGE_DIR="./images"
# Function to send single image
send_image() {
local image_path="$1"
local caption="$2"
curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendPhoto" \
-F chat_id="$CHAT_ID" \
-F photo="@$image_path" \
-F caption="$caption"
}
# Send all images in directory
for image in "$IMAGE_DIR"/*.{jpg,jpeg,png,webp}; do
if [[ -f "$image" ]]; then
filename=$(basename "$image")
echo "Sending: $filename"
send_image "$image" "Auto-sent: $filename"
sleep 2 # Rate limiting
fi
done
echo "Bulk image sending completed!"Advanced Python Bot with Error Handling
import asyncio
import aiohttp
import aiofiles
from pathlib import Path
import logging
class AdvancedMediaBot:
def __init__(self, token):
self.token = token
self.base_url = f"https://api.telegram.org/bot{token}"
self.session = None
async def __aenter__(self):
self.session = aiohttp.ClientSession()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.session:
await self.session.close()
async def send_media_with_retry(self, endpoint, data, files, max_retries=3):
"""Send media with exponential backoff retry"""
for attempt in range(max_retries):
try:
async with self.session.post(f"{self.base_url}/{endpoint}",
data=data, files=files) as response:
result = await response.json()
if response.status == 200:
return result
elif response.status == 429: # Rate limited
retry_after = int(response.headers.get('Retry-After', 1))
logging.warning(f"Rate limited, waiting {retry_after}s")
await asyncio.sleep(retry_after)
else:
logging.error(f"API error: {result}")
except Exception as e:
logging.error(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
await asyncio.sleep(2 ** attempt) # Exponential backoff
return None
async def bulk_send_images(self, chat_id, image_dir, batch_size=5):
"""Send images in batches with rate limiting"""
image_paths = list(Path(image_dir).glob('*.{jpg,jpeg,png,webp}'))
for i in range(0, len(image_paths), batch_size):
batch = image_paths[i:i + batch_size]
tasks = []
for image_path in batch:
task = self.send_image_async(chat_id, str(image_path),
f"Auto-sent: {image_path.name}")
tasks.append(task)
# Process batch concurrently
results = await asyncio.gather(*tasks, return_exceptions=True)
# Log results
for path, result in zip(batch, results):
if isinstance(result, Exception):
logging.error(f"Failed to send {path.name}: {result}")
else:
logging.info(f"Successfully sent {path.name}")
# Rate limiting between batches
if i + batch_size < len(image_paths):
await asyncio.sleep(2)
# Usage
async def main():
async with AdvancedMediaBot(os.environ['BOT_TOKEN']) as bot:
await bot.bulk_send_images(os.environ['CHAT_ID'], './media/images')
asyncio.run(main())Performance & Optimization Tips
Speed Optimization
- Pre-process and compress media before sending
- Use async/await for concurrent uploads
- Implement connection pooling for multiple requests
- Cache frequently sent media files
- Use WebP format for smaller file sizes
Rate Limiting & Best Practices
- Max 20 messages per minute to same chat
- Max 30 messages per second to different chats
- Add 1-2 second delays between bulk sends
- Handle 429 Too Many Requests gracefully
- Monitor bot performance and delivery rates
Frequently Asked Questions
What image formats does Telegram support?▼
Telegram supports JPEG, PNG, WebP, and GIF formats for images. JPEG and WebP offer the best compression. PNG is ideal for graphics with transparency.
What's the maximum file size for images and videos?▼
Images can be up to 10MB as photos (with compression) or 2GB as documents. Videos can be up to 2GB and are automatically compressed unless sent as documents.
How can I preserve original image quality?▼
Send images as documents instead of photos to avoid Telegram's automatic compression. Use the sendDocument API endpoint with the image file.
Can I send multiple images at once?▼
Yes, use the sendMediaGroup API endpoint to send up to 10 images or videos as an album. This is perfect for batch processing workflows.
How do I handle video compression automatically?▼
Telegram automatically compresses videos sent as videos. For original quality, send as documents. You can also pre-compress with FFmpeg before sending.
Start Your Media Automation Today
Join thousands of developers who have streamlined their Telegram media workflows. Start with images and videos, then expand to complete automation campaigns.