Skip to content

✨ Quick Start

Introduction

NestKit's Telegram bot integration is built on grammY, a powerful framework for building Telegram bots in TypeScript. Our implementation extends grammY with NestJS-specific features, providing a seamless integration with dependency injection, middleware system, and TypeORM.

This quick start guide will help you set up a Telegram bot with essential features like commands, conversations, and menu interfaces. The architecture is designed to be modular and maintainable, allowing you to scale your bot as your application grows.

Let's get started with the basic setup:

  1. Install the NestKit package:

    bash
    npm install @deep/nest-kit
  2. Register Telegram configuration in your main module:

    typescript
    // src/config/index.ts
    import { createTelegramConfig } from '@deepvision/nest-kit/configs';
  3. Add the required environment variables to your .env.yml file:

    yaml
    # ============ Telegram =============
    TELEGRAM_BOT_TOKEN: "xxx"
    TELEGRAM_WEBHOOK_SECRET_TOKEN: "xxx"
  4. Register the GrammyModule in your application module:

    typescript
    // src/app.module.ts
    import { Module } from '@nestjs/common';
    import { GrammyModule } from '@deep/nest-kit/dist/modules/grammy';
    
    @Module({
      imports: [
        // ...other modules
        GrammyModule,
      ],
    })
    export class AppModule {}
  5. Create an auth middleware to resolve users by Telegram ID:

    typescript
    // src/modules/bot/middlewares/auth.middleware.ts
    import { BaseAuthMiddleware } from '@deep/nest-kit/dist/grammy-kit';
    import { MaybeNull } from '@deep/nest-kit/types/maybe';
    import { Injectable } from '@nestjs/common';
    import { User } from '@/modules/users/user.entity';
    
    @Injectable()
    export class AuthMiddleware extends BaseAuthMiddleware<User> {
      async getUserByTelegramId(telegramId: number): Promise<MaybeNull<User>> {
        return await this.dataSource.getRepository(User).findOne({
          where: {
            telegramId,
          },
        });
      }
    }
  6. Create your first command:

    typescript
    // src/modules/bot/commands/start.command.ts
    import { BaseCommand, GrammyContext } from '@deep/nest-kit/dist/grammy-kit';
    import { Injectable } from '@nestjs/common';
    import { CommandContext } from 'grammy';
    import { MainMenu } from '../menus/main.menu';
    
    @Injectable()
    export class StartCommand extends BaseCommand {
      constructor(
        private readonly mainMenu: MainMenu,
      ) {
        super();
      }
    
      async run(ctx: CommandContext<GrammyContext>): Promise<void> {
        const logger = this.logger.child({
          action: this.run.name,
          fromId: ctx.from?.id,
        });
    
        logger.info(`Start command received from ${ctx.from?.id} (${ctx.from?.first_name} ${ctx.from?.last_name ?? ''})`);
    
        await this.mainMenu.reply(`Welcome, ${ctx.user.fullName} 👋`, ctx);
      }
    }
  7. Create a bot module:

    typescript
    // src/modules/bot/bot.module.ts
    import { Module } from '@nestjs/common';
    import { StartCommand } from './commands/start.command';
    import { AuthMiddleware } from './middlewares/auth.middleware';
    
    @Module({
      providers: [
        // Middlewares
        AuthMiddleware,
        // Commands
        StartCommand,
      ],
    })
    export class BotModule {}
  8. Set up polling mode in your main.ts file:

    typescript
    // src/main.ts
    import { GRAMMY_BOT, TELEGRAM_CONFIG_TOKEN, getConfigToken } from '@deep/nest-kit/dist/grammy-kit';
    import { Bot } from 'grammy';
    
    async function bootstrap() {
      // ...existing code...
    
      const tgConfig = app.get<TelegramConfigType>(getConfigToken(TELEGRAM_CONFIG_TOKEN));
      if (!tgConfig.webhook.enabled) {
        const bot = app.get<Bot>(GRAMMY_BOT);
        logger.info('Start Grammy bot');
        await bot.start();
      }
    
      // ...existing code...
    }
    bootstrap();
  9. Run your NestJS server:

    bash
    npm run start:dev
  10. Start your bot by sending the /start command or clicking the Start button in your Telegram chat.

Created by DeepVision Software.