Skip to content

Multiple bots

Register each instance with a unique botName. Every named bot receives its own Telegraf instance, options, scene stage, listener explorer and shutdown hook.

ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TelegrafModule } from 'nestjs-telega';

@Module({
  imports: [
    ConfigModule.forRoot(),
    TelegrafModule.forRootAsync({
      imports: [ConfigModule],
      botName: 'cat',
      useFactory: (configService: ConfigService) => ({
        token: configService.getOrThrow<string>('CAT_BOT_TOKEN'),
      }),
      inject: [ConfigService],
    }),
    TelegrafModule.forRootAsync({
      imports: [ConfigModule],
      botName: 'dog',
      useFactory: (configService: ConfigService) => ({
        token: configService.getOrThrow<string>('DOG_BOT_TOKEN'),
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

WARNING

Only one default bot may be registered. Named bots must not reuse a name.

Inject a named bot with @InjectBot('name'):

ts
import { Injectable } from '@nestjs/common';
import { InjectBot } from 'nestjs-telega';
import { Context, Telegraf } from 'telegraf-hardened';

@Injectable()
export class EchoService {
  constructor(@InjectBot('cat') private catBot: Telegraf<Context>) {}
}

For a factory provider, use getBotToken('name'):

ts
{
  provide: CatsService,
  useFactory: (catBot: Telegraf<Context>) => {
    return new CatsService(catBot);
  },
  inject: [getBotToken('cat')],
}

By default the module discovers handlers throughout the application. Limit discovery to selected modules with include:

ts
TelegrafModule.forRootAsync({
  imports: [ConfigModule],
  botName: 'cat',
  useFactory: (configService: ConfigService) => ({
    token: configService.getOrThrow<string>('CAT_BOT_TOKEN'),
    include: [CatsModule],
  }),
  inject: [ConfigService],
}),

Released under the MIT License.