120 lines
4.6 KiB
TypeScript
120 lines
4.6 KiB
TypeScript
/** Входящее сообщение боту. */
|
||
export interface TelegramMessage {
|
||
updateId: number;
|
||
chatId: number;
|
||
text: string;
|
||
}
|
||
|
||
export interface TelegramClient {
|
||
readonly name: "telegram" | "mock";
|
||
/** Имя бота без @ — для ссылки привязки. */
|
||
readonly botUsername: string;
|
||
sendMessage(chatId: number, text: string): Promise<void>;
|
||
/** Новые сообщения боту после `offset` (id обновления + 1). */
|
||
getUpdates(offset: number): Promise<TelegramMessage[]>;
|
||
}
|
||
|
||
export class TelegramError extends Error {
|
||
constructor(message: string, options?: { cause?: unknown }) {
|
||
super(message, options);
|
||
this.name = "TelegramError";
|
||
}
|
||
}
|
||
|
||
type Fetch = typeof fetch;
|
||
|
||
/** Имя бота в Телеграме: латиница, цифры, «_», 5–32 символа. Ключ бота (с «:») таким не является. */
|
||
export function isPlausibleUsername(name: string): boolean {
|
||
return /^[A-Za-z0-9_]{5,32}$/.test(name);
|
||
}
|
||
|
||
/** Клиент Telegram Bot API. Нужны TELEGRAM_BOT_TOKEN и TELEGRAM_BOT_USERNAME. */
|
||
export class BotApiTelegramClient implements TelegramClient {
|
||
readonly name = "telegram" as const;
|
||
|
||
/** Имя бота без @. Пустое, пока не известно: тогда привязка невозможна. */
|
||
botUsername: string;
|
||
|
||
constructor(
|
||
private readonly token: string,
|
||
botUsername: string,
|
||
private readonly fetchImpl: Fetch = fetch,
|
||
) {
|
||
this.botUsername = isPlausibleUsername(botUsername) ? botUsername : "";
|
||
}
|
||
|
||
/**
|
||
* Спрашивает у Телеграма настоящее имя бота (getMe): так ссылка всегда ведёт на живого бота,
|
||
* даже если в TELEGRAM_BOT_USERNAME внесли не то. Возвращает false, если ключ не подошёл.
|
||
*/
|
||
async resolveUsername(): Promise<boolean> {
|
||
try {
|
||
const me = await this.call<{ username?: string }>("getMe", {});
|
||
if (me.username) this.botUsername = me.username;
|
||
return Boolean(this.botUsername);
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private async call<T>(method: string, body: Record<string, unknown>): Promise<T> {
|
||
let response: Response;
|
||
try {
|
||
response = await this.fetchImpl(`https://api.telegram.org/bot${this.token}/${method}`, {
|
||
method: "POST",
|
||
headers: { "content-type": "application/json" },
|
||
body: JSON.stringify(body),
|
||
});
|
||
} catch (error) {
|
||
// Текст ошибки сети может содержать URL с токеном — не отдаём его наружу.
|
||
throw new TelegramError(`Telegram недоступен (${method})`, { cause: error });
|
||
}
|
||
const data = (await response.json().catch(() => null)) as { ok?: boolean; result?: T; description?: string } | null;
|
||
if (!response.ok || !data?.ok) {
|
||
throw new TelegramError(`Telegram ${method}: ${data?.description ?? `HTTP ${response.status}`}`);
|
||
}
|
||
return data.result as T;
|
||
}
|
||
|
||
async sendMessage(chatId: number, text: string): Promise<void> {
|
||
await this.call("sendMessage", { chat_id: chatId, text, disable_web_page_preview: true });
|
||
}
|
||
|
||
async getUpdates(offset: number): Promise<TelegramMessage[]> {
|
||
const updates = await this.call<Array<{ update_id: number; message?: { chat: { id: number }; text?: string } }>>(
|
||
"getUpdates",
|
||
{ offset, timeout: 0, allowed_updates: ["message"] },
|
||
);
|
||
return updates.flatMap((u) =>
|
||
u.message?.text ? [{ updateId: u.update_id, chatId: u.message.chat.id, text: u.message.text }] : [],
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* МОК Telegram: хранит отправленное в памяти, входящие добавляются через `receive`.
|
||
* Для реальной работы нужны секреты TELEGRAM_BOT_TOKEN и TELEGRAM_BOT_USERNAME.
|
||
*/
|
||
export class MockTelegramClient implements TelegramClient {
|
||
readonly name = "mock" as const;
|
||
readonly sent: Array<{ chatId: number; text: string }> = [];
|
||
failSend = false;
|
||
private updates: TelegramMessage[] = [];
|
||
private nextId = 1;
|
||
|
||
constructor(readonly botUsername = "mock_freetravel_bot") {}
|
||
|
||
async sendMessage(chatId: number, text: string): Promise<void> {
|
||
if (this.failSend) throw new TelegramError("Telegram sendMessage: Forbidden: bot was blocked by the user (мок)");
|
||
this.sent.push({ chatId, text });
|
||
}
|
||
|
||
async getUpdates(offset: number): Promise<TelegramMessage[]> {
|
||
return this.updates.filter((u) => u.updateId >= offset);
|
||
}
|
||
|
||
receive(chatId: number, text: string): void {
|
||
this.updates.push({ updateId: this.nextId++, chatId, text });
|
||
}
|
||
}
|