125 lines
3.7 KiB
TypeScript
125 lines
3.7 KiB
TypeScript
// 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;
|
|
}
|
|
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;
|
|
}
|
|
|
|
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> {
|
|
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());
|
|
}
|
|
|
|
sendMessage(chatId: number, text: string, extra: Record<string, unknown> = {}) {
|
|
return this.call<TgMessage>("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra });
|
|
}
|
|
}
|