robot-mafia / nestjs-telegraf

🤖 Powerful Nest module for easy and fast creation Telegram bots
https://nestjs-telegraf.0x467.com
MIT License
520 stars 89 forks source link

Set bot public in TelegrafService #7

Closed lamuertepeluda closed 4 years ago

lamuertepeluda commented 4 years ago

Hi,

first thing, thanks a lot for this library.

I'm trying to add a middleware to the bot, but I see it is not accessible outside the TelegrafService.

Wouldn't it make sense to have public readonly bot at this line instead of having it private? Then it would be possible to call bot.use as showed here

I can make a PR if you wish

evilsprut commented 4 years ago

Hey @lamuertepeluda .

Unfortunately, this is a very early version of the module, so a lot of basic Telegraf functionality is not implemented.

I will think what can be done in future versions to make Telegraf middlewares convenient.

Be sure to write if you need anything. And thank you for the pull request.

lamuertepeluda commented 4 years ago

You're more than welcome! So fare everything is good and setting the bot public allowed me to add some useful middlewares to the bot in the onModuleInit method of the bot.module.ts like this

// in perf.bot.middleware.ts
export const perfMiddleware = async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  Logger.log(`Response time: ${ms}ms`);
};

// in bot.module.ts like in your example repo
export class BotModule implements OnModuleInit {
  constructor(
    private readonly moduleRef: ModuleRef,
    private readonly telegrafService: TelegrafService,
    private readonly configService: ConfigService,
  ) {}
  async onModuleInit() {
     // Finally adding middlewares here 😊
    this.telegrafService.bot.use(
      perfMiddleware
    );

    this.telegrafService.init(this.moduleRef);
    if (this.configService.get('bot.isDevMode')) {
      this.telegrafService.startPolling();
      Logger.log('BotModule polling started', 'BotModule');
    }
  }
}

Of course I added more useful middlewares like session or some others listed here

evilsprut commented 4 years ago

@all-contributors please add @lamuertepeluda for code, bug, ideas

allcontributors[bot] commented 4 years ago

@bukhalo

I've put up a pull request to add @lamuertepeluda! :tada: