30 lines
898 B
TypeScript
30 lines
898 B
TypeScript
export type TelegramUpdate = Record<string, any>;
|
|
|
|
export function telegramApiBase() {
|
|
return process.env.TELEGRAM_API_BASE || "https://api.telegram.org";
|
|
}
|
|
|
|
export function requireTelegramBotToken() {
|
|
const token = process.env.TELEGRAM_BOT_TOKEN;
|
|
if (!token) throw new Error("TELEGRAM_BOT_TOKEN is required");
|
|
return token;
|
|
}
|
|
|
|
export async function telegramBotApi<T>(method: string, body: unknown): Promise<T> {
|
|
const token = requireTelegramBotToken();
|
|
const res = await fetch(`${telegramApiBase()}/bot${token}/${method}`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
|
|
const json = (await res.json().catch(() => null)) as any;
|
|
if (!res.ok || !json?.ok) {
|
|
const desc = json?.description || `HTTP ${res.status}`;
|
|
throw new Error(`Telegram API ${method} failed: ${desc}`);
|
|
}
|
|
|
|
return json.result as T;
|
|
}
|
|
|