### Combined Middleware Usage Example Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt Demonstrates the combined usage of various grammy-middlewares, including `ignoreOld`, `onlyAdmin`, `onlyPublic`, `onlySuperAdmin`, and `sequentialize`. This example showcases global middleware application and command-specific middleware composition for robust bot logic. ```typescript import { Bot } from 'grammy' import { run } from '@grammyjs/runner' import { ignoreOld, onlyAdmin, onlyPublic, onlySuperAdmin, sequentialize } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) const SUPER_ADMIN_ID = Number(process.env.SUPER_ADMIN_ID) // Global middlewares - apply to all updates bot.use( ignoreOld(300), // Ignore messages older than 5 minutes sequentialize() // Ensure sequential processing per chat ) // Public group commands with admin restriction bot.command('kick', onlyPublic((ctx) => ctx.reply('Use this command in a group')), onlyAdmin((ctx) => ctx.reply('Only admins can kick users')), async (ctx) => { const userId = ctx.message?.reply_to_message?.from?.id if (userId) { await ctx.banChatMember(userId) await ctx.unbanChatMember(userId) ctx.reply('User has been kicked.') } } ) // Super admin only commands bot.command('stats', onlySuperAdmin(SUPER_ADMIN_ID), (ctx) => { ctx.reply('Bot statistics: ...') }) run(bot) ``` -------------------------------- ### Using Grammy Middlewares Source: https://github.com/backmeupplz/grammy-middlewares/blob/main/README.md Demonstrates how to import and apply various middlewares from the 'grammy-middlewares' package to a grammY bot instance. It shows the usage of ignoreOld, onlyAdmin, onlyPublic, onlySuperAdmin, and sequentialize. The onlyMenuAuthor middleware is also shown in the context of a menu. ```typescript import { ignoreOld, onlyAdmin, onlyPublic, onlySuperAdmin, sequentialize, } from 'grammy-middlewares' // ... bot setup ... bot.use( ignoreOld(), onlyAdmin(ctx => ctx.reply( 'Only admins can do this' )), onlyPublic(ctx => ctx.reply( 'You can only use public chats' )), onlySuperAdmin(env.SUPER_ADMIN_ID), sequentialize() ) // ... menu setup ... menu.text( 'Only menu creator', onlyMenuAuthor(ctx => ctx.reply('Only menu creator can do this') ), ctx => ... ) ``` -------------------------------- ### Sequential Update Processing with `sequentialize` Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt Ensures that updates from the same chat are processed one at a time to prevent race conditions, especially when using grammY's runner for concurrent update processing. This middleware is applied globally using `bot.use()`. ```typescript import { Bot } from 'grammy' import { run } from '@grammyjs/runner' import { sequentialize } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) // Apply sequentialize before other middleware when using runner bot.use(sequentialize()) // These handlers are now safe from race conditions within the same chat bot.on('message', async (ctx) => { // Updates from the same chat are processed one at a time // Updates from different chats can still run concurrently const count = await incrementMessageCount(ctx.chat.id) if (count % 100 === 0) { ctx.reply(`This chat has reached ${count} messages!`) } }) // Use runner for concurrent processing with sequential safety run(bot) ``` -------------------------------- ### Menu Interaction Restriction with `onlyMenuAuthor` Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt Restricts menu interactions to only the user who initially triggered the menu. This is crucial for preventing unauthorized users from interacting with menus not intended for them. The menu must reply to the original message for this middleware to function correctly. ```typescript import { Bot } from 'grammy' import { Menu } from '@grammyjs/menu' import { onlyMenuAuthor } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) const settingsMenu = new Menu('settings') .text('Option 1', onlyMenuAuthor((ctx) => { ctx.answerCallbackQuery('Only the person who opened this menu can use it!') }), (ctx) => { ctx.reply('You selected Option 1') }) .text('Option 2', onlyMenuAuthor((ctx) => { ctx.answerCallbackQuery('This menu belongs to someone else!') }), (ctx) => { ctx.reply('You selected Option 2') }) bot.use(settingsMenu) bot.command('settings', async (ctx) => { // Reply to the user's command - this is required for onlyMenuAuthor to work await ctx.reply('Choose a setting:', { reply_to_message_id: ctx.message?.message_id, reply_markup: settingsMenu }) }) bot.start() ``` -------------------------------- ### Ignore Old Messages Middleware for grammY Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt The `ignoreOld` middleware filters out messages older than a specified threshold, preventing the bot from processing stale updates. It defaults to 5 minutes but can be configured with a custom duration in seconds. This is useful for bots that might go offline and need to avoid backlog processing. ```typescript import { Bot } from 'grammy' import { ignoreOld } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) // Ignore messages older than 5 minutes (default) bot.use(ignoreOld()) // Or specify a custom threshold in seconds (e.g., 2 minutes) bot.use(ignoreOld(120)) bot.on('message', (ctx) => { // This handler only receives messages less than 5 minutes old ctx.reply('Hello! Your message was received in time.') }) bot.start() ``` -------------------------------- ### Restrict Commands to Admins Middleware for grammY Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt The `onlyAdmin` middleware ensures that specific commands can only be executed by chat administrators. It intelligently handles different chat types and can optionally provide feedback to non-admin users via an error handler. This is crucial for commands that modify chat settings or require elevated privileges. ```typescript import { Bot } from 'grammy' import { onlyAdmin } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) // Restrict a command to admins only with error feedback bot.command('ban', onlyAdmin((ctx) => { ctx.reply('Sorry, only administrators can use this command.') }), async (ctx) => { // This code only runs if user is an admin const userId = ctx.message?.reply_to_message?.from?.id if (userId) { await ctx.banChatMember(userId) ctx.reply('User has been banned.') } }) // Without error handler - silently ignores non-admins bot.command('settings', onlyAdmin(), (ctx) => { ctx.reply('Admin settings panel...') }) bot.start() ``` -------------------------------- ### Restrict Commands to Super Admin Middleware for grammY Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt The `onlySuperAdmin` middleware restricts access to commands to a single, designated super administrator identified by their Telegram user ID. This differs from `onlyAdmin` by checking against a specific user ID rather than chat permissions, making it ideal for bot-wide administrative actions like broadcasting or shutting down the bot. ```typescript import { Bot } from 'grammy' import { onlySuperAdmin } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) const SUPER_ADMIN_ID = 123456789 // Your Telegram user ID // Only the super admin can use these commands bot.command('broadcast', onlySuperAdmin(SUPER_ADMIN_ID), async (ctx) => { // Broadcast message to all users - only bot owner can do this ctx.reply('Broadcasting message to all users...') }) bot.command('shutdown', onlySuperAdmin(SUPER_ADMIN_ID), (ctx) => { ctx.reply('Shutting down bot...') process.exit(0) }) // Can also use environment variable bot.command('debug', onlySuperAdmin(Number(process.env.SUPER_ADMIN_ID)), (ctx) => { ctx.reply('Debug info: ' + JSON.stringify(ctx.update, null, 2)) }) bot.start() ``` -------------------------------- ### Restrict Commands to Public Chats Middleware for grammY Source: https://context7.com/backmeupplz/grammy-middlewares/llms.txt The `onlyPublic` middleware restricts the execution of commands to public group or channel chats, excluding private messages. This is beneficial for features that are contextually relevant only in group settings, such as initiating polls or managing group-specific configurations. It can also include an error handler for private messages. ```typescript import { Bot } from 'grammy' import { onlyPublic } from 'grammy-middlewares' const bot = new Bot(process.env.BOT_TOKEN) // Only allow this command in groups/channels bot.command('poll', onlyPublic((ctx) => { ctx.reply('This command only works in group chats. Add me to a group to use it!') }), (ctx) => { // This code only runs in group chats or channels ctx.reply('Creating a poll for the group...') }) // Without error handler - silently ignores private messages bot.command('groupstats', onlyPublic(), (ctx) => { ctx.reply('Group statistics...') }) bot.start() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.