grammy-media-group
v1.0.4
Published
Middleware and utilities for handling and grouping media messages (photos, videos) in grammY bots, enabling easy processing of media groups.
Downloads
418
Maintainers
Readme
MediaGroup Middleware for grammY
A lightweight middleware for grammY Telegram bots that collects and groups media messages (like photos and videos) into a single media_group context property. This makes it easier to handle albums using a simple timeout-based strategy.
✨ Features
- 🖼️ Handles both photos and videos (albums)
- 🧩 Provides a
mediaGroupfilter for a clean handler withbot.filter() - 🧩 Provides
copyMediaGroupfunction to copy media groups - ✅ Type-safe with TypeScript support
📦 Installation
npm install grammy-media-group🚀 Usage
1. Setup (ESM / TypeScript)
import { Bot } from "grammy";
import { MediaGroupHandler, mediaGroup } from "grammy-media-group";
const bot = new Bot("<BOT_TOKEN>");
const mediaGroupHandler = new MediaGroupHandler(4000); // optional timeout in ms
bot.use(mediaGroupHandler.middleware());1. Setup (CommonJS)
const { Bot } = require("grammy");
const { MediaGroupHandler, mediaGroup } = require("grammy-media-group");
const bot = new Bot("<BOT_TOKEN>");
const mediaGroupHandler = new MediaGroupHandler(4000); // optional timeout in ms
bot.use(mediaGroupHandler.middleware());2. Handle Media Groups
This example shows how to use the mediaGroup filter to detect incoming media groups. When a media group is detected, the handler/middleware processes the grouped media files.
bot.filter(mediaGroup, async (ctx) => {
const media = ctx.media_group;
console.log(media.length); // outputs the media group (album) length
// handle the media group...
});📋 Copying a Media Group
You can use the copyMediaGroup utility function to copy a received media group, or copy it directly from the context into a format ready to be sent. This is useful if you want to resend an album with a custom caption or formatting.
// Import if you don't want to copy it directly from the context
import { copyMediaGroup } from "grammy-media-group";
// Or require if you are using CommonJS
const { copyMediaGroup } = require("grammy-media-group");
bot.filter(mediaGroup, async (ctx) => {
// You can pass an optional options object to customize caption
// and formatting
const copiedMediaGroup = copyMediaGroup(ctx.media_group, {
caption: "<b>Here's the album!</b>",
parse_mode: "HTML"
});
// Or you can also copy the media group directly from the context
// and pass the optional options object there as well
const copiedMediaGroup = ctx.copyMediaGroup({
caption: "<b>Here's the album!</b>",
parse_mode: "HTML"
});
// Then you are ready to send the copied media group
await ctx.api.sendMediaGroup(ctx.chat.id, copiedMediaGroup);
});⚠️ Notes
- Note: This workaround may be unreliable or imprecise, as it relies on a timeout to determine when a media group is complete, which may lead to inaccuracies in cases of delayed or dropped messages.
