import { blob } from "https://esm.town/v/std/blob";
import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
import process from "node:process";
const DB_KEY = "telegram_Chotillo";
const LS = "/ls";
const X = "/x";
const X_ = X + " ";
const initBlob = async () => {
let exist = await blob.getJSON(DB_KEY);
if (!exist) {
await blob.setJSON(DB_KEY, []);
exist = [];
}
return exist;
};
const send = async (chatId: number, msg: string) => {
await telegramSendMessage(
process.env.telegramBotToken,
{ chat_id: chatId, text: msg },
);
};
export const telegramWebhookEchoMessage = async (req: Request) => {
const db: string[] = await initBlob();
if (
req.headers.get("x-telegram-bot-api-secret-token")
!== process.env.telegramWebhookSecret
) {
return new Response(undefined, { status: 401 });
}
const body = await req.json();
const text: string = body.message.text;
const chatId: number = body.message.chat.id;
if (text.startsWith(LS)) {
await send(chatId, db.join("\n"));
return Response.json("ok");
}
if (!text.startsWith(X_)) {
return Response.json("ok");
}
const cmd = text.split(X_)[1];
await blob.setJSON(DB_KEY, [...db, cmd]);
await send(chatId, `Processed ${cmd.length} bytes!`);
return Response.json("ok");
};