DEV Community

Nikita Zavada
Nikita Zavada

Posted on

How to Handle Telegram Albums in grammY

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]
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Why This Helps

Instead of manually buffering Telegram updates, the collector:

Top comments (0)