I use Telegraf and cron from @nestjs/schedule in my Nestjs app.
Below you can see my app.module:
import { Module } from '@nestjs/common';
import { BotModule } from 'src/bot/bot.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getConnectionOptions } from 'typeorm';
import { ConfigModule } from '@nestjs/config';
import { ScheduleModule } from '@nestjs/schedule';
@Module({
imports: [
BotModule,
ScheduleModule.forRoot(),
ConfigModule.forRoot({
isGlobal: true
}),
TypeOrmModule.forRootAsync({
useFactory: async () =>
Object.assign(await getConnectionOptions(), {
autoLoadEntities: true
})
})
]
})
export class AppModule {}
bot.module:
import { Module } from '@nestjs/common';
import { BotService } from 'src/bot/bot.service';
import { TelegrafModule } from 'nestjs-telegraf';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TelegramBot } from './entities/bot.entity';
@Module({
imports: [
TypeOrmModule.forFeature([TelegramBot]),
TelegrafModule.forRootAsync({
useFactory: () => ({
token: process.env.BOT_TELEGRAM_TOKEN
})
})
],
providers: [BotService]
})
export class BotModule {}
bot.service:
import { Cron } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { On, Update } from 'nestjs-telegraf';
import { Context } from 'telegraf';
import { Repository } from 'typeorm';
import { TelegramBot } from './entities/bot.entity';
@Update()
export class BotService {
constructor(
@InjectRepository(TelegramBot)
private telegramRepo: Repository<TelegramBot>
) {}
@On('message')
@Cron('*/30 * * * * *')
async message(ctx: Context): Promise<void> {
await ctx.reply('Hello there');
}
}
My main goal is to receive every 30 seconds message from bot into chat: "Hello there", but instead I receive nothing and messages in terminal:
[Nest] 47039 - 15/09/2021, 15:39:30 [Scheduler] TypeError: Cannot read property 'reply' of undefined +30005ms
[Nest] 47039 - 15/09/2021, 15:40:00 [Scheduler] TypeError: Cannot read property 'reply' of undefined +29997ms
[Nest] 47039 - 15/09/2021, 15:40:30 [Scheduler] TypeError: Cannot read property 'reply' of undefined +29995ms
[Nest] 47039 - 15/09/2021, 15:41:00 [Scheduler] TypeError: Cannot read property 'reply' of undefined +30003ms
[Nest] 47039 - 15/09/2021, 15:41:30 [Scheduler] TypeError: Cannot read property 'reply' of undefined +29999ms
[Nest] 47039 - 15/09/2021, 15:42:00 [Scheduler] TypeError: Cannot read property 'reply' of undefined +30002ms
So how can I use Cron for working correctly with Telegram bot?