Skip to content

๐Ÿ“ˆ Open source, privacy-first web analytics โ€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Implemented the mechanism of deferred messages (#167)

Yevhenii Kulisidi891017175b7d
diff --git a/apps/production/src/auth/auth.module.ts b/apps/production/src/auth/auth.module.ts
index 617ee46cc..94adb1615 100644
--- a/apps/production/src/auth/auth.module.ts
+++ b/apps/production/src/auth/auth.module.ts
@@ -6,6 +6,7 @@ import { MailerModule } from 'src/mailer/mailer.module'
import { UserModule } from 'src/user/user.module'
import { ProjectModule } from 'src/project/project.module'
import { TelegramService } from 'src/integrations/telegram/telegram.service'
+import { TypeOrmModule } from '@nestjs/typeorm'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
import {
@@ -13,6 +14,7 @@ import {
JwtAccessTokenStrategy,
JwtRefreshTokenStrategy,
} from './strategies'
+import { Message } from '../integrations/telegram/entities/message.entity'
@Module({
imports: [
@@ -23,6 +25,7 @@ import {
MailerModule,
ActionTokensModule,
ProjectModule,
+ TypeOrmModule.forFeature([Message]),
],
controllers: [AuthController],
providers: [
diff --git a/apps/production/src/auth/auth.service.ts b/apps/production/src/auth/auth.service.ts
index 946d6babd..daf465b33 100644
--- a/apps/production/src/auth/auth.service.ts
+++ b/apps/production/src/auth/auth.service.ts
@@ -186,8 +186,8 @@ export class AuthService {
}
if (user && user.isTelegramChatIdConfirmed) {
- await this.telegramService.sendMessage(
- Number(user.telegramChatId),
+ await this.telegramService.addMessage(
+ user.telegramChatId,
'โš ๏ธ *Someone has tried to login to their account with an incorrect password.*',
{ parse_mode: 'Markdown' },
)
@@ -239,13 +239,9 @@ export class AuthService {
`*Date:* ${loginDate} (UTC)\n\n` +
'If it was not you, please change your password immediately.'
if (user && user.isTelegramChatIdConfirmed) {
- await this.telegramService.sendMessage(
- Number(user.telegramChatId),
- message,
- {
- parse_mode: 'Markdown',
- },
- )
+ await this.telegramService.addMessage(user.telegramChatId, message, {
+ parse_mode: 'Markdown',
+ })
}
}
diff --git a/apps/production/src/integrations/telegram/entities/message.entity.ts b/apps/production/src/integrations/telegram/entities/message.entity.ts
new file mode 100644
index 000000000..8494ca9da
--- /dev/null
+++ b/apps/production/src/integrations/telegram/entities/message.entity.ts
@@ -0,0 +1,24 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ PrimaryGeneratedColumn,
+} from 'typeorm'
+
+@Entity()
+export class Message {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column('varchar')
+ chatId: string
+
+ @Column('text')
+ text: string
+
+ @Column('json', { nullable: true, default: null })
+ extra: unknown | null
+
+ @CreateDateColumn()
+ createdAt: Date
+}
diff --git a/apps/production/src/integrations/telegram/telegram.module.ts b/apps/production/src/integrations/telegram/telegram.module.ts
index 596487783..a22e90ebd 100644
--- a/apps/production/src/integrations/telegram/telegram.module.ts
+++ b/apps/production/src/integrations/telegram/telegram.module.ts
@@ -5,6 +5,7 @@ import { session } from 'telegraf'
import { UserModule } from 'src/user/user.module'
import { ProjectModule } from 'src/project/project.module'
import { AnalyticsModule } from 'src/analytics/analytics.module'
+import { TypeOrmModule } from '@nestjs/typeorm'
import { TelegramController } from './telegram.controller'
import { TelegramUpdate } from './telegram.update'
import { StartScene } from './scene/start.scene'
@@ -12,6 +13,7 @@ import { ProjectsScene } from './scene/projects.scene'
import { SettingsScene } from './scene/settings.scene'
import { UnlinkAccountScene } from './scene/unlink-account.scene'
import { TelegramService } from './telegram.service'
+import { Message } from './entities/message.entity'
@Module({
imports: [
@@ -38,6 +40,7 @@ import { TelegramService } from './telegram.service'
middlewares: [session()],
}),
}),
+ TypeOrmModule.forFeature([Message]),
UserModule,
ProjectModule,
AnalyticsModule,
diff --git a/apps/production/src/integrations/telegram/telegram.service.ts b/apps/production/src/integrations/telegram/telegram.service.ts
index 0b85f0d51..c1aacb896 100644
--- a/apps/production/src/integrations/telegram/telegram.service.ts
+++ b/apps/production/src/integrations/telegram/telegram.service.ts
@@ -3,7 +3,10 @@ import { ConfigService } from '@nestjs/config'
import { InjectBot } from 'nestjs-telegraf'
import { Markup, Telegraf } from 'telegraf'
import { UserService } from 'src/user/user.service'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Repository } from 'typeorm'
import { Context } from './interface/context.interface'
+import { Message } from './entities/message.entity'
@Injectable()
export class TelegramService {
@@ -11,6 +14,8 @@ export class TelegramService {
@InjectBot() private readonly bot: Telegraf<Context>,
private readonly userService: UserService,
private readonly configService: ConfigService,
+ @InjectRepository(Message)
+ private readonly messageRepository: Repository<Message>,
) {}
async getStartMessage(telgramId: number) {
@@ -49,7 +54,7 @@ export class TelegramService {
return { text, extra }
}
- async sendMessage(chatId: number, text: string, extra?: unknown) {
+ async confirmLinkAccount(userId: string, chatId: number) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
@@ -57,12 +62,10 @@ export class TelegramService {
return
}
- const chat = await this.bot.telegram.getChat(chatId)
- if (!chat) return
- await this.bot.telegram.sendMessage(chatId, text, extra)
+ await this.userService.updateUserTelegramId(userId, chatId, true)
}
- async confirmLinkAccount(userId: string, chatId: number) {
+ async cancelLinkAccount(userId: string) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
@@ -70,10 +73,10 @@ export class TelegramService {
return
}
- await this.userService.updateUserTelegramId(userId, chatId, true)
+ await this.userService.updateUserTelegramId(userId, null)
}
- async cancelLinkAccount(userId: string) {
+ async confirmUnlinkAccount(chatId: number) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
@@ -81,10 +84,28 @@ export class TelegramService {
return
}
- await this.userService.updateUserTelegramId(userId, null)
+ const user = await this.userService.getUserByTelegramId(chatId)
+ await this.userService.updateUserTelegramId(user.id, null)
}
- async confirmUnlinkAccount(chatId: number) {
+ async addMessage(chatId: string, text: string, extra?: unknown) {
+ await this.messageRepository.save({ chatId, text, extra })
+ }
+
+ async getMessages() {
+ const messagesCount = 25
+ return this.messageRepository.find({
+ take: messagesCount,
+ order: { createdAt: 'DESC' },
+ })
+ }
+
+ async sendMessage(
+ messageId: string,
+ chatId: string,
+ text: string,
+ extra?: unknown,
+ ) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
@@ -92,7 +113,18 @@ export class TelegramService {
return
}
- const user = await this.userService.getUserByTelegramId(chatId)
- await this.userService.updateUserTelegramId(user.id, null)
+ const chat = await this.bot.telegram.getChat(chatId)
+
+ if (!chat) {
+ await this.deleteMessage(messageId)
+ return
+ }
+
+ await this.bot.telegram.sendMessage(chatId, text, extra)
+ await this.deleteMessage(messageId)
+ }
+
+ async deleteMessage(messageId: string) {
+ await this.messageRepository.delete(messageId)
}
}
diff --git a/apps/production/src/task-manager/task-manager.module.ts b/apps/production/src/task-manager/task-manager.module.ts
index 3b9f0fbd1..ea785f378 100644
--- a/apps/production/src/task-manager/task-manager.module.ts
+++ b/apps/production/src/task-manager/task-manager.module.ts
@@ -2,6 +2,7 @@ import { Module, forwardRef } from '@nestjs/common'
import { AlertModule } from 'src/alert/alert.module'
import { ExtensionsModule } from 'src/marketplace/extensions/extensions.module'
import { TelegramService } from 'src/integrations/telegram/telegram.service'
+import { TypeOrmModule } from '@nestjs/typeorm'
import { TaskManagerService } from './task-manager.service'
import { MailerModule } from '../mailer/mailer.module'
import { UserModule } from '../user/user.module'
@@ -9,6 +10,7 @@ import { ProjectModule } from '../project/project.module'
import { AnalyticsModule } from '../analytics/analytics.module'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { AppLoggerModule } from '../logger/logger.module'
+import { Message } from '../integrations/telegram/entities/message.entity'
@Module({
imports: [
@@ -20,6 +22,7 @@ import { AppLoggerModule } from '../logger/logger.module'
forwardRef(() => AnalyticsModule),
ExtensionsModule,
AppLoggerModule,
+ TypeOrmModule.forFeature([Message]),
],
providers: [TaskManagerService, TelegramService],
exports: [TaskManagerService],
diff --git a/apps/production/src/task-manager/task-manager.service.ts b/apps/production/src/task-manager/task-manager.service.ts
index 61deae793..adbf054c7 100644
--- a/apps/production/src/task-manager/task-manager.service.ts
+++ b/apps/production/src/task-manager/task-manager.service.ts
@@ -763,8 +763,8 @@ export class TaskManagerService {
lastTriggered: new Date(),
})
if (project.admin && project.admin.isTelegramChatIdConfirmed) {
- this.telegramService.sendMessage(
- Number(project.admin.telegramChatId),
+ this.telegramService.addMessage(
+ project.admin.telegramChatId,
`๐Ÿ”” Alert *${alert.name}* got triggered!\nYour project *${project.name}* has *${online}* online users right now!`,
{
parse_mode: 'Markdown',
@@ -842,13 +842,9 @@ export class TaskManagerService {
)}!`
if (project.admin && project.admin.isTelegramChatIdConfirmed) {
- this.telegramService.sendMessage(
- Number(project.admin.telegramChatId),
- text,
- {
- parse_mode: 'Markdown',
- },
- )
+ this.telegramService.addMessage(project.admin.telegramChatId, text, {
+ parse_mode: 'Markdown',
+ })
}
}
})
@@ -983,4 +979,24 @@ export class TaskManagerService {
return totalInstalls / extensions.length
}
+
+ @Cron(CronExpression.EVERY_5_SECONDS)
+ async sendTelegramMessages() {
+ try {
+ const messages = await this.telegramService.getMessages()
+
+ messages.forEach(async message => {
+ await this.telegramService.sendMessage(
+ message.id,
+ message.chatId,
+ message.text,
+ message.extra,
+ )
+ })
+ } catch (error) {
+ this.logger.error(
+ `[CRON WORKER](sendTelegramMessages) Error occured: ${error}`,
+ )
+ }
+ }
}
diff --git a/apps/production/src/user/user.controller.ts b/apps/production/src/user/user.controller.ts
index 96f9474c1..1789351a9 100644
--- a/apps/production/src/user/user.controller.ts
+++ b/apps/production/src/user/user.controller.ts
@@ -531,8 +531,8 @@ export class UserController {
isTelegramChatIdConfirmed: false,
})
- this.telegramService.sendMessage(
- Number(userDTO.telegramChatId),
+ this.telegramService.addMessage(
+ userDTO.telegramChatId,
'Please confirm your Telegram chat ID',
Markup.inlineKeyboard([
[
diff --git a/apps/production/src/user/user.module.ts b/apps/production/src/user/user.module.ts
index 8a91cac34..ebc36563a 100644
--- a/apps/production/src/user/user.module.ts
+++ b/apps/production/src/user/user.module.ts
@@ -11,10 +11,11 @@ import { AuthModule } from '../auth/auth.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
import { RefreshToken } from './entities/refresh-token.entity'
+import { Message } from '../integrations/telegram/entities/message.entity'
@Module({
imports: [
- TypeOrmModule.forFeature([User, RefreshToken]),
+ TypeOrmModule.forFeature([User, RefreshToken, Message]),
ActionTokensModule,
MailerModule,
forwardRef(() => AuthModule),
diff --git a/migrations/mysql/2023_07_06.sql b/migrations/mysql/2023_07_06.sql
new file mode 100644
index 000000000..97ee3afa7
--- /dev/null
+++ b/migrations/mysql/2023_07_06.sql
@@ -0,0 +1,8 @@
+CREATE TABLE IF NOT EXISTS `message` (
+ `id` varchar(36) NOT NULL,
+ `chatId` varchar(255) NOT NULL,
+ `text` text NOT NULL,
+ `extra` json DEFAULT NULL,
+ `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+ PRIMARY KEY (`id`)
+)
\ No newline at end of file