feat(api, web): тест Telegram из формы, подсказки ошибок API и UX настроек
Docker / build (push) Has been cancelled

Тест отправки использует значения формы без предварительного сохранения; пустой токен при сохранении не затирает сохранённый. Добавлены подсказки по частым ошибкам Telegram API и колонка ошибок в журнале уведомлений.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Denozordec
2026-06-29 00:54:51 +07:00
co-authored by Cursor
parent 7f91bc3624
commit 05e7bf829e
13 changed files with 319 additions and 72 deletions
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { formatTelegramApiError, telegramErrorHint } from './telegram.js'
describe('telegramErrorHint', () => {
it('maps thread not found', () => {
expect(telegramErrorHint('Bad Request: message thread not found')).toContain('Thread ID')
})
it('maps chat not found', () => {
expect(telegramErrorHint('Bad Request: chat not found')).toContain('Chat ID')
})
it('returns null for unknown errors', () => {
expect(telegramErrorHint('Something else')).toBeNull()
})
})
describe('formatTelegramApiError', () => {
it('includes hint for known telegram description', () => {
const msg = formatTelegramApiError(
'-1001',
{ status: 400, statusText: 'Bad Request' },
{ ok: false, description: 'Bad Request: message thread not found' },
)
expect(msg).toContain('message thread not found')
expect(msg).toContain('Thread ID')
})
it('falls back to raw body when JSON has no description', () => {
const msg = formatTelegramApiError(
'-1001',
{ status: 400, statusText: 'Bad Request' },
{},
'invalid payload',
)
expect(msg).toBe('-1001: invalid payload')
})
})
+52 -3
View File
@@ -7,6 +7,49 @@ export interface TelegramSendResult {
error?: string
}
interface TelegramApiResponse {
ok?: boolean
description?: string
error_code?: number
}
/** Маппинг частых ошибок Telegram API на подсказки (для тестов и UI). */
export function telegramErrorHint(description: string): string | null {
const d = description.toLowerCase()
if (d.includes('message thread not found')) {
return 'Проверьте Thread ID и что в группе включены топики'
}
if (d.includes('chat not found')) {
return 'Бот не добавлен в чат или неверный Chat ID'
}
if (d.includes('not enough rights')) {
return 'Дайте боту право отправлять сообщения (администратор в группе)'
}
if (d.includes('unauthorized')) {
return 'Неверный токен бота'
}
if (d.includes('bot was blocked')) {
return 'Пользователь заблокировал бота'
}
return null
}
export function formatTelegramApiError(
chatId: string,
res: Pick<Response, 'status' | 'statusText'>,
data: TelegramApiResponse,
rawBody?: string,
): string {
const description = data.description?.trim()
if (description) {
const hint = telegramErrorHint(description)
return hint ? `${chatId}: ${description}${hint}` : `${chatId}: ${description}`
}
const snippet = rawBody?.trim().slice(0, 200)
const fallback = snippet || res.statusText || `HTTP ${res.status}`
return `${chatId}: ${fallback}`
}
export async function sendTelegramMessage(
token: string,
chatIds: string | string[],
@@ -43,12 +86,18 @@ export async function sendTelegramMessage(
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...payload, chat_id: chatId }),
})
const data = (await res.json().catch(() => ({}))) as { ok?: boolean; description?: string }
const rawBody = await res.text()
let data: TelegramApiResponse = {}
try {
data = JSON.parse(rawBody) as TelegramApiResponse
} catch {
/* non-JSON body */
}
if (data.ok) {
anyOk = true
} else {
const err = data.description || res.statusText || 'Unknown error'
errors.push(`${chatId}: ${err}`)
const err = formatTelegramApiError(chatId, res, data, rawBody)
errors.push(err)
console.warn(`Telegram sendMessage failed for chat ${chatId}:`, err)
}
} catch (err) {