103 lines
4.8 KiB
TypeScript
103 lines
4.8 KiB
TypeScript
/** Минимальный контракт Telegram Bot API, нужный боту RCT-3. */
|
||
export interface TgUser { id: number; username?: string; language_code?: string; first_name?: string }
|
||
export interface TgChat { id: number; type: string }
|
||
export interface TgContact { phone_number: string; user_id?: number }
|
||
export interface TgMessage { message_id: number; chat: TgChat; from?: TgUser; text?: string; contact?: TgContact }
|
||
export interface TgCallback { id: string; from: TgUser; data?: string; message?: TgMessage }
|
||
export interface TgUpdate { update_id: number; message?: TgMessage; callback_query?: TgCallback }
|
||
|
||
export interface InlineButton { text: string; callback_data: string }
|
||
export type ReplyMarkup =
|
||
| { inline_keyboard: InlineButton[][] }
|
||
| { keyboard: { text: string; request_contact?: boolean }[][]; resize_keyboard?: boolean; one_time_keyboard?: boolean }
|
||
| { remove_keyboard: true };
|
||
|
||
export class TelegramError extends Error {
|
||
constructor(readonly code: number, description: string) { super(description); }
|
||
}
|
||
|
||
export interface TelegramApi {
|
||
getMe(): Promise<TgUser>;
|
||
getUpdates(offset: number, timeoutSec: number): Promise<TgUpdate[]>;
|
||
sendMessage(chatId: number, text: string, markup?: ReplyMarkup): Promise<void>;
|
||
answerCallbackQuery(id: string): Promise<void>;
|
||
}
|
||
|
||
export class HttpTelegramApi implements TelegramApi {
|
||
constructor(private token: string, private base = "https://api.telegram.org") {}
|
||
|
||
private async call<T>(method: string, body: object, timeoutMs = 15_000): Promise<T> {
|
||
const res = await fetch(`${this.base}/bot${this.token}/${method}`, {
|
||
method: "POST",
|
||
headers: { "content-type": "application/json" },
|
||
body: JSON.stringify(body),
|
||
signal: AbortSignal.timeout(timeoutMs),
|
||
});
|
||
const j = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: T; error_code?: number; description?: string };
|
||
if (!j.ok) throw new TelegramError(j.error_code ?? res.status, j.description ?? `HTTP ${res.status}`);
|
||
return j.result as T;
|
||
}
|
||
|
||
getMe() { return this.call<TgUser>("getMe", {}); }
|
||
getUpdates(offset: number, timeoutSec: number) {
|
||
return this.call<TgUpdate[]>("getUpdates", { offset, timeout: timeoutSec, allowed_updates: ["message", "callback_query"] }, (timeoutSec + 10) * 1000);
|
||
}
|
||
async sendMessage(chatId: number, text: string, markup?: ReplyMarkup) {
|
||
await this.call("sendMessage", { chat_id: chatId, text, ...(markup ? { reply_markup: markup } : {}) });
|
||
}
|
||
async answerCallbackQuery(id: string) { await this.call("answerCallbackQuery", { callback_query_id: id }); }
|
||
}
|
||
|
||
/** Мок Telegram: копит отправленное, отдаёт заранее положенные обновления. */
|
||
export class MockTelegramApi implements TelegramApi {
|
||
readonly sent: { chatId: number; text: string; markup?: ReplyMarkup }[] = [];
|
||
readonly answered: string[] = [];
|
||
queue: (TgUpdate[] | TelegramError)[] = [];
|
||
constructor(readonly username = "mock_intern_bot") {}
|
||
async getMe() { return { id: 1, username: this.username }; }
|
||
async getUpdates(): Promise<TgUpdate[]> {
|
||
const next = this.queue.shift();
|
||
if (next instanceof TelegramError) throw next;
|
||
return next ?? [];
|
||
}
|
||
async sendMessage(chatId: number, text: string, markup?: ReplyMarkup) { this.sent.push({ chatId, text, markup }); }
|
||
async answerCallbackQuery(id: string) { this.answered.push(id); }
|
||
}
|
||
|
||
export interface PollOptions {
|
||
onUpdate(u: TgUpdate): Promise<void>;
|
||
signal?: AbortSignal;
|
||
timeoutSec?: number;
|
||
sleep?: (ms: number) => Promise<void>;
|
||
log?: (msg: string) => void;
|
||
}
|
||
|
||
/**
|
||
* Long polling. 409 (бот опрашивает другая версия) и сетевые ошибки не роняют приложение:
|
||
* ждём и повторяем. Ошибка в обработке одного обновления не блокирует остальные.
|
||
*/
|
||
export async function pollUpdates(api: TelegramApi, o: PollOptions): Promise<void> {
|
||
const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
||
const log = o.log ?? ((m) => console.warn(m));
|
||
let offset = 0;
|
||
while (!o.signal?.aborted) {
|
||
let updates: TgUpdate[];
|
||
try {
|
||
updates = await api.getUpdates(offset, o.timeoutSec ?? 25);
|
||
} catch (e) {
|
||
const conflict = e instanceof TelegramError && e.code === 409;
|
||
log(conflict ? "telegram: бота опрашивает другая версия (409), повтор через 30 с" : `telegram: ошибка опроса: ${(e as Error).message}`);
|
||
await sleep(conflict ? 30_000 : 5_000);
|
||
continue;
|
||
}
|
||
for (const u of updates) {
|
||
offset = Math.max(offset, u.update_id + 1);
|
||
try {
|
||
await o.onUpdate(u);
|
||
} catch (e) {
|
||
log(`telegram: ошибка обработки ${u.update_id}: ${(e as Error).message}`);
|
||
}
|
||
}
|
||
}
|
||
}
|