π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
import { forwardRef, Inject, Injectable, Optional } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { Markup } from 'telegraf'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { Message } from './entities/message.entity'
import { UserService } from '../../user/user.service'
import type { Convenience } from 'telegraf/types'
import { NotificationChannelService } from '../../notification-channel/notification-channel.service'
@Injectable()
export class TelegramService {
constructor(
private readonly userService: UserService,
private readonly configService: ConfigService,
@InjectRepository(Message)
private readonly messageRepository: Repository<Message>,
@Optional()
@Inject(forwardRef(() => NotificationChannelService))
private readonly notificationChannelService?: NotificationChannelService,
) {}
async getStartMessage(telegramId: number) {
const user = await this.userService.getUserByTelegramId(
telegramId.toString(),
)
let text = ''
let extra: Convenience.ExtraReplyMessage = {}
if (!user) {
text =
'Welcome to the Swetrix Bot!' +
'\n\n' +
'Your Telegram ID is: ' +
`<code>${telegramId.toString()}</code>` +
'\n\n' +
'You can use this ID to link your Telegram account with your Swetrix account.' +
'\n\n' +
'To do this, go to your <a href="https://swetrix.com/settings">Swetrix account settings</a> and enter this ID in the Telegram field.' +
'\n\n' +
'After that, you can use the bot to manage your projects.'
extra = {
// @ts-expect-error It's not typed
disable_web_page_preview: true,
reply_markup: { remove_keyboard: true },
}
}
if (user) {
text = 'Welcome to the Swetrix Bot!'
extra = {
...Markup.keyboard([['π Projects', 'βοΈ Settings']])
.oneTime()
.resize(),
}
}
return { text, extra }
}
async confirmLinkAccount(userId: string, chatId: number) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
) {
return
}
// Ensure the confirming Telegram user matches the pending chat ID on the user.
// This prevents confirming from a different chat/user if callback data ever leaks.
const user = await this.userService.findOne({ where: { id: userId } })
if (
!user ||
user.isTelegramChatIdConfirmed ||
user.telegramChatId !== String(chatId)
) {
return
}
await this.userService.updateUserTelegramId(userId, chatId, true)
await this.getNotificationChannelService().upsertTelegramChannel(
userId,
String(chatId),
)
}
async cancelLinkAccount(userId: string, chatId: number) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
) {
return
}
const user = await this.userService.findOne({ where: { id: userId } })
if (!user || user.isTelegramChatIdConfirmed) {
return
}
// Only allow cancelling if the pending chat ID matches the current chat.
if (user.telegramChatId !== String(chatId)) {
return
}
await this.userService.updateUserTelegramId(userId, null)
}
async confirmUnlinkAccount(chatId: number) {
if (
this.configService.get<string>('ENABLE_INTEGRATIONS') !== 'true' &&
this.configService.get<string>('ENABLE_TELEGRAM_INTEGRATION') !== 'true'
) {
return
}
const user = await this.userService.getUserByTelegramId(chatId.toString())
if (!user) {
return
}
await this.getNotificationChannelService().deleteTelegramChannelsByChatId(
chatId.toString(),
user.id,
)
await this.userService.updateUserTelegramId(user.id, null)
}
private getNotificationChannelService() {
if (!this.notificationChannelService) {
throw new Error('NotificationChannelService is not available')
}
return this.notificationChannelService
}
async addMessage(
chatId: string,
text: string,
extra?: Convenience.ExtraReplyMessage,
) {
await this.messageRepository.save({ chatId, text, extra })
}
escapeTelegramMarkdownV2(text?: string | null) {
if (text === null || text === undefined) return ''
// Characters to escape for MarkdownV2: _ * [ ] ( ) ~ ` > # + - = | { } . ! and \ (not requested by Telegram, but CodeQL is complaining)
const charsToEscapeRegex = /[_*[\]()~`>#+\-=|{}.!\\]/g
return text.replace(charsToEscapeRegex, '\\$&')
}
escapeTelegramMarkdown(text?: string | null) {
if (text === null || text === undefined) return ''
// Characters to escape for legacy Markdown: _, *, `, [, \
const charsToEscapeRegex = /[_*`[\]\\]/g
return text.replace(charsToEscapeRegex, '\\$&')
}
}