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!

fix: Telegram integration connector

Blue Mousec9d1bdca0dae
diff --git a/backend/apps/cloud/src/integrations/telegram/entities/message.entity.ts b/backend/apps/cloud/src/integrations/telegram/entities/message.entity.ts
index 8494ca9da..f27911e2f 100644
--- a/backend/apps/cloud/src/integrations/telegram/entities/message.entity.ts
+++ b/backend/apps/cloud/src/integrations/telegram/entities/message.entity.ts
@@ -1,3 +1,4 @@
+import type { Convenience } from 'telegraf/types'
import {
Column,
CreateDateColumn,
@@ -17,7 +18,7 @@ export class Message {
text: string
@Column('json', { nullable: true, default: null })
- extra: unknown | null
+ extra: Convenience.ExtraReplyMessage | null
@CreateDateColumn()
createdAt: Date
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram-message.worker.spec.ts b/backend/apps/cloud/src/integrations/telegram/telegram-message.worker.spec.ts
new file mode 100644
index 000000000..0271105c5
--- /dev/null
+++ b/backend/apps/cloud/src/integrations/telegram/telegram-message.worker.spec.ts
@@ -0,0 +1,86 @@
+import { Telegraf, TelegramError } from 'telegraf'
+import { Repository } from 'typeorm'
+import { Message } from './entities/message.entity'
+import { TelegramMessageWorker } from './telegram-message.worker'
+
+describe('Telegram message delivery', () => {
+ const message = {
+ id: 'message-id',
+ chatId: 'chat-id',
+ text: 'An alert fired',
+ extra: { parse_mode: 'Markdown' },
+ }
+ const sendMessage = jest.fn()
+ const messages = { find: jest.fn(), delete: jest.fn() }
+ let worker: TelegramMessageWorker
+
+ beforeEach(() => {
+ jest.resetAllMocks()
+ messages.find.mockResolvedValue([message])
+ worker = new TelegramMessageWorker(
+ { telegram: { sendMessage } } as unknown as Telegraf,
+ messages as unknown as Repository<Message>,
+ )
+ })
+
+ it('sends queued alerts with their saved options before removing them', async () => {
+ sendMessage.mockImplementationOnce(async () => {
+ expect(messages.delete).not.toHaveBeenCalled()
+ })
+ await worker.sendQueuedMessages()
+ expect(sendMessage).toHaveBeenCalledWith(
+ message.chatId,
+ message.text,
+ message.extra,
+ )
+ expect(messages.delete).toHaveBeenCalledWith(message.id)
+ })
+
+ it.each([
+ new Error('Network unavailable'),
+ new TelegramError({ error_code: 502, description: 'Bad gateway' }),
+ new TelegramError({ error_code: 401, description: 'Unauthorized' }),
+ ])('retains the alert after %s and delivers it on retry', async (error) => {
+ sendMessage.mockRejectedValueOnce(error)
+ await worker.sendQueuedMessages()
+ expect(messages.delete).not.toHaveBeenCalled()
+ await worker.sendQueuedMessages()
+ expect(messages.delete).toHaveBeenCalledWith(message.id)
+ })
+
+ it('respects Telegram’s retry interval', async () => {
+ jest.useFakeTimers()
+ try {
+ sendMessage.mockRejectedValueOnce(
+ new TelegramError({
+ error_code: 429,
+ description: 'Too many requests',
+ parameters: { retry_after: 30 },
+ }),
+ )
+ await worker.sendQueuedMessages()
+ jest.advanceTimersByTime(29000)
+ await worker.sendQueuedMessages()
+ expect(sendMessage).toHaveBeenCalledTimes(1)
+ expect(messages.delete).not.toHaveBeenCalled()
+ jest.advanceTimersByTime(1000)
+ await worker.sendQueuedMessages()
+ expect(messages.delete).toHaveBeenCalledWith(message.id)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it.each([400, 403])(
+ 'continues past a permanently rejected alert (%i)',
+ async (code) => {
+ messages.find.mockResolvedValue([message, { ...message, id: 'next' }])
+ sendMessage.mockRejectedValueOnce(
+ new TelegramError({ error_code: code, description: 'Rejected' }),
+ )
+ await worker.sendQueuedMessages()
+ expect(sendMessage).toHaveBeenCalledTimes(2)
+ expect(messages.delete.mock.calls).toEqual([[message.id], ['next']])
+ },
+ )
+})
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram-message.worker.ts b/backend/apps/cloud/src/integrations/telegram/telegram-message.worker.ts
new file mode 100644
index 000000000..74a54ac73
--- /dev/null
+++ b/backend/apps/cloud/src/integrations/telegram/telegram-message.worker.ts
@@ -0,0 +1,53 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { Cron, CronExpression } from '@nestjs/schedule'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Telegraf, TelegramError } from 'telegraf'
+import { Repository } from 'typeorm'
+import { Message } from './entities/message.entity'
+
+@Injectable()
+export class TelegramMessageWorker {
+ private readonly logger = new Logger(TelegramMessageWorker.name)
+ private retryAfter = 0
+
+ constructor(
+ private readonly bot: Telegraf,
+ @InjectRepository(Message)
+ private readonly messages: Repository<Message>,
+ ) {}
+
+ @Cron(CronExpression.EVERY_5_SECONDS, { waitForCompletion: true })
+ async sendQueuedMessages() {
+ if (Date.now() < this.retryAfter) return
+
+ const messages = await this.messages.find({
+ take: 25,
+ order: { createdAt: 'ASC', id: 'ASC' },
+ })
+ for (const message of messages) {
+ try {
+ await this.bot.telegram.sendMessage(
+ message.chatId,
+ message.text,
+ message.extra ?? undefined,
+ )
+ } catch (error) {
+ if (!(error instanceof TelegramError)) {
+ this.logger.warn(
+ `Telegram request failed for message ${message.id}. Will retry.`,
+ )
+ return
+ }
+ this.logger.warn(
+ `Telegram rejected message ${message.id}: ${error.message}`,
+ )
+ if (error.code === 429) {
+ this.retryAfter =
+ Date.now() + (error.parameters?.retry_after ?? 5) * 1000
+ }
+ if (error.code !== 400 && error.code !== 403) return
+ }
+ await this.messages.delete(message.id)
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts b/backend/apps/cloud/src/integrations/telegram/telegram.module.ts
index 963a3420b..396001b13 100644
--- a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts
+++ b/backend/apps/cloud/src/integrations/telegram/telegram.module.ts
@@ -10,6 +10,7 @@ import {
import { ConfigService } from '@nestjs/config'
import { Telegraf } from 'telegraf'
import { TypeOrmModule } from '@nestjs/typeorm'
+import { TelegramMessageWorker } from './telegram-message.worker'
import { TelegramUpdate } from './telegram.update'
import { StartScene } from './scene/start.scene'
import { ProjectsScene } from './scene/projects.scene'
@@ -47,6 +48,7 @@ const hasTelegramToken = !!process.env.TELEGRAM_BOT_TOKEN
configService.get<string>('TELEGRAM_BOT_TOKEN'),
),
},
+ TelegramMessageWorker,
TelegramUpdate,
StartScene,
ProjectsScene,
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts b/backend/apps/cloud/src/integrations/telegram/telegram.service.ts
index da694742e..56f4c42ac 100644
--- a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts
+++ b/backend/apps/cloud/src/integrations/telegram/telegram.service.ts
@@ -1,9 +1,8 @@
import { forwardRef, Inject, Injectable, Optional } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
-import { Markup, Telegraf } from 'telegraf'
+import { Markup } from 'telegraf'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
-import { Context } from './interface/context.interface'
import { Message } from './entities/message.entity'
import { UserService } from '../../user/user.service'
import type { Convenience } from 'telegraf/types'
@@ -12,7 +11,6 @@ import { NotificationChannelService } from '../../notification-channel/notificat
@Injectable()
export class TelegramService {
constructor(
- @Optional() @Inject(Telegraf) private readonly bot: Telegraf<Context>,
private readonly userService: UserService,
private readonly configService: ConfigService,
@InjectRepository(Message)
@@ -142,14 +140,6 @@ export class TelegramService {
await this.messageRepository.save({ chatId, text, extra })
}
- async getMessages() {
- const messagesCount = 25
- return this.messageRepository.find({
- take: messagesCount,
- order: { createdAt: 'DESC' },
- })
- }
-
escapeTelegramMarkdownV2(text?: string | null) {
if (text === null || text === undefined) return ''
@@ -165,38 +155,4 @@ export class TelegramService {
const charsToEscapeRegex = /[_*`[\]\\]/g
return text.replace(charsToEscapeRegex, '\\$&')
}
-
- async sendMessage(
- messageId: string,
- chatId: string,
- text: string,
- extra?: Convenience.ExtraReplyMessage,
- ) {
- if (
- this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
- this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
- ) {
- return
- }
-
- // If the bot isn't launched on this node (e.g. non-primary instance),
- // do nothing here and let the primary node handle queued messages.
- if (!this.bot) {
- return
- }
-
- 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/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts b/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts
index b37ae2c1e..707f77c06 100644
--- a/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts
@@ -1,4 +1,10 @@
-import { Injectable, Logger, Optional } from '@nestjs/common'
+import {
+ forwardRef,
+ Inject,
+ Injectable,
+ Logger,
+ Optional,
+} from '@nestjs/common'
import { TelegramService } from '../../integrations/telegram/telegram.service'
import {
NotificationChannel,
@@ -13,7 +19,9 @@ export class TelegramChannelService implements ChannelDispatcher {
private readonly logger = new Logger(TelegramChannelService.name)
constructor(
- @Optional() private readonly telegramService: TelegramService | null,
+ @Optional()
+ @Inject(forwardRef(() => TelegramService))
+ private readonly telegramService?: TelegramService,
) {}
async send(
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index 85f6cb610..347802389 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -61,11 +61,7 @@ import {
REPEATED_OVERAGE_ALLOWED_PERCENTAGE,
TRAFFIC_SPIKE_ALLOWED_PERCENTAGE,
} from '../user/plan-usage'
-import {
- getRandomTip,
- isPrimaryClusterNode,
- isPrimaryNode,
-} from '../common/utils'
+import { getRandomTip, isPrimaryNode } from '../common/utils'
import { AppLoggerService } from '../logger/logger.service'
import { DiscordService } from '../integrations/discord/discord.service'
import { SlackService } from '../integrations/slack/slack.service'
@@ -1936,42 +1932,6 @@ export class TaskManagerService {
}
}
- @Cron(CronExpression.EVERY_5_SECONDS)
- async sendTelegramMessages() {
- try {
- // Only one instance should process Telegram message queue; otherwise messages
- // may be deleted by nodes that don't have the bot launched.
- if (!(isPrimaryNode() && isPrimaryClusterNode())) {
- return
- }
-
- const messages = await this.telegramService.getMessages()
-
- const promises = messages.map(async (message) => {
- try {
- await this.telegramService.sendMessage(
- message.id,
- message.chatId,
- message.text,
- message.extra,
- )
- } catch (reason) {
- this.logger.error(
- `[CRON WORKER](sendTelegramMessages) Error occured while sending message: ${reason}`,
- )
- } finally {
- await this.telegramService.deleteMessage(message.id)
- }
- })
-
- await Promise.allSettled(promises)
- } catch (error) {
- this.logger.error(
- `[CRON WORKER](sendTelegramMessages) Error occured: ${error}`,
- )
- }
- }
-
// Disable reports for inactive users
// Some people stop using Swetrix but keep the account (and don't disable the email reports in settings), so why keep spamming them?
// EVERY SUNDAY AT 2:00 AM (right before we send weekly reports)