How to work with Cron and Telegraf-bot in Nestjs? - node.js

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?

The main problem into your solution, it's you don't able to use context in that scenario. This is an example how you can do that.
import { Injectable } from '#nestjs/common';
import { Cron, CronExpression } from "#nestjs/schedule";
import { Telegram } from 'telegraf';
#Injectable()
export class CronService {
private readonly bot: Telegram = new Telegram(process.env.BOT_TOKEN);
constructor() {}
#Cron(CronExpression.EVERY_30_SECONDS)
async runCronEvery30Seconds() {
await this.bot.sendMessage('chat ID','Hello there');
}
}

Related

NestJS : ERROR [ExceptionHandler] Nest can't resolve dependencies of the ClientService

I am working with NestJSproject. I make an entity Client and a DTO for the "inscrit()" function
when I ran the project, I got the following:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the ClientService (?). Please make sure that the argument ClientRepository at index [0] is available in the ClientModule context.
Potential solutions:
- If ClientRepository is a provider, is it part of the current ClientModule?
- If ClientRepository is exported from a separate #Module, is that module imported within ClientModule?
#Module({
imports: [ /* the Module containing ClientRepository */ ]
})
this is the client.service.ts file
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClientInscritDto } from './dto/client-inscrit.dto';
import { Client } from './entity/client.entity';
import * as bcrypt from 'bcrypt';
import { ConflictException } from '#nestjs/common/exceptions';
#Injectable()
export class ClientService {
constructor(
#InjectRepository(Client)
private clientRepository : Repository<Client>
){}
async inscrit(clientData: ClientInscritDto) : Promise<Partial<Client>>{
const client = this.clientRepository.create({...clientData});
client.salt = await bcrypt.genSalt();
client.mdp = await bcrypt.hash(clientData.mdp, client.salt);
try{
await this.clientRepository.save(client);
}catch(err){
throw new ConflictException(`le surname ${clientData.surname} ou l'email ${clientData.email} existe déjà`);
}
return client;
}
}
The answer for this was that I forget adding in client.module.ts file:
imports: [
TypeOrmModule.forFeature([Client])
],

TypeError: Cannot read properties of undefined when call method of injected provider in NestJS

Follow tutorial at here, I'm just implement simple NestJS app with a module have injected provider below:
# app.module.ts
import { Module } from '#nestjs/common'
import { ConfigModule } from '#nestjs/config'
import { AuthModule } from '#/modules/auth/auth.module'
#Module({
imports: [
ConfigModule.forRoot(),
AuthModule
]
})
export class AppModule {}
# auth.module.ts
import { Module } from '#nestjs/common'
import { AuthController } from '#/modules/auth/auth.controller'
import { AuthService } from '#/modules/auth/auth.service'
#Module({
controllers: [AuthController],
providers: [AuthService]
})
export class AuthModule {}
# auth.controller.ts
import { Controller, Get } from '#nestjs/common'
import { AuthService } from '#/modules/auth/auth.service'
#Controller('auth')
export class AuthController {
constructor (private readonly service: AuthService) {}
#Get('me')
public getSelfInfo (): string {
return this.service.getSelfInfo()
}
}
# auth.service.ts
import { Injectable } from '#nestjs/common'
#Injectable()
export class AuthService {
getSelfInfo (): string {
return 'ok'
}
}
But when call to endpoint, this error thrown:
[Nest] 17196 - 09/23/2022, 2:34:18 PM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getSelfInfo')
TypeError: Cannot read properties of undefined (reading 'getSelfInfo')
at AuthController.getSelfInfo (/dist/modules/auth/auth.controller.js:16:29)
Please tell me which problem at here.
Solved this issue when add code block below to app.controller.ts:
#Inject(AuthService)
private readonly service: AuthService
constructor (service: AuthService) {
this.service = service
}

NestJS - Nest can't resolve dependencies of the ConfigurationService (ConfigService, ?)

I am new to NestJs + Typescript, trying to initialize a project, after building it throws the following error:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the ConfigurationService (ConfigService, ?). Please make sure that the argument CachingService at index [1] is available in the ConfigurationService context.
I tried many possible ways to solve this but no luck yet
These are the two modules in question:
import { CacheModule, Module } from '#nestjs/common';
import { CachingService } from './caching.service';
#Module({
imports: [
CacheModule.register({
ttl: 0,
}),
],
providers: [CachingService],
exports: [CachingService],
})
export class CachingModule {}
import { Module } from '#nestjs/common';
import { ConfigModule } from '#nestjs/config';
import { CachingModule } from '../caching/caching.module';
import { ConfigurationService } from './configuration.service';
import { config } from './environmentConfig/default.config';
import deploymentConfig from './deploymentConfig/config';
import { CachingService } from '../caching/caching.service';
#Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [() => config, deploymentConfig],
}),
CachingModule,
],
providers: [ConfigurationService, CachingService],
exports: [ConfigurationService],
})
export class ConfigurationModule {}
This is the service where I am trying to use the cachingModule and the error is being thrown:
import { Injectable, Logger, OnModuleInit } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { CachingService } from '../caching/caching.service';
#Injectable()
export class ConfigurationService implements OnModuleInit {
private readonly logger = new Logger(ConfigurationService.name);
constructor(
private readonly configService: ConfigService,
private cachingService: CachingService,
) {}
How to fix this?
Remove the CachingService as a provider in the ConfigurationModule.

NestJs error: can't resolve dependencies of the Service (?). Please make sure that the argument SchemaModel at index [0] is available

I get this error:
Nest can't resolve dependencies of the UserPreferencesService (?). Please make sure that the argument UserPreferencesSchemaModel at index [0] is available in the UserPreferencesModule context.
What can the error be? I understand that the problem happens in the user-preferences.service.ts file. as when I comment the following lines from the user-preferences.module.ts file all works fine.
controllers: [UserPreferencesController],
providers: [UserPreferencesService],
This is my user-preferences.service.ts file:
import { Injectable } from '#nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '#nestjs/mongoose';
import { UserPreferencesInterface } from './interfaces/user-preferences.interface';
#Injectable()
export class UserPreferencesService {
constructor(
#InjectModel('UserPreferencesSchema')
private readonly UserPreferencesModel: Model<UserPreferencesInterface>,
) {}
public async postUserPreferences(newUserPreferences: any): Promise<any> {
const userPreferences = await new this.UserPreferencesModel(
newUserPreferences,
);
return userPreferences.save();
}
}
app.module.ts
import { Module } from '#nestjs/common';
import { UserPreferencesModule } from './user-preferences/user-preferences.module';
import { MongooseModule } from '#nestjs/mongoose';
#Module({
imports: [
UserPreferencesModule,
MongooseModule.forRoot(
'mongodb+srv://user:pass#db.hucjifz.mongodb.net/dbname?retryWrites=true&w=majority',
),
],
})
export class AppModule {}
user-preferences.module.ts
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { UserPreferencesSchema } from './schemas/user-preferences.schema';
import { UserPreferencesController } from './user-preferences.controller';
import { UserPreferencesService } from './user-preferences.service';
#Module({
imports: [
MongooseModule.forFeature([
{
name: 'UserPreferences',
schema: UserPreferencesSchema,
},
]),
],
controllers: [UserPreferencesController],
providers: [UserPreferencesService],
})
export class UserPreferencesModule {}
user-preferences.controller.ts
import {Body, Controller, Get, Post, Put } from '#nestjs/common';
import { UserPreferencesService } from './user-preferences.service';
import { UserPreferencesDto } from './dto/user-preferences.dto'
#Controller('user-preferences')
export class UserPreferencesController {
constructor(private userPreferencesService: UserPreferencesService) {}
#Get()
public getUserPreferences() {
return this.userPreferencesService.getUserPreferences();
}
#Post ()
public postUserPreferences(
#Body() userPreferences: UserPreferencesDto
) {
return this.userPreferencesService.postUserPreferences( userPreferences );
}
}
this is the complete error:
[Nest] 65481 - 06/07/2022, 6:00:04 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the UserPreferencesService (?). Please make sure that the argument UserPreferencesSchemaModel at index [0] is available in the UserPreferencesModule context.
Potential solutions:
- If UserPreferencesSchemaModel is a provider, is it part of the current UserPreferencesModule?
- If UserPreferencesSchemaModel is exported from a separate #Module, is that module imported within UserPreferencesModule?
#Module({
imports: [ /* the Module containing UserPreferencesSchemaModel */ ]
})
Error: Nest can't resolve dependencies of the UserPreferencesService (?). Please make sure that the argument UserPreferencesSchemaModel at index [0] is available in the UserPreferencesModule context.
Potential solutions:
- If UserPreferencesSchemaModel is a provider, is it part of the current UserPreferencesModule?
- If UserPreferencesSchemaModel is exported from a separate #Module, is that module imported within UserPreferencesModule?
#Module({
imports: [ /* the Module containing UserPreferencesSchemaModel */ ]
})
at Injector.lookupComponentInParentModules (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:231:19)
at Injector.resolveComponentInstance (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:184:33)
at resolveParam (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:106:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:121:27)
at Injector.loadInstance (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:52:9)
at Injector.loadProvider (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:74:9)
at async Promise.all (index 3)
at InstanceLoader.createInstancesOfProviders (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/instance-loader.js:44:9)
at /Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/instance-loader.js:29:13
O.K, after digging alot I found that the problem was caused because MongooseModule.forFeature name and #InjectModel() in user-preferences.service.ts value were not identical.
They must be identical.

NestJS Unable to Resolve Dependencies

I'm getting this error when I run my NestJS app.
[Nest] 19139 - 03/01/2020, 2:10:01 PM [ExceptionHandler] Nest can't resolve dependencies of the AccountsService (AccountRepository, ?, HashPasswordService). Please make sure that the argument Object at index [1] is available in the AccountsModule context.
Potential solutions:
- If Object is a provider, is it part of the current AccountsModule?
- If Object is exported from a separate #Module, is that module imported within AccountsModule?
#Module({
imports: [ /* the Module containing Object */ ]
})
+1ms
I am a bit confused what it causing this. As far as I can tell, my code looks correct. Here is the definition for my AccountsService class:
import { Injectable, ConflictException, Logger, InternalServerErrorException, NotFoundException, Inject } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Account } from 'src/accounts/entities/account';
import { Repository, FindManyOptions, UpdateDateColumn } from 'typeorm';
import { CreateAccount } from 'src/accounts/dtos/create-account';
import { GetAccountsWithFilters } from 'src/accounts/dtos/get-accounts-with-filters';
import { UpdateAccountProfileInfo } from 'src/accounts/dtos/update-account-profile-info';
import { HashPasswordService } from '../hash-password/hash-password.service';
import { UpdateEmail } from 'src/accounts/dtos/update-email';
import { UpdatePhone } from 'src/accounts/dtos/update-phone';
import { AccountRepository } from 'src/accounts/repositories/account-repository';
/**
* AccountsService encapsulates all the actions that can be performed by an account.
*/
#Injectable()
export class AccountsService {
constructor(
#InjectRepository(AccountRepository) private accountRepository: AccountRepository,
private logger = new Logger("Accounts Service"),
#Inject(HashPasswordService)
private hashPasswordService: HashPasswordService,
) { }
// more code here
}
My Module looks like this.
import { Module } from '#nestjs/common';
import { AccountsService } from './services/accounts/accounts.service';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Account } from './entities/account';
import { AccountsController } from './controllers/accounts/accounts.controller';
import { AccountCleanerService } from './services/account-cleaner/account-cleaner.service';
import { AuthenticationService } from './services/authentication/authentication.service';
import { AuthenticationController } from './controllers/authentication/authentication.controller';
import { HashPasswordService } from './services/hash-password/hash-password.service';
import { JwtModule } from "#nestjs/jwt";
import { PassportModule } from "#nestjs/passport";
import { JwtStrategy } from './auth-strategies/jwt-strategy';
import { AccountRepository } from './repositories/account-repository';
#Module({
imports: [
TypeOrmModule.forFeature([
Account,
AccountRepository,
]),
JwtModule.register({
secret: "SOME_APP_SECRET",
signOptions: {
expiresIn: 3600
}
}),
PassportModule.register({
defaultStrategy: "jwt",
}),
],
controllers: [
AccountsController,
AuthenticationController,
],
providers: [
AccountRepository,
HashPasswordService,
AccountsService,
AccountCleanerService,
AuthenticationService,
JwtStrategy,
],
exports: [JwtStrategy, PassportModule],
})
export class AccountsModule { }
Lastly, here is the App Module:
import { Module } from '#nestjs/common';
import { AccountsModule } from './accounts/accounts.module';
import { TypeOrmModule } from "#nestjs/typeorm";
import {Account} from "./accounts/entities/account";
import { ConfigModule } from "#nestjs/config";
import account from "./../config/account";
import auth from "./../config/auth";
import database from "./../config/database";
import server from "./../config/server";
import { AccountRepository } from './accounts/repositories/account-repository';
#Module({
imports: [
AccountsModule,
ConfigModule.forRoot({
// make this module available globally
isGlobal: true,
// The configuration files.
load: [
account,
auth,
database,
server
],
}),
TypeOrmModule.forRoot({
type: "mongodb",
url: "my connection string here",
entities: []
}),
],
controllers: [],
providers: [],
})
export class AppModule { }
As you can see, I have clearly made the services available to the module. So, I am kind of confused why Nest is unable to resolve the dependencies. Additionally, there should not be any other module right now, aside from the App module.,, which is also provided above. Any ideas why NestJS is throwing this error?
Nest is having trouble resolving the dependency of Logger, and as it is not provided in the providers array, it won't be able to resolve it. You've got three options:
1) Move the private logger = new Logger('Account Service') to the body of the constructor
2) Move the private logger = new Logger('Account Service') to the third position and mark it as #Optional() so that Nest doesn't throw an error when the value is unknown.
3) Add Logger to the providers array of AccountModule and then use the this.logger.setContext() method to properly set the context
The built in Logger class is #Injectable() so it is possible to use it through DI, but you have to ensure that it is provided just as any other provider is in the NestJS ecosystem.

Resources