124 lines
3.4 KiB
TypeScript
124 lines
3.4 KiB
TypeScript
/** Telegram Bot API: тонкий клиент на fetch (в тестах — mockTelegram). */
|
|
import type { FetchFn } from "./google.ts";
|
|
|
|
export class TelegramError extends Error {
|
|
code: number;
|
|
constructor(code: number, message: string) {
|
|
super(message);
|
|
this.code = code;
|
|
}
|
|
}
|
|
|
|
export interface TgUser {
|
|
id: number;
|
|
first_name?: string;
|
|
last_name?: string;
|
|
username?: string;
|
|
}
|
|
|
|
export interface TgMessage {
|
|
message_id: number;
|
|
date: number;
|
|
chat: {
|
|
id: number;
|
|
type: "private" | "group" | "supergroup" | "channel";
|
|
title?: string;
|
|
username?: string;
|
|
};
|
|
from?: TgUser;
|
|
text?: string;
|
|
caption?: string;
|
|
forward_origin?: {
|
|
type: string;
|
|
sender_user?: TgUser;
|
|
sender_user_name?: string;
|
|
chat?: { title?: string };
|
|
};
|
|
}
|
|
|
|
export interface TgUpdate {
|
|
update_id: number;
|
|
message?: TgMessage;
|
|
callback_query?: { id: string; from: TgUser; data?: string; message?: TgMessage };
|
|
}
|
|
|
|
export interface InlineButton {
|
|
text: string;
|
|
callback_data?: string;
|
|
url?: string;
|
|
}
|
|
|
|
export class TelegramClient {
|
|
private token: string;
|
|
private fetchFn: FetchFn;
|
|
|
|
constructor(token: string, fetchFn: FetchFn = fetch) {
|
|
this.token = token;
|
|
this.fetchFn = fetchFn;
|
|
}
|
|
|
|
async call<T>(method: string, params: Record<string, unknown> = {}, signal?: AbortSignal): Promise<T> {
|
|
const res = await this.fetchFn(`https://api.telegram.org/bot${this.token}/${method}`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(params),
|
|
signal,
|
|
});
|
|
const body = (await res
|
|
.json()
|
|
.catch(() => ({ ok: false, error_code: res.status, description: "bad response" }))) as {
|
|
ok: boolean;
|
|
result?: T;
|
|
error_code?: number;
|
|
description?: string;
|
|
};
|
|
if (!body.ok)
|
|
throw new TelegramError(body.error_code ?? res.status, body.description ?? "telegram error");
|
|
return body.result as T;
|
|
}
|
|
|
|
getMe(): Promise<TgUser> {
|
|
return this.call("getMe");
|
|
}
|
|
|
|
getWebhookInfo(): Promise<{ url: string }> {
|
|
return this.call("getWebhookInfo");
|
|
}
|
|
|
|
getUpdates(offset: number | undefined, timeout: number, signal?: AbortSignal): Promise<TgUpdate[]> {
|
|
return this.call(
|
|
"getUpdates",
|
|
{ offset, timeout, allowed_updates: ["message", "callback_query"] },
|
|
signal,
|
|
);
|
|
}
|
|
|
|
sendMessage(chatId: number | string, text: string, buttons?: InlineButton[][]): Promise<TgMessage> {
|
|
return this.call("sendMessage", {
|
|
chat_id: chatId,
|
|
text,
|
|
link_preview_options: { is_disabled: true },
|
|
...(buttons ? { reply_markup: { inline_keyboard: buttons } } : {}),
|
|
});
|
|
}
|
|
|
|
answerCallback(id: string, text?: string): Promise<boolean> {
|
|
return this.call("answerCallbackQuery", { callback_query_id: id, text });
|
|
}
|
|
}
|
|
|
|
/** Ссылка на сообщение: для супергрупп — t.me/c/…, для остальных ссылки нет. */
|
|
export function messageLink(m: TgMessage): string | undefined {
|
|
if (m.chat.type === "supergroup" || m.chat.type === "channel") {
|
|
if (m.chat.username) return `https://t.me/${m.chat.username}/${m.message_id}`;
|
|
const id = String(m.chat.id).replace(/^-100/, "");
|
|
return `https://t.me/c/${id}/${m.message_id}`;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
export function userName(u?: TgUser): string | undefined {
|
|
if (!u) return undefined;
|
|
return [u.first_name, u.last_name].filter(Boolean).join(" ") || u.username;
|
|
}
|