nestjs-telegraf/README.md
2020-08-23 00:00:59 +03:00

8.2 KiB

Nest Logo

NestJS Telegraf

npm GitHub last commit NPM

Telegraf module for NestJS.

Installation

$ npm i nestjs-telegraf

Once the installation process is complete, we can import the TelegrafModule into the root AppModule.

/* app.module.ts */

import { Module } from '@nestjs/common';
import { TelegrafModule } from 'nestjs-telegraf';

@Module({
  imports: [
    TelegrafModule.forRoot({
      token: 'TELEGRAM_BOT_TOKEN',
    })
  ],
})
export class AppModule {}

The forRoot() method accepts the same configuration object as Telegraf class constructor from the Telegraf package, as described here.

Telegraf methods

Each Telegraf instance method described here has own decorator in nestjs-telegraf package. The name of the decorator corresponds to the name of the Telegraf method. For example @Hears, @On, @Action and so on.

Now let's try to repeat the example from the Telegraf documentation page.

/* app.service.ts */

import { Injectable } from '@nestjs/common';
import {
  Start,
  Help,
  On,
  Hears,
  Context,
} from 'nestjs-telegraf';

@Injectable()
export class AppService {
  @Start()
  start(ctx: Context) {
    ctx.reply('Welcome');
  }

  @Help()
  help(ctx: Context) {
    ctx.reply('Send me a sticker');
  }

  @On('sticker')
  on(ctx: Context) {
    ctx.reply('👍');
  }

  @Hears('hi')
  hears(ctx: Context) {
    ctx.reply('Hey there');
  }
}

Bot injection

At times you may need to access the native Telegraf instance. For example, you may want to connect stage middleware. You can inject the Telegraf by using the @InjectBot() decorator as follows:

import { Injectable } from '@nestjs/common';
import { InjectBot, TelegrafProvider } from 'nestjs-telegraf';

@Injectable()
export class BotSettingsService {
  constructor(@InjectBot() private bot: TelegrafProvider) {}
}

Async configuration

When you need to pass module options asynchronously instead of statically, use the forRootAsync() method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.

One technique is to use a factory function:

TelegrafModule.forRootAsync({
  useFactory: () => ({
    token: 'TELEGRAM_BOT_TOKEN',
  }),
});

Like other factory providers, our factory function can be async and can inject dependencies through inject.

TelegrafModule.forRootAsync({
  imports: [ConfigModule.forFeature(telegrafModuleConfig)],
  useFactory: async (configService: ConfigService) => ({
    token: configService.get<string>('TELEGRAM_BOT_TOKEN'),
  }),
  inject: [ConfigService],
});

Alternatively, you can configure the TelegrafModule using a class instead of a factory, as shown below:

TelegrafModule.forRootAsync({
  useClass: TelegrafConfigService,
});

The construction above instantiates TelegrafConfigService inside TelegrafModule, using it to create the required options object. Note that in this example, the TelegrafConfigService has to implement the TelegrafOptionsFactory interface, as shown below. The TelegrafModule will call the createTelegrafOptions() method on the instantiated object of the supplied class.

@Injectable()
class TelegrafConfigService implements TelegrafOptionsFactory {
  createTelegrafOptions(): TelegrafModuleOptions {
    return {
      token: 'TELEGRAM_BOT_TOKEN',
    };
  }
}

If you want to reuse an existing options provider instead of creating a private copy inside the TelegrafModule, use the useExisting syntax.

TelegrafModule.forRootAsync({
  imports: [ConfigModule.forFeature(telegrafModuleConfig)],
  useExisting: ConfigService,
});

Webhooks

If you want to configure a telegram bot webhook, you need to get a middleware from TelegrafProvider for connect it in your main.ts file.

To access it, you must use the app.get() method, followed by the provider reference:

const telegrafProvider = app.get('TelegrafProvider');

Now you can connect middleware:

app.use(telegrafProvider.webhookCallback('/secret-path'));

The last step is to specify launchOptions in forRoot method:

TelegrafModule.forRootAsync({
  imports: [ConfigModule.forFeature(telegrafModuleConfig)],
  useFactory: async (configService: ConfigService) => ({
    token: configService.get<string>('TELEGRAM_BOT_TOKEN'),
    launchOptions: {
      webhook: {
        domain: 'domain.tld',
        hookPath: '/secret-path',
      }
    }
  }),
  inject: [ConfigService],
});

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

People

License

Nest is MIT licensed.

Contributors

Thanks goes to these wonderful people (emoji key):


Eldar Salimzebarov

🐛

Vito Macchia

💻 🐛

KITAHARA SETSUNA

💻 🐛

Aleksandr Bukhalo

💻 📖 👀

Vyacheslav Saloid

🐛

This project follows the all-contributors specification. Contributions of any kind welcome!