When building Telegram bots with grammY, it is natural to expect that a media album arrives as a single message.
In reality, Telegram works differently.
If a user sends an album with multiple photos or videos, your bot receives multiple separate update events instead of one complete post.
For example:
update #1 -> photo_1
update #2 -> photo_2
update #3 -> photo_3
instead of:
single_post -> [photo_1, photo_2, photo_3]
This quickly creates several annoying problems:
- duplicate database records
- race conditions
- buffering logic
- ordering issues
- timeout handling
At first, handling this manually may seem simple.
Usually the implementation starts with something like this:
const mediaGroups = new Map();
// buffering
// sorting
// cleanup
// timeout handling
But once Redis, multiple workers, or production traffic enter the picture, the logic becomes much more complicated.
The Solution
Install the library telegram-media — a TypeScript library for Node.js that collects Telegram media groups into a single normalized object.
Installation
npm install telegram-media
grammY Example
import { Bot } from "grammy";
import {
createRedisMediaGroupStorage,
createTelegramMediaGroup,
} from "telegram-media";
const bot = new Bot(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.start();
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)