All files / src/services sendViaTelegram.ts

43.9% Statements 18/41
100% Branches 0/0
0% Functions 0/2
43.9% Lines 18/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                       1x 1x                        
 
 
process.env.NTBA_FIX_319 = 1 as any // prevent telegram lib promise error log shall be before the lib import
 
import TelegramBot from 'node-telegram-bot-api'
import { GreenDotAppConfig } from '../types/appConfig.types'
import { getActiveAppConfig } from '../helpers/getGreenDotConfigs'
import { capitalize1st } from 'topkat-utils'
 
 
let telegramBot
let sendOnErrorCodeGlob: GreenDotAppConfig['alerts']['telegram']['sendOnErrorCode']
let errorChatId: GreenDotAppConfig['alerts']['telegram']['chatId']
let appNameGlob: string
 
export async function initTelegramBot() {

    const { alerts, name } = await getActiveAppConfig(true) || {}

    if (alerts && alerts.telegram && alerts.telegram.enable) {
        const { botId, chatId, sendOnErrorCode } = alerts.telegram
        telegramBot = new TelegramBot(botId)
        errorChatId = chatId
        appNameGlob = name
        sendOnErrorCodeGlob = sendOnErrorCode || (code => code === 500)
    }
}
 
export async function sendErrorViaTelegram(code, msg: string, extraInfos: string) {
    if (errorChatId && sendOnErrorCodeGlob(code)) {
        await telegramBot.sendMessage(
            errorChatId,
            `<b>${capitalize1st(appNameGlob)} App => error ${code}: ${msg}</b>\n<code>${extraInfos
                .replace(/.*\n/, '') // first line
                // eslint-disable-next-line no-control-regex
                .replace(/\u001b\[[012345]m/g, '') // removecli code coloration
            }</code>`,
            { parse_mode: 'HTML' }
        )
    }
}