0x467 / nestjs-telegraf

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

Bot Error Handling in NestJS Application #1156

Closed shahriarenayaty closed 2 weeks ago

shahriarenayaty commented 9 months ago

Hello every body, I am encountering an issue with my Telegraf bot integrated into a NestJS application. When the bot encounters an error, it causes my entire application to crash, which is not the desired behavior. Instead, I want my application to log the error and continue functioning without any disruptions. e.g. this error: Error: 409: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running FetchError: request to https://api.telegram.org/bot**********:[REDACTED]/getMe failed, reason: connect ETIMEDOUT 10.10.34.36:443 Proposed Solution: I believe the ideal solution for this issue is to make use of the bot.catch method in Telegraf, which is designed for error handling within the bot itself. This way, the bot can log errors and continue processing, ensuring that the NestJS application remains functional even when bot errors occur.

Code Attempted I have tried the following code to handle errors within my Telegraf bot:

@Injectable()
export class TelegramBotService {
  constructor(
    @InjectBot(TelegramBotName)
    private bot: Telegraf<TelegramContext>,
    private readonly developerService: DeveloperService,
  ) {
    this.bot.catch((error, ctx: TelegramContext) => {
      console.error('Telegraf error:', error);
      console.log(ctx);
    });
  }

and this is how I add my telegrafModule to App Module

@Module({
  imports: [
      TelegrafModule.forRootAsync({
          imports: [ConfigModule],
          inject: [ConfigService], // Inject ConfigService
          botName: TelegramBotName,
          useFactory: (configService: ConfigService) => ({
            token: configService.get('TELEGRAM_TOKEN'),
            middlewares: [sessionMiddleware],
            include: [TelegramBotModule],
          }),
      })
  ]
  })
export class AppModule {}

Thank you for your assistance in finding a solution to this issue. If you have any recommendations or suggestions on how to implement proper error handling for the Telegraf bot within a NestJS application, please share them. Your input will be greatly appreciated.

0x467 commented 2 weeks ago

Fixed in https://github.com/0x467/nestjs-telegraf/commit/9c0286c23c707f3366f670be3c91d61758186157