Files
blog/write/src/lib/bot/tg.ts
T
2026-06-02 00:23:04 +08:00

53 lines
1.2 KiB
TypeScript

import { API, ALLOWED_IDS } from "./config";
interface TgResponse<T = unknown> {
ok: boolean;
result?: T;
description?: string;
}
export async function tg<T = unknown>(
method: string,
body: Record<string, unknown>
): Promise<TgResponse<T>> {
const res = await fetch(`${API}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return res.json() as Promise<TgResponse<T>>;
}
export function allowed(chatId: number): boolean {
if (ALLOWED_IDS.length === 0) return true;
return ALLOWED_IDS.includes(chatId);
}
export async function sendMessage(
chatId: number,
text: string,
opts?: Record<string, unknown>
): Promise<void> {
const safeText = String(text || "");
try {
await tg("sendMessage", {
chat_id: chatId,
text: safeText,
parse_mode: "HTML",
disable_web_page_preview: true,
...opts,
});
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
if (msg.includes("parse") || msg.includes("HTML")) {
await tg("sendMessage", {
chat_id: chatId,
text: safeText,
...opts,
});
} else {
throw e;
}
}
}