Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not able to handle requests in parallel #1048

Open
baunov opened this issue Feb 3, 2023 · 1 comment
Open

Not able to handle requests in parallel #1048

baunov opened this issue Feb 3, 2023 · 1 comment

Comments

@baunov
Copy link

baunov commented Feb 3, 2023

Hi,I've been following documentation to setup the simplest possible bot as an experiment.

@Update()
@Injectable()
export class AppUpdate {
 
  @Command('random')
  async onRandom(@Ctx() ctx: Context) {
    console.log('Random');
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(null);
      }, 10000);
    });
    await ctx.reply(`Rnd is ${Math.random()}`);
  }
}

And in app.module

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TelegrafModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        token: configService.get<string>('TELEGRAM_BOT_TOKEN'),
      }),
      inject: [ConfigService],
    }),
    HttpModule,
  ],
  controllers: [],
  providers: [AppUpdate],
})
export class AppModule {}

I'm stuck with an issue where onRandom() is not being called until the previous call returns. So, if multiple users are using the bot, they have to wait and queue up to get the response.

Is that expected behaviour? What am I doing wrong here?

Versions:

"nestjs-telegraf": "^2.6.3",
"@nestjs/core": "^8.0.0",
"telegraf": "^4.11.2"
@kzamulin
Copy link

Hello, I'm not 100% sure about that, however I think this is normal and expected behaviour. I'm also new to telegram bots, so I've just reproduced your code, and then started googling, and it seems to me that parallel handling of some commands can be accomplished via async code only. Look at https://grammy.dev/advanced/scaling.html which I find usefull for understanding.

In you code, if you want to handle requests in parallel, you should not await new Promise, but rather resolve it as follows:

  @Command('random')
  async onRandom(@Ctx() ctx: TelegrafContext) {
    console.log('Random');
    const promise = new Promise((resolve) => {
      setTimeout(() => {
        resolve(Math.random());
      }, 10000);
    });
    promise.then(
      (result) => {
        ctx.reply(`Rnd is ${result}`);
      },
      (error) => {
        console.log(error);
      }
    );
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants