When building Telegram bots with Telegraf, it is easy to expect that a media album arrives as a single message.
In reality, Telegram sends every media item as a separate update.
For example, if a user sends an album with 3 photos, your bot receives:
update #1 -> photo_1
update #2 -> photo_2
update #3 -> photo_3
instead of:
single_post -> [photo_1, photo_2, photo_3]
This creates several annoying production problems:
duplicate database records
race conditions
buffering logic
ordering issues
timeout handling
At first, the solution usually starts with something simple:
const mediaGroups = new Map();
// buffering
// sorting
// cleanup
// timeout handling
But once Redis, multiple workers, or higher traffic enter the picture, the logic becomes much harder to maintain.
The Solution
I built telegram-media — a TypeScript library for Node.js that collects Telegram media groups into a single normalized object.
Installation
npm install telegram-media
Telegraf Example
import { Telegraf } from "telegraf";
import {
createRedisMediaGroupStorage,
createTelegramMediaGroup,
} from "telegram-media";
const bot = new Telegraf(process.env.BOT_TOKEN!);
const collector = createTelegramMediaGroup({
storage: createRedisMediaGroupStorage(redisClient),
timeoutMs: 3000,
supportedMediaTypes: ["photo", "video", "audio"],
async onCollected(post) {
console.log("Collected media group:", post);
},
});
bot.on("message", async (ctx) => {
await collector.collect(ctx.update);
});
bot.launch();
Why This Helps?
Instead of manually buffering Telegram updates, the collector:
groups related media automatically
preserves media ordering
prevents duplicate processing
works with Redis
returns a single normalized post object
Features
Media group aggregation
Redis support
Duplicate prevention
Media ordering
Configurable timeout
TypeScript support
Links
npm: https://www.npmjs.com/package/telegram-media
GitHub: https://github.com/NikitosIT/telegram-media
Top comments (0)