1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { telegramValTownBotSecrets } from "https://esm.town/v/stevekrouse/telegramValTownBotSecrets";
import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
import { telegramSendPhoto } from "https://esm.town/v/vtdocs/telegramSendPhoto?v=1";
export let telegramValTownBot = async (req: Request) => {
// Authentication
const bearerString = req.headers.get("authorization");
const token = bearerString?.replace("Bearer ", "");
let chat = telegramValTownBotSecrets.find((c) => c.secret === token);
if (!chat) {
return new Response("Unauthorized", { status: 401 });
}
const url = new URL(req.url);
try {
if (url.pathname === "/text") {
const { text, options } = await req.json();
// TODO validate with Zod
const response = await telegramSendMessage(
Deno.env.get("telegramBot"),
{
...options,
chat_id: chat.chatId,
text,
},
);
return handleTelegramResponse(response);
} else if (url.pathname === "/photo") {
const { options } = await req.json();
console.log(options);
// TODO validate with Zod
const response = await telegramSendPhoto(Deno.env.get("telegramBot"), {
...options,
chat_id: chat.chatId,
});
return handleTelegramResponse(response);
}
return new Response("Not found", { status: 404 });
} catch (e) {
console.log(e);
return new Response("Error sending", { status: 500 });
}
};
function handleTelegramResponse(response) {
console.log(response);
if (response.ok) {
return new Response("OK", { status: 200 });
} else {
return new Response("Error sending: " + response.description, { status: 500 });
}
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.