peppa/apps/bot/src/telegram.ts

167 lines
6.2 KiB
TypeScript

import { m as tr } from "@peppa/shared/i18n";
// Minimal Telegram Bot API client. The base URL is configurable so tests can point it at
// mock-telegram (packages/testkit).
export interface TgUser {
id: number;
username?: string;
first_name?: string;
}
export interface TgMessage {
message_id: number;
chat: { id: number; type: string; title?: string };
from?: TgUser;
text?: string;
/** PEP-62: a group became a supergroup (new chat id). */
migrate_to_chat_id?: number;
reply_to_message?: TgMessage;
/** PEP-45: voice notes and audio files become stories after transcription. */
voice?: TgFileRef;
audio?: TgFileRef;
/** PEP-143: a photo comes as several sizes (the last is the largest); its text is the caption. */
photo?: TgFileRef[];
/** An image sent «as a file». */
document?: TgFileRef & { file_name?: string };
caption?: string;
/** Messages of one album share it. */
media_group_id?: string;
}
export interface TgFileRef {
file_id: string;
duration?: number;
mime_type?: string;
file_size?: number;
}
export interface TgCallbackQuery {
id: string;
from: TgUser;
message?: TgMessage;
data?: string;
}
export interface TgUpdate {
update_id: number;
message?: TgMessage;
callback_query?: TgCallbackQuery;
}
export interface InlineButton {
text: string;
callback_data?: string;
url?: string;
}
const TG_TEXT_MAX = 4096;
const TG_CLIP_NOTE_TEXT = tr("(полностью — на сайте Peppa FACTORY)");
const TG_CLIP_NOTE = "\n\n… " + TG_CLIP_NOTE_TEXT;
/** PEP-180: a text that fits Telegram — cut at the last line break before the limit. */
export function clipForTelegram(text: string): string {
if (text.length <= TG_TEXT_MAX) return text;
const room = TG_TEXT_MAX - TG_CLIP_NOTE.length;
const cut = text.lastIndexOf("\n", room);
return `${text.slice(0, cut > room / 2 ? cut : room)}${TG_CLIP_NOTE}`;
}
export class TelegramError extends Error {
readonly method: string;
readonly code: number;
readonly description: string;
readonly retryAfter?: number;
constructor(method: string, code: number, description: string, retryAfter?: number) {
super(`${method}: ${code} ${description}`);
this.method = method;
this.code = code;
this.description = description;
this.retryAfter = retryAfter;
}
}
export class TelegramApi {
private readonly token: string;
private readonly baseUrl: string;
constructor(token: string, baseUrl = "https://api.telegram.org") {
this.token = token;
this.baseUrl = baseUrl;
}
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
// PEP-180: Telegram refuses texts over 4096 characters — a long message goes shortened (cut at a
// line break, so no HTML tag is left open), with a note that the whole text is on the site.
if ((method === "sendMessage" || method === "editMessageText") && typeof params.text === "string" && params.text.length > TG_TEXT_MAX) {
params = { ...params, text: clipForTelegram(params.text) };
}
let res: Response;
try {
res = await fetch(`${this.baseUrl}/bot${this.token}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
throw new TelegramError(method, 0, (e as Error).message);
}
const body = (await res.json().catch(() => ({}))) as {
ok?: boolean;
result?: T;
description?: string;
error_code?: number;
parameters?: { retry_after?: number };
};
if (!body.ok) {
throw new TelegramError(method, body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after);
}
return body.result as T;
}
getMe() {
return this.call<TgUser>("getMe");
}
getUpdates(offset: number, timeoutSec: number, signal?: AbortSignal) {
return this.call<TgUpdate[]>(
"getUpdates",
{ offset, timeout: timeoutSec, allowed_updates: ["message", "callback_query"] },
(timeoutSec + 10) * 1000,
).catch((e) => {
if (signal?.aborted) return [];
throw e;
});
}
answerCallbackQuery(id: string, text?: string) {
return this.call<boolean>("answerCallbackQuery", { callback_query_id: id, text });
}
getFile(fileId: string) {
return this.call<{ file_id: string; file_path?: string; file_size?: number }>("getFile", { file_id: fileId });
}
/** Bytes of a file from getFile (Bot API: GET /file/bot<token>/<file_path>, up to 20 MB). */
async downloadFile(filePath: string): Promise<Buffer> {
const res = await fetch(`${this.baseUrl}/file/bot${this.token}/${filePath}`, { signal: AbortSignal.timeout(60_000) });
if (!res.ok) throw new TelegramError("downloadFile", res.status, res.statusText);
return Buffer.from(await res.arrayBuffer());
}
/** PEP-143: a photo uploaded from memory (multipart/form-data, as the Bot API wants for new files). */
async sendPhoto(chatId: number, photo: { data: Uint8Array; filename: string; mime: string }, extra: Record<string, unknown> = {}): Promise<TgMessage> {
const form = new FormData();
form.set("chat_id", String(chatId));
for (const [k, v] of Object.entries(extra)) if (v != null && k !== "chat_id") form.set(k, typeof v === "string" ? v : JSON.stringify(v));
form.set("photo", new Blob([photo.data as BlobPart], { type: photo.mime }), photo.filename);
let res: Response;
try {
res = await fetch(`${this.baseUrl}/bot${this.token}/sendPhoto`, { method: "POST", body: form, signal: AbortSignal.timeout(60_000) });
} catch (e) {
throw new TelegramError("sendPhoto", 0, (e as Error).message);
}
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: TgMessage; description?: string; error_code?: number; parameters?: { retry_after?: number } };
if (!body.ok) throw new TelegramError("sendPhoto", body.error_code ?? res.status, body.description ?? res.statusText, body.parameters?.retry_after);
return body.result as TgMessage;
}
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
}
}