npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@mdreal/nestjs-tg-bot

v0.0.5

Published

NestJS module for building Telegram bots with grammY. Supports multiple bots, decorators, injection, polling, and webhooks.

Readme

@mdreal/nestjs-tg-bot

npm version License Downloads

A fully-typed, decorator-driven NestJS module for building Telegram bots with grammY.

This package provides a clean, modular approach to integrating grammY bots into your NestJS applications. It is designed for developers who value SOLID principles, KISS design, and first-class TypeScript support.


✨ Highlights

  • Dynamic NestJS Module Easily register one or multiple Telegram bots with TelegramModule.forRoot() / forRootAsync().

  • Multiple Bots in One App Run any number of bots in a single NestJS instance. Each bot has a unique name and isolated scope.

  • Decorator-based API Write expressive and concise handlers with decorators:

    • @Command("..."), @Hears("..."), @On("..."), @Use()
    • Shorthands: @Start(), @Help()
  • Scoped Handlers @Scope("botName") / @Scopes([...]) let you control which bot executes which handler.

  • Elegant Dependency Injection Inject instances directly into services:

    • @InjectBot("name")
    • @InjectApi("name")
    • @InjectWebhook("name")
    • @InjectOptions("name")
  • Nest-style Integration Uses Nest’s DiscoveryService to auto-wire handlers at bootstrap. No manual plumbing required.

  • Flexible Runtime Choose between polling or webhook mode per bot. Supports grammY plugins, middlewares, logging, and rate limiting.


📦 Installation

pnpm add @mdreal/nestjs-tg-bot
# peer dependencies (required in your app)
pnpm add @nestjs/common @nestjs/core reflect-metadata

🚀 Getting Started

Single Bot Setup

import { Module } from "@nestjs/common";
import { TelegramModule } from "@mdreal/nestjs-tg-bot";

@Module({
  imports: [
    TelegramModule.forRoot({
      name: "mybot",
      token: process.env.TELEGRAM_TOKEN!,
      mode: "auto",   // "auto" | "polling" | "webhook"
      logging: true,  // use NestJS logger
    }),
  ],
})
export class AppModule {}

Basic Handler

import { Injectable } from "@nestjs/common";
import { Start, Help } from "@mdreal/nestjs-tg-bot";
import type { Context } from "grammy";

@Injectable()
export class BotHandlers {
  @Start()
  async onStart(ctx: Context) {
    await ctx.reply("Welcome to the bot!");
  }

  @Help()
  async onHelp(ctx: Context) {
    await ctx.reply("Available commands: /start, /help");
  }
}

🤖 Multiple Bots Example

@Module({
  imports: [
    TelegramModule.forRoot({ name: "alpha", token: process.env.TG_ALPHA! }),
    TelegramModule.forRoot({ name: "beta", token: process.env.TG_BETA! }),
  ],
})
export class AppModule {}

import { Injectable } from "@nestjs/common";
import { Scope, Command } from "@mdreal/nestjs-tg-bot";
import type { Context } from "grammy";

@Injectable()
@Scope("beta") // binds only to the "beta" bot
export class BetaHandlers {
  @Command("ping")
  async onPing(ctx: Context) {
    await ctx.reply("pong from beta bot");
  }
}

💉 Dependency Injection

import { Injectable } from "@nestjs/common";
import { InjectBot, InjectApi } from "@mdreal/nestjs-tg-bot";
import type { Bot, Api } from "grammy";

@Injectable()
export class BotService {
  constructor(
    @InjectBot("mybot") private readonly bot: Bot,
    @InjectApi("mybot") private readonly api: Api,
  ) {}

  async notify(chatId: number, message: string) {
    await this.api.sendMessage(chatId, message);
  }
}

⚙️ Configuration Options

TelegramModule.forRoot({
  name: "mybot",
  token: "...",
  mode: "auto" | "polling" | "webhook",
  apiPlugins: [],      // register grammY API plugins
  rateLimit: {},       // in-memory rate limiting
  middlewares: [],     // custom grammY middlewares
  polling: {},         // PollingOptions
  webhook: { url: ""}, // WebhookOptions
  logging: true,       // enable NestJS logger
  onError: (err) => {}, 
  onStart: (info) => {},
});

🧭 Roadmap

✅ Implemented

  • Core decorators: @Command, @Start, @Help, @Hears, @On, @Use
  • Multi-bot support with @Scope / @Scopes
  • Injection helpers: @InjectBot, @InjectApi, @InjectWebhook, @InjectOptions
  • Auto-binding via DiscoveryService

🚧 Planned Built-ins

  • @AdminOnly() — restricts handlers to configured admin user IDs
  • @PrivateChat() / @GroupChat() — run handlers only in specific chat types
  • @Throttle(ms) — simple per-user throttling for spam control
  • @Alias("...") — define multiple triggers for the same command
  • @Fallback() — catch-all handler for unrecognized input
  • @InlineQuery() — shorthand for inline query events
  • @ChosenInlineResult() — shorthand for chosen inline results
  • @CallbackQuery("...") — decorator for handling button callbacks
  • Auto-generated /help command that aggregates available commands

🛠 Infrastructure

  • CLI generator: nest g handler for scaffolded handlers with decorators
  • Graceful shutdown hooks (bot.stop() integration with Nest lifecycle)
  • Example starter projects (REST + bot hybrid apps)

📖 Documentation & References

This library bridges the two worlds: ergonomics of grammY inside the structured environment of NestJS.


🤝 Contributing

Contributions, issues, and feature requests are welcome. Please open an issue to discuss ideas before submitting PRs.


📄 License

Licensed under the Apache License 2.0.
Copyright © 2025 MDReal